Error after pressing the "Play" button

Asked by ehsan benabbas

Hi everyone,

I am using Ubuntu 18.04, and Yade 2019-08-08.git-775ae74

I use the Triaxial code by Bruno Chareyre [1] to run triaxial simulation on my specimen and only made the following changes in [1]:

num_spheres=20000,
targetPorosity = 0.4
young=200000000
poisson=1
mn,mx=Vector3(0,0,0),Vector3(0.02,0.02,0.02)
sigmaIso=-500000
particleDensity=2000
O.materials.append(FrictMat(young=young,poisson=poisson,frictionAngle=radians(compFricDegree),density=particleDensity,label='spheres'))
from yade import pack
sp=pack.SpherePack()
clumps=False
volume = (mx[0]-mn[0])*(mx[1]-mn[1])*(mx[2]-mn[2])
sp.makeCloud(mn,mx,0.0002,0.5,num_spheres,False, 0.95,seed=1)
O.bodies.append([sphere(center,rad,material='spheres') for center,rad in sp])
triax.goal1 = sigmaIso
triax.goal2 = sigmaIso
triax.goal3 = sigmaIso
f unb<stabilityThreshold and abs(sigmaIso-triax.meanStress)/sigmaIso<0.001:
triax.goal1 = sigmaIso
triax.goal2 = rate
triax.goal3 = sigmaIso

[1] https://gitlab.com/yade-dev/trunk/blob/master/examples/triax-tutorial/script-session1.py

***********************************************

The code can be run up to opening 3 windows (plot, show3D,remote) and I get the "END" message on the screen successfully. My problem is that when I press the "Play" button, nothing happens and then I get the following error:

============ RECORD AND PLOT DATA ============
/home/ehsan/yade/install/lib/x86_64-linux-gnu/yade-2019-08-08.git-775ae74/py/yade/plot.py:444: MatplotlibDeprecationWarning:
The 'verts' kwarg was deprecated in Matplotlib 3.0 and will be removed in 3.2. Use 'marker' instead.
  scatter=pylab.scatter(scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0,s=scatterSize,color=line.get_color(),**scatterMarkerKw)
************** END **************
Analysis has been taken for 987.977 seconds or 16.466283333333333 minutes
[[ ^L clears screen, ^U kills line. F12 controller, F11 3D view (press "h" in 3D view for help), F10 both, F9 generator, F8 plot. ]]

Unhandled exception in thread started by <function liveUpdate at 0x7f3808480730>
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/yade/install/lib/x86_64-linux-gnu/yade-2019-08-08.git-775ae74/py/yade/plot.py in liveUpdate(timestamp)
    512 for ax in axes:
    513 try:
--> 514 ax.relim() # recompute axes limits
    515 ax.autoscale_view()
    516 except RuntimeError: pass # happens if data are being updated and have not the same dimension at the very moment

~/.local/lib/python3.6/site-packages/matplotlib/axes/_base.py in relim(self, visible_only)
   2049 for line in self.lines:
   2050 if not visible_only or line.get_visible():
-> 2051 self._update_line_limits(line)
   2052
   2053 for p in self.patches:

~/.local/lib/python3.6/site-packages/matplotlib/axes/_base.py in _update_line_limits(self, line)
   1922 Figures out the data limit of the given line, updating self.dataLim.
   1923 """
-> 1924 path = line.get_path()
   1925 if path.vertices.size == 0:
   1926 return

~/.local/lib/python3.6/site-packages/matplotlib/lines.py in get_path(self)
   1025 """
   1026 if self._invalidy or self._invalidx:
-> 1027 self.recache()
   1028 return self._path
   1029

~/.local/lib/python3.6/site-packages/matplotlib/lines.py in recache(self, always)
    677 y = self._y
    678
--> 679 self._xy = np.column_stack(np.broadcast_arrays(x, y)).astype(float)
    680 self._x, self._y = self._xy.T # views
    681

<__array_function__ internals> in broadcast_arrays(*args, **kwargs)

~/.local/lib/python3.6/site-packages/numpy/lib/stride_tricks.py in broadcast_arrays(*args, **kwargs)
    262 args = [np.array(_m, copy=False, subok=subok) for _m in args]
    263
--> 264 shape = _broadcast_shape(*args)
    265
    266 if all(array.shape == shape for array in args):

~/.local/lib/python3.6/site-packages/numpy/lib/stride_tricks.py in _broadcast_shape(*args)
    189 # use the old-iterator because np.nditer does not handle size 0 arrays
    190 # consistently
--> 191 b = np.broadcast(*args[:32])
    192 # unfortunately, it cannot handle 32 or more arguments directly
    193 for pos in range(32, len(args), 31):

ValueError: shape mismatch: objects cannot be broadcast to a single shape
In [1]:

Thank you for your help
Bests,
Ehsan

Question information

Language:
English Edit question
Status:
Answered
For:
Yade Edit question
Assignee:
No assignee Edit question
Last query:
Last reply:
Revision history for this message
Robert Caulk (rcaulk) said :
#1

Hello,

This error is a known issue [1]. Sadly it is an issue on matplotlib's end, not Yade's.

Can you confirm that it does not happen when you run the unedited example script?

It has been alleviated in the past by controlling the frequency of plotting [2], so I suspect you made a change to the frequency of plotting. But with out your script, I am just making guesses.

Cheers,

Robert

[1]https://gitlab.com/yade-dev/trunk/issues/110
[2]https://answers.launchpad.net/yade/+question/670492

Revision history for this message
ehsan benabbas (ehsanben) said :
#2

Hello,

Thanks for letting me know about [1]. There's no any way to solve this? The question that I don't know the answer clearly is that after pressing the "Play" button, the data in output files (let say we have a text output file) will be increased based on the deformation we are getting in 3Dshow window? This is because when the run is finished, the 3Dshow window pops up but packing is in it's initial state and it will have deformation after choosing the "Play" button. That is why I am not sure when the analysis is finished? after running the code or after pressing the "Play" button and waiting for deformation.

> Can you confirm that it does not happen when you run the unedited example script?
Yes I confirm that. Why that happens when I edit this code?

> It has been alleviated in the past by controlling the frequency of plotting [2], so I suspect you made a change to the frequency of plotting. But with out your script, I am just making guesses.
I will share my code in the next comment.

Revision history for this message
ehsan benabbas (ehsanben) said :
#3

This is my code:

######################################################################################################
######### TRIAXIAL PROBLEM, Y IS THE VERTICAL AXIS, X IS THE RIGHT AXIS, Z IS THE FRONT AXIS #########
######################################################################################################

print ('************** START **************')
import numpy as np
import datetime
import time
import math
from yade import qt, export, utils
from datetime import datetime

######################################
######### DEFINING VARIABLES #########

print ('============ DEFINING VARIABLES ============')

nRead=readParamsFromTable(
 num_spheres=20000,
 compFricDegree = 30,
 key='_triax_base_',
 unknownOk=True
)

from yade.params import table

num_spheres=table.num_spheres
key=table.key
targetPorosity = 0.4
compFricDegree = table.compFricDegree
finalFricDegree = 30
rate=-0.02
damp=0.2
thick=0
stabilityThreshold=0.01
young=200000000
poisson=1
mn,mx=Vector3(0,0,0),Vector3(0.02,0.02,0.02)
sigmaIso=-500000
particleDensity=2000
######################################################
################# DEFINING FUNCTIONS #################

print ('============ DEFINING FUNCTIONS ============')
from yade import plot
def history():
    plot.addData(e11 = -triax.strain[0],
    e22 = -triax.strain[1],
    e33 = -triax.strain[2],
    ev = -triax.strain[0]-triax.strain[1]-triax.strain[2],
    s11 = -triax.stress(triax.wall_right_id)[0],
    s22 = -triax.stress(triax.wall_top_id)[1],
    s33 = -triax.stress(triax.wall_front_id)[2],
    i = O.iter,
    n = triax.porosity)

######################################################
################# DEFINING MATERIALS #################

print ('============ DEFINING MATERIALS ============')
O.materials.append(FrictMat(young=young,poisson=poisson,frictionAngle=radians(compFricDegree),density=particleDensity,label='spheres'))
O.materials.append(FrictMat(young=young,poisson=poisson,frictionAngle=0,density=0,label='walls'))

####################################################
################# DEFINING PACKING #################

print ('============ DEFINING PACKING ============')
walls=aabbWalls([mn,mx],thickness=thick,material='walls')
wallIds=O.bodies.append(walls)

from yade import pack
sp=pack.SpherePack()
clumps=False
volume = (mx[0]-mn[0])*(mx[1]-mn[1])*(mx[2]-mn[2])
sp.makeCloud(mn,mx,0.0002,0.5,num_spheres,False, 0.95,seed=1)
O.bodies.append([sphere(center,rad,material='spheres') for center,rad in sp])

from yade import export
export.text('PackingData')

##########################################################
################# DEFINING TRIAXIAL TEST #################

print ('============ DEFINING TRIAXIAL TEST ============')
triax=TriaxialStressController(
 maxMultiplier=1.+2e4/young,
 finalMaxMultiplier=1.+2e3/young,
 thickness = thick,
 stressMask = 7,
 internalCompaction=True,
)

####################################################
################# DEFINING ENGINES #################

print ('============ DEFINING ENGINES ============')
O.engines=[
 ForceResetter(),
 InsertionSortCollider([Bo1_Sphere_Aabb(),Bo1_Box_Aabb()]),
 InteractionLoop(
  [Ig2_Sphere_Sphere_ScGeom(),Ig2_Box_Sphere_ScGeom()],
  [Ip2_FrictMat_FrictMat_FrictPhys()],
  [Law2_ScGeom_FrictPhys_CundallStrack()]
 ),
 GlobalStiffnessTimeStepper(active=1,timeStepUpdateInterval=100,timestepSafetyCoefficient=0.8),
 triax,
 PyRunner(iterPeriod=1,command='history()',label='recorder'),
 TriaxialStateRecorder(iterPeriod=1,file='WallStresses'+table.key),
 NewtonIntegrator(damping=damp,label="newton")
]
Gl1_Sphere.stripes=True
if nRead==0: yade.qt.Controller(), yade.qt.View()
print ('Number of elements: ', len(O.bodies))
print ('Box Volume: ', triax.boxVolume)
print ('Box Volume calculated: ', volume)

###############################################################
################# APPLYING CONFINING PRESSURE #################

print ('============ APPLYING CONFINING PRESSURE ============')
triax.stressmask=7
triax.goal1 = sigmaIso
triax.goal2 = sigmaIso
triax.goal3 = sigmaIso
while 1:
    O.run(1000, True)
    unb = unbalancedForce()
    meanS = (triax.stress(triax.wall_right_id)[0]+triax.stress(triax.wall_top_id)[1]+triax.stress(triax.wall_front_id)[2])/3
    print ('~~~~~~~~~~~~~ Phase_01: Converging to Isotropic Compression, 50kPa ~~~~~~~~~~~~~')
    print ('unbalanced force:',unb,' mean stress engine: ',triax.meanStress,' mean stress (Calculated): ',meanS)
    print ('porosity=',triax.porosity)
    print ('void ratio=',triax.porosity/(1-triax.porosity))
    if unb<stabilityThreshold and abs(sigmaIso-triax.meanStress)/sigmaIso<0.001:
        break
O.save('confinedPhase'+key+'.xml')
e22Check=triax.strain[1]
print ('Axial Strain',e22Check)
print ('Mean stress engine: ',triax.meanStress)
print ('Mean stress (Calculated): ',meanS)
print ('################## Isotropic phase is finished and saved successfully ##################')

#############################################################
################# REACHING TARGET POROSITY ##################

print ('============ REACHING TARGET POROSITY ============')
import sys #this is only for the flush() below

while triax.porosity>targetPorosity:
 compFricDegree = 0.95*compFricDegree
 setContactFriction(radians(compFricDegree))
 print ("\r Friction: ",compFricDegree," porosity:",triax.porosity)
 sys.stdout.flush()
 O.run(1000,1)

print ('Final Number of elements: ', len(O.bodies))
print ('Final Box Volume: ', triax.boxVolume)
print ('Final Box Volume calculated: ', volume)
print ('Final porosity=',triax.porosity)
print ('Final void ratio=',triax.porosity/(1-triax.porosity))
O.save('compactedState'+key+'.yade.gz')
print ('################## Target porosity is reached and compacted state saved successfully ##################')

######################################################
################# DEVIATORIC LOADING #################

print ('============ APPLYING DEVIATORIC LOADING ============')
triax.internalCompaction=False
setContactFriction(radians(finalFricDegree))
triax.stressControl_2 = 0
triax.stressMask = 5
triax.goal1 = sigmaIso
triax.goal2 = rate
triax.goal3 = sigmaIso
newton.damping = 0.1
unb = unbalancedForce()
axialS = triax.stress(triax.wall_top_id)[1]
print ('step=', O.iter, 'unbalanced force:',unb,' sigma2: ',axialS, 'q=', axialS-sigmaIso)
print ('Axial Deformation (%)', (triax.strain[1]-e22Check)*100)
print ('~~~~~~~~~~~~~ Phase_02: Converging to Deviatoric Compression, Strain Rate ~~~~~~~~~~~~~')
O.save ('final.xml')
print ('################## Deviatoric phase is finished and saved successfully ##################')

########################################################
################# RECORD AND PLOT DATA #################

print ('============ RECORD AND PLOT DATA ============')
if 1:
  O.engines=O.engines[0:5]+[PyRunner(iterPeriod=1,command='history()',label='recorder')]+O.engines[5:7]
else:
  O.engines[4]=PyRunner(iterPeriod=1,command='history()',label='recorder')
O.run(100,True)
plot.plots={'e22':('ev')}
plot.labels={'s11':'$\sigma_{11}$' , 's22':'$\sigma_{22}$' , 's33':'$\sigma_{33}$' , 'e22':'$\epsilon_{22}$' , 'ev':'$\epsilon_{V}$'}
plot.plot()
plot.saveDataTxt('results'+key)
plot.saveGnuplot('plotScript'+key)

#####################################################
################# RECORD Micro DATA #################

data = []
for i in O.interactions:
   fn = i.phys.normalForce
   fs = i.phys.shearForce
   cp = i.geom.contactPoint
   normal = i.geom.normal
   b1,b2 = [O.bodies[id] for id in (i.id1,i.id2)]
   p1,p2 = [b.state.pos for b in (b1,b2)]
   branch = p2 - p1
   cp,normal,branch,fn,fs = [tuple(v) for v in (cp,normal,branch,fn,fs)] # Vector3 -> tuple
   d = dict(cp=cp,normal=normal,branch=branch,fn=fn,fs=fs)
   data.append(d)
# new data contains the information, you can save it e.g. as JSON
import json
with open("interactions.json","w") as f:
   json.dump(data,f,indent=3)

# =============================================================================
# with open(fileName,"w") as ff:
# ff.write("# cpx cpy cpz fnx fny fnz ...\n")
# for d in data: # or directly for i in O.interactions
# cp = d["cp"]
# fn = d["fn"]
# ...
# ff.write("{} {} {} {} {} {} ... "\n".format(cp[0],cp[1],cp[2],fn[0],fn[1],fn[2],...)
# =============================================================================
#######################################
################# END #################

print ('************** END **************')
O.realtime
print ('Analysis has been taken for',O.realtime, 'seconds or', O.realtime/60, 'minutes')

Cheers,
Ehsan

Revision history for this message
Jan Stránský (honzik) said :
#4

> the data ... will be increased based on the deformation we are getting in 3Dshow window?

I would say it oppositely, the 3Dshow is based on "data".
But yes, clearly, running the simulation (pressing play or writing O.run) changes the its state - it is the meaning of running :-)

> the data in output files (let say we have a text output file) will be increased

it strongly depends on the script.
**In this specific case**:
- you have PyRunner calling history() in O.engines
- after Play, history() stores more data by plot.addData
- BUT after play, it DOES NOT do any saving, so your data output files will not change
- you can also add saving (plot.saveDataTxt) to history(), then it would change data files / create new files after Play

> I am not sure when the analysis is finished? after running the code or after pressing the "Play" button and waiting for deformation.

The simulation is finished at the time you want it to be finished :-)
Some scripts define just initialization and assume user to further interact (pressing play).
Some scripts define the initial state and also some running, possibly to the desired final state.
Some scripts may be combination of both.

I **guess** that this simulation is intended to be finished, when ****END**** is printed.
But you may want it to be finished at a different time, it really is up to you.

**My** opinion and usage of Play button:
- use GUI (3D view and play/step buttons) in the phase when you are creating and tuning the simulation
- for "production" scripts, do not use GUI. The script should be "self-defined", relying on well defined stop conditions and running without your interactions. Then you can smoothly automate the running or use yade-batch for batch simulations

cheers
Jan

Can you help with this problem?

Provide an answer of your own, or ask ehsan benabbas for more information if necessary.

To post a message you must log in.