Python API

The Python module sphere is intended as the main interface to the sphere application. It is recommended to use this module for simulation setup, simulation execution, and analysis of the simulation output data.

In order to use the API, the file sphere.py must be placed in the same directory as the Python files.

Sample usage

Below is a simple, annotated example of how to setup, execute, and post-process a sphere simulation. The example is also found in the python/ folder as collision.py.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
'''
Example of two particles colliding.
Place script in sphere/python/ folder, and invoke with `python collision.py`
'''

# Import the sphere module for setting up, running, and analyzing the
# experiment. We also need the numpy module when setting arrays in the sphere
# object.
import sphere
import numpy


### SIMULATION SETUP

# Create a sphere object with two preallocated particles and a simulation ID
SB = sphere.sim(np = 2, sid = 'collision')

SB.radius[:] = 0.3 # set radii to 0.3 m

# Define the positions of the two particles
SB.x[0, :] = numpy.array([10.0, 5.0, 5.0])   # particle 1 (idx 0)
SB.x[1, :] = numpy.array([11.0, 5.0, 5.0])   # particle 2 (idx 1)

# The default velocity is [0,0,0]. Slam particle 1 into particle 2 by defining
# a positive x velocity for particle 1.
SB.vel[0, 0] = 1.0

# Set the world limits and the particle sorting grid. The particles need to stay
# within the world limits for the entire simulation, otherwise it will stop!
SB.initGridAndWorldsize(margin = 5.0)

# Define the temporal parameters, e.g. the total time (total) and the file
# output interval (file_dt), both in seconds
SB.initTemporal(total = 2.0, file_dt = 0.1)

# Using a 'dry' run, the sphere main program will display important parameters.
# sphere will end after displaying these values.
SB.run(dry = True)


### RUNNING THE SIMULATION

# Start the simulation on the GPU from the sphere program
SB.run()


### ANALYSIS OF SIMULATION RESULTS

# Plot the system energy through time, image saved as collision-energy.png
SB.visualize(method = 'energy')

# Render the particles using the built-in raytracer
SB.render()

# Alternative visualization using ParaView. See the documentation of
# ``sim.writeVTKall()`` for more information about displaying the
# particles in ParaView.
SB.writeVTKall()

The full documentation of the sphere Python API can be found below.

The sphere module

sphere.V_sphere(r)

Calculates the volume of a sphere with radius r

Returns

The sphere volume [m^3]

Return type

float

sphere.cleanup(sim)

Removes the input/output files and images belonging to the object simulation ID from the input/, output/ and img_out/ folders.

Parameters

spherebin (sim) – A sim object

sphere.convert(graphics_format='png', folder='../img_out', remove_ppm=False)

Converts all PPM images in img_out to graphics_format using ImageMagick. All PPM images are subsequently removed if remove_ppm is True.

Parameters
  • graphics_format (str) – Convert the images to this format

  • folder (str) – The folder containing the PPM images to convert

  • remove_ppm (bool) – Remove ALL ppm files in folder after conversion

sphere.render(binary, method='pres', max_val=1000.0, lower_cutoff=0.0, graphics_format='png', verbose=True)

Render target binary using the sphere raytracer.

Parameters
  • method (str) – The color visualization method to use for the particles. Possible values are: ‘normal’: color all particles with the same color, ‘pres’: color by pressure, ‘vel’: color by translational velocity, ‘angvel’: color by rotational velocity, ‘xdisp’: color by total displacement along the x-axis, ‘angpos’: color by angular position.

  • max_val (float) – The maximum value of the color bar

  • lower_cutoff (float) – Do not render particles with a value below this value, of the field selected by method

  • graphics_format (str) – Convert the PPM images generated by the ray tracer to this image format using Imagemagick

  • verbose (bool) – Show verbose information during ray tracing

sphere.run(binary, verbose=True, hideinputfile=False)

Execute sphere with target binary file as input.

Parameters
  • binary (str) – Input file for sphere

  • verbose (bool) – Show sphere output

  • hideinputfile (bool) – Hide the input file

class sphere.sim(sid='unnamed', np=0, nd=3, nw=0, fluid=False, cfd_solver=0)

Class containing all sphere data.

Contains functions for reading and writing binaries, as well as simulation setup and data analysis. Most arrays are initialized to default values.

Parameters
  • np (int) – The number of particles to allocate memory for (default=1)

  • nd (int) – The number of spatial dimensions (default=3). Note that 2D and 1D simulations currently are not possible.

  • nw (int) – The number of dynamic walls (default=1)

  • sid (str) – The simulation id (default=’unnamed’). The simulation files will be written with this base name.

  • fluid (bool) – Setup fluid simulation (default=False)

  • cfd_solver (int) – Fluid solver to use if fluid == True. 0: Navier-Stokes (default), 1: Darcy.

ReynoldsNumber()

Estimate the per-cell Reynolds number by: Re=rho * ||v_f|| * dx/mu. This value is returned and also stored in self.Re.

Returns

Reynolds number

Return type

Numpy array with dimensions like the fluid grid

acceleration(idx=-1)

Returns the acceleration of one or more particles, selected by their index. If the index is equal to -1 (default value), all accelerations are returned.

Parameters

idx (int, list or numpy.array) – Index or index range of particles

Returns

n-by-3 matrix of acceleration(s)

Return type

numpy.array

adaptiveGrid()

Set the height of the fluid grid to automatically readjust to the height of the granular assemblage, as dictated by the position of the top wall. This will readjust self.L[2] during the simulation to equal the position of the top wall self.w_x[0].

See also staticGrid()

addParticle(x, radius, xyzsum=array([0., 0., 0.]), vel=array([0., 0., 0.]), fixvel=array([0.]), force=array([0., 0., 0.]), angpos=array([0., 0., 0.]), angvel=array([0., 0., 0.]), torque=array([0., 0., 0.]), es_dot=array([0.]), es=array([0.]), ev_dot=array([0.]), ev=array([0.]), p=array([0.]), color=0)

Add a single particle to the simulation object. The only required parameters are the position (x) and the radius (radius).

Parameters
  • x (numpy.array) – A vector pointing to the particle center coordinate.

  • radius (float) – The particle radius

  • vel (numpy.array) – The particle linear velocity (default=[0,0,0])

  • fixvel (float) – 0: Do not fix particle velocity (default), 1: Fix horizontal linear velocity, -1: Fix horizontal and vertical linear velocity

  • angpos (numpy.array) – The particle angular position (default=[0,0,0])

  • angvel (numpy.array) – The particle angular velocity (default=[0,0,0])

  • torque (numpy.array) – The particle torque (default=[0,0,0])

  • es_dot (float) – The particle shear energy loss rate (default=0)

  • es (float) – The particle shear energy loss (default=0)

  • ev_dot (float) – The particle viscous energy rate loss (default=0)

  • ev (float) – The particle viscous energy loss (default=0)

  • p (float) – The particle pressure (default=0)

adjustUpperWall(z_adjust=1.1)

Included for legacy purposes, calls adjustWall() with idx=0.

Parameters

z_adjust (float) – Increase the world and grid size by this amount to allow for wall movement.

adjustWall(idx, adjust=1.1)

Adjust grid and dynamic wall to max. particle position. The wall thickness will by standard equal the maximum particle diameter. The density equals the particle density, and the wall size is equal to the width and depth of the simulation domain (self.L[0] and self.L[1]).

Param

idx: The wall to adjust. 0=+z, upper wall (default), 1=-x, left wall, 2=+x, right wall, 3=-y, front wall, 4=+y, back wall.

Parameters

adjust (float) – Increase the world and grid size by this amount to allow for wall movement.

bond(i, j)

Create a bond between particles with index i and j

Parameters
  • i (int) – Index of first particle in bond

  • j (int) – Index of second particle in bond

bondsRose(graphics_format='pdf')

Visualize the trend and plunge angles of the bond pairs in a rose plot. The plot is saved in the current folder as ‘bonds-<simulation id>-rose.<graphics_format>’.

Parameters

graphics_format (str) – Save the plot in this format

bulkPorosity(trim=True)

Calculates the bulk porosity of the particle assemblage.

Parameters

trim (bool) – Trim the total volume to the smallest axis-parallel cube containing all particles.

Returns

The bulk porosity, in [0:1]

Return type

float

cellSize()

Calculate the particle sorting (and fluid) cell dimensions. These values are stored in self.dx and are NOT returned.

checkerboardColors(nx=6, ny=6, nz=6)

Assign checkerboard color values to the particles in an orthogonal grid.

Parameters
  • nx (int) – Number of color values along the x axis

  • ny (int) – Number of color values along the y ayis

  • nz (int) – Number of color values along the z azis

cleanup()

Removes the input/output files and images belonging to the object simulation ID from the input/, output/ and img_out/ folders.

consolidate(normal_stress=10000.0)

Setup consolidation experiment. Specify the upper wall normal stress in Pascal, default value is 10 kPa.

Parameters

normal_stress (float) – The normal stress to apply from the upper wall

contactModel(contactmodel)

Define which contact model to use for the tangential component of particle-particle interactions. The elastic-viscous-frictional contact model (2) is considered to be the most realistic contact model, while the viscous-frictional contact model is significantly faster.

Parameters

contactmodel (int) – The type of tangential contact model to use (visco-frictional=1, elasto-visco-frictional=2)

contactParticleArea(i, j)

Finds the average area of an two particles in an inter-particle contact.

Parameters
  • i (int or array of ints) – Index of first particle

  • j (int or array of ints) – Index of second particle

  • d (float or array of floats) – Overlap distance

Returns

Contact area [m*m]

Return type

float or array of floats

contactSurfaceArea(i, j, overlap)

Finds the contact surface area of an inter-particle contact.

Parameters
  • i (int or array of ints) – Index of first particle

  • j (int or array of ints) – Index of second particle

  • d (float or array of floats) – Overlap distance

Returns

Contact area [m*m]

Return type

float or array of floats

convergence()

Read the convergence evolution in the CFD solver. The values are stored in self.conv with iteration number in the first column and iteration count in the second column.

See also: plotConvergence()

createBondPair(i, j, spacing=-0.1)

Bond particles i and j. Particle j is moved adjacent to particle i, and oriented randomly.

Parameters
  • i (int) – Index of first particle in bond

  • j (int) – Index of second particle in bond

  • spacing (float) – The inter-particle distance prescribed. Positive values result in a inter-particle distance, negative equal an overlap. The value is relative to the sum of the two radii.

currentNormalStress(type='defined')

Calculates the current magnitude of the defined or effective top wall normal stress.

Parameters

type (str) – Find the ‘defined’ (default) or ‘effective’ normal stress

Returns

The current top wall normal stress in Pascal

Return type

float

currentTime(value=-1)

Get or set the current time. If called without arguments the current time is returned. If a new time is passed in the ‘value’ argument, the time is written to the object.

Parameters

value (float) – The new current time

Returns

The current time

Return type

float

defaultParams(mu_s=0.5, mu_d=0.5, mu_r=0.0, rho=2600, k_n=1160000000.0, k_t=1160000000.0, k_r=0, gamma_n=0.0, gamma_t=0.0, gamma_r=0.0, gamma_wn=0.0, gamma_wt=0.0, capillaryCohesion=0)

Initialize particle parameters to default values.

Parameters
  • mu_s (float) – The coefficient of static friction between particles [-]

  • mu_d (float) – The coefficient of dynamic friction between particles [-]

  • rho (float) – The density of the particle material [kg/(m^3)]

  • k_n (float) – The normal stiffness of the particles [N/m]

  • k_t (float) – The tangential stiffness of the particles [N/m]

  • k_r (float) – The rolling stiffness of the particles [N/rad] Parameter not used

  • gamma_n (float) – Particle-particle contact normal viscosity [Ns/m]

  • gamma_t (float) – Particle-particle contact tangential viscosity [Ns/m]

  • gamma_r (float) – Particle-particle contact rolling viscosity Parameter not used

  • gamma_wn (float) – Wall-particle contact normal viscosity [Ns/m]

  • gamma_wt (float) – Wall-particle contact tangential viscosity [Ns/m]

  • capillaryCohesion (int) – Enable particle-particle capillary cohesion interaction model (0=no (default), 1=yes)

defineWorldBoundaries(L, origo=[0.0, 0.0, 0.0], dx=-1)

Set the boundaries of the world. Particles will only be able to interact within this domain. With dynamic walls, allow space for expansions. Important: The particle radii have to be set beforehand. The world edges act as static walls.

Parameters
  • L (numpy.array) – The upper boundary of the domain [m]

  • origo (numpy.array) – The lower boundary of the domain [m]. Negative values won’t work. Default=[0.0, 0.0, 0.0].

  • dx (float) – The cell width in any direction. If the default value is used (-1), the cell width is calculated to fit the largest particle.

deleteAllParticles()

Deletes all particles in the simulation object.

deleteParticle(i)

Delete particle(s) with index i.

Parameters

i (int, list or numpy.array) – One or more particle indexes to delete

disableFluidPressureModulation()

Set the parameters for the sine wave modulating the fluid pressures at the top boundary to zero.

See also: setFluidPressureModulation()

disableTopWallNormalStressModulation()

Set the parameters for the sine wave modulating the normal stress at the top dynamic wall to zero.

See also: setTopWallNormalStressModulation()

dry()

Set the simulation to be dry (no fluids).

See also wet()

energy(method)

Calculates the sum of the energy components of all particles.

Parameters

method (str) – The type of energy to return. Possible values are ‘pot’ for potential energy [J], ‘kin’ for kinetic energy [J], ‘rot’ for rotational energy [J], ‘shear’ for energy lost by friction, ‘shearrate’ for the rate of frictional energy loss [W], ‘visc_n’ for viscous losses normal to the contact [J], ‘visc_n_rate’ for the rate of viscous losses normal to the contact [W], and finally ‘bondpot’ for the potential energy stored in bonds [J]

Returns

The value of the selected energy type

Return type

float

findAllAverageParticlePairAreas()

Finds the average area of an inter-particle contact. This function requires a prior call to findOverlaps() as it reads from the self.pairs and self.overlaps arrays.

Returns

Array of contact surface areas

Return type

array of floats

findAllContactSurfaceAreas()

Finds the contact surface area of an inter-particle contact. This function requires a prior call to findOverlaps() as it reads from the self.pairs and self.overlaps arrays.

Returns

Array of contact surface areas

Return type

array of floats

findContactStresses(area='average')

Finds all particle-particle uniaxial normal stresses (by first calling findNormalForces()) and calculating the stress magnitudes by dividing the normal force magnitude with the average particle area (‘average’) or by the contact surface area (‘contact’).

The result is saved in self.sigma_contacts.

Parameters

area (str) – Area to use: ‘average’ (default) or ‘contact’

See also: findNormalForces() and findOverlaps()

findCoordinationNumber()

Finds the coordination number (the average number of contacts per particle). Requires a previous call to findOverlaps(). Values are stored in self.coordinationnumber.

findHydraulicConductivities()

Calculates the hydrological conductivities from the Kozeny-Carman relationship. These values are only relevant when the Darcy solver is used (self.cfd_solver=1). The permeability pre-factor self.k_c and the assemblage porosities must be set beforehand. The former values are set if a file from the output/ folder is read using self.readbin.

findLoadedContacts(threshold)

Finds the indices of contact pairs where the contact stress magnitude exceeds or is equal to a specified threshold value. This function calls findContactStresses().

Parameters

threshold (float) – Threshold contact stress [Pa]

Returns

Array of contact indices

Return type

array of ints

findMeanCoordinationNumber()

Returns the coordination number (the average number of contacts per particle). Requires a previous call to findOverlaps()

Returns

The mean particle coordination number

Return type

float

findNormalForces()

Finds all particle-particle overlaps (by first calling findOverlaps()) and calculating the normal magnitude by multiplying the overlaps with the elastic stiffness self.k_n.

The result is saved in self.f_n_magn.

See also: findOverlaps() and findContactStresses()

findOverlaps()

Find all particle-particle overlaps by a n^2 contact search, which is done in C++. The particle pair indexes and the distance of the overlaps is saved in the object itself as the .pairs and .overlaps members.

See also: findNormalForces()

findPermeabilities()

Calculates the hydrological permeabilities from the Kozeny-Carman relationship. These values are only relevant when the Darcy solver is used (self.cfd_solver=1). The permeability pre-factor self.k_c and the assemblage porosities must be set beforehand. The former values are set if a file from the output/ folder is read using self.readbin.

forcechains(lc=200.0, uc=650.0, outformat='png', disp='2d')

Visualizes the force chains in the system from the magnitude of the normal contact forces, and produces an image of them. Warning: Will segfault if no contacts are found.

Parameters
  • lc (float) – Lower cutoff of contact forces. Contacts below are not visualized

  • uc (float) – Upper cutoff of contact forces. Contacts above are visualized with this value

  • outformat (str) – Format of output image. Possible values are ‘interactive’, ‘png’, ‘epslatex’, ‘epslatex-color’

  • disp (str) – Display forcechains in ‘2d’ or ‘3d’

forcechainsRose(lower_limit=0.25, graphics_format='pdf')

Visualize trend and plunge angles of the strongest force chains in a rose plot. The plots are saved in the current folder with the name ‘fc-<simulation id>-rose.pdf’.

Parameters
  • lower_limit (float) – Do not visualize force chains below this relative contact force magnitude, in ]0;1[

  • graphics_format (str) – Save the plot in this format

frictionalEnergy(idx)

Returns the frictional dissipated energy for a particle.

Parameters

idx (int) – Particle index

Returns

The frictional energy lost of the particle [J]

Return type

float

generateBimodalRadii(r_small=0.005, r_large=0.05, ratio=0.2, verbose=True)

Draw random radii from two distinct sizes.

Parameters
  • r_small (float) – Radii of small population [m], in ]0;r_large[

  • r_large (float) – Radii of large population [m], in ]r_small;inf[

  • ratio (float) – Approximate volumetric ratio between the two populations (large/small).

See also: generateRadii().

generateRadii(psd='logn', mean=0.00044, variance=8.8e-09, histogram=False)

Draw random particle radii from a selected probability distribution. The larger the variance of radii is, the slower the computations will run. The reason is two-fold: The smallest particle dictates the time step length, where smaller particles cause shorter time steps. At the same time, the largest particle determines the sorting cell size, where larger particles cause larger cells. Larger cells are likely to contain more particles, causing more contact checks.

Parameters
  • psd (str) – The particle side distribution. One possible value is logn, which is a log-normal probability distribution, suitable for approximating well-sorted, coarse sediments. The other possible value is uni, which is a uniform distribution from mean - variance to mean + variance.

  • mean (float) – The mean radius [m] (default=440e-6 m)

  • variance (float) – The variance in the probability distribution [m].

See also: generateBimodalRadii().

hydraulicConductivity(phi=0.35)

Determine the hydraulic conductivity (K) [m/s] from the permeability prefactor and a chosen porosity. This value is stored in self.K_c. This function only works for the Darcy solver (self.cfd_solver == 1)

Parameters

phi (float) – The porosity to use in the Kozeny-Carman relationship

Returns

The hydraulic conductivity [m/s]

Return type

float

hydraulicDiffusivity()

Determine the hydraulic diffusivity (D) [m*m/s]. The result is stored in self.D. This function only works for the Darcy solver (self.cfd_solver[0] == 1)

hydraulicPermeability(phi_min=0.3, phi_max=0.99)

Determine the hydraulic permeability (k) [m*m] from the Kozeny-Carman relationship, using the permeability prefactor (self.k_c), and the range of valid porosities set in src/darcy.cuh, by default in the range 0.1 to 0.9.

This function is only valid for the Darcy solver (self.cfd_solver == 1).

id(sid='')

Returns or sets the simulation id/name, which is used to identify simulation files in the output folders.

Parameters

sid (str) – The desired simulation id. If left blank the current simulation id will be returned.

Returns

The current simulation id if no new value is set.

Return type

str

idAppend(string)

Append a string to the simulation id/name, which is used to identify simulation files in the output folders.

Parameters

string (str) – The string to append to the simulation id (self.sid).

inertiaParameterPlanarShear()

Returns the value of the inertia parameter $I$ during planar shear proposed by GDR-MiDi 2004.

Returns

The value of $I$

Return type

float

See also: shearStrainRate() and shearVel()

initFluid(mu=0.00089, rho=1000.0, p=0.0, hydrostatic=False, cfd_solver=0)

Initialize the fluid arrays and the fluid viscosity. The default value of mu equals the dynamic viscosity of water at 25 degrees Celcius. The value for water at 0 degrees Celcius is 17.87e-4 kg/(m*s).

Parameters
  • mu (float) – The fluid dynamic viscosity [kg/(m*s)]

  • rho (float) – The fluid density [kg/(m^3)]

  • p – The hydraulic pressure to initialize the cells to. If the parameter hydrostatic is set to True, this value will apply to the fluid cells at the top

  • hydrostatic (bool) – Initialize the fluid pressures to the hydrostatic pressure distribution. A pressure gradient with depth is only created if a gravitational acceleration along z previously has been specified

  • cfd_solver (int) – Solver to use for the computational fluid dynamics. Accepted values: 0 (Navier Stokes, default) and 1 (Darcy).

initGrid(dx=-1)

Initialize grid suitable for the particle positions set previously. The margin parameter adjusts the distance (in no. of max. radii) from the particle boundaries. Important: The particle radii have to be set beforehand if the cell width isn’t specified by dx.

Parameters

dx (float) – The cell width in any direction. If the default value is used (-1), the cell width is calculated to fit the largest particle.

initGridAndWorldsize(margin=2.0)

Initialize grid suitable for the particle positions set previously. The margin parameter adjusts the distance (in no. of max. radii) from the particle boundaries. If the upper wall is dynamic, it is placed at the top boundary of the world.

Parameters

margin (float) – Distance to world boundary in no. of max. particle radii

initGridPos(gridnum=array([12, 12, 36]))

Initialize particle positions in loose, cubic configuration. gridnum is the number of cells in the x, y and z directions. Important: The particle radii and the boundary conditions (periodic or not) for the x and y boundaries have to be set beforehand.

Parameters

gridnum (numpy.array) – The number of particles in x, y and z directions

initRandomGridPos(gridnum=array([12, 12, 32]), padding=2.1)

Initialize particle positions in loose, cubic configuration with some variance. gridnum is the number of cells in the x, y and z directions. Important: The particle radii and the boundary conditions (periodic or not) for the x and y boundaries have to be set beforehand. The world size and grid height (in the z direction) is readjusted to fit the particle positions.

Parameters
  • gridnum (numpy.array) – The number of particles in x, y and z directions

  • padding (float) – Increase distance between particles in x, y and z directions with this multiplier. Large values create more random packings.

initRandomPos(gridnum=array([12, 12, 36]))

Initialize particle positions in completely random configuration. Radii must be set beforehand. If the x and y boundaries are set as periodic, the particle centers will be placed all the way to the edge. On regular, non-periodic boundaries, the particles are restrained at the edges to make space for their radii within the bounding box.

Parameters
  • gridnum (numpy.array) – The number of sorting cells in each spatial direction (default=[12, 12, 36])

  • dx (float) – The cell width in any direction. If the default value is used (-1), the cell width is calculated to fit the largest particle.

initTemporal(total, current=0.0, file_dt=0.05, step_count=0, dt=-1, epsilon=0.01)

Set temporal parameters for the simulation. Important: Particle radii, physical parameters, and the optional fluid grid need to be set prior to these if the computational time step (dt) isn’t set explicitly. If the parameter dt is the default value (-1), the function will estimate the best time step length. The value of the computational time step for the DEM is checked for stability in the CFD solution if fluid simulation is included.

Parameters
  • total (float) – The time at which to end the simulation [s]

  • current – The current time [s] (default=0.0 s)

  • file_dt – The interval between output files [s] (default=0.05 s)

  • dt – The computational time step length [s]

  • epsilon (float) – Time step multiplier (default=0.01)

Step_count

The number of the first output file (default=0)

kineticEnergy(idx)

Returns the (linear) kinetic energy for a particle.

Parameters

idx (int) – Particle index

Returns

The kinetic energy of the particle [J]

Return type

float

largestFluidTimeStep(safety=0.5, v_max=-1.0)

Finds and returns the largest time step in the fluid phase by von Neumann and Courant-Friedrichs-Lewy analysis given the current velocities. This ensures stability in the diffusive and advective parts of the momentum equation.

The value of the time step decreases with increasing fluid viscosity (self.mu), and increases with fluid cell size (self.L/self.num)

and fluid velocities (self.v_f)

Parameters
  • safety (float) – Safety factor which is multiplied to the largest time step.

  • v_max (float) – The largest anticipated absolute fluid velocity [m/s]

Returns

The largest timestep stable for the current fluid state.

Return type

float

largestMass()

Returns the mass of the heaviest particle.

Parameters

idx (int) – Particle index

Returns

The mass of the particle [kg]

Return type

float

mass(idx)

Returns the mass of a particle.

Parameters

idx (int) – Particle index

Returns

The mass of the particle [kg]

Return type

float

momentOfInertia(idx)

Returns the moment of inertia of a particle.

Parameters

idx (int) – Particle index

Returns

The moment of inertia [kg*m^2]

Return type

float

momentum(idx)

Returns the momentum (m*v) of a particle.

Parameters

idx (int) – The particle index

Returns

The particle momentum [N*s]

Return type

numpy.array

normalBoundariesXY()

Set the x and y boundary conditions to be static walls.

See also periodicBoundariesXY() and periodicBoundariesX()

periodicBoundariesX()

Set the x boundary conditions to be periodic.

See also normalBoundariesXY() and periodicBoundariesXY()

periodicBoundariesXY()

Set the x and y boundary conditions to be periodic.

See also normalBoundariesXY() and periodicBoundariesX()

plotContacts(graphics_format='png', figsize=[4, 4], title=None, lower_limit=0.0, upper_limit=1.0, alpha=1.0, return_data=False, outfolder='.', f_min=None, f_max=None, histogram=True, forcechains=True)

Plot current contact orientations on polar plot

Parameters
  • lower_limit (float) – Do not visualize force chains below this relative contact force magnitude, in ]0;1[

  • upper_limit (float) – Visualize force chains above this relative contact force magnitude but cap color bar range, in ]0;1[

  • graphics_format (str) – Save the plot in this format

plotConvergence(graphics_format='png', verbose=True)

Plot the convergence evolution in the CFD solver. The plot is saved in the output folder with the file name ‘<simulation id>-conv.<graphics_format>’.

Parameters
  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

See also: convergence()

plotFluidDiffAdvPresZ(graphics_format='png', verbose=True)

Compare contributions to the velocity from diffusion and advection, assuming the flow is 1D along the z-axis, phi=1, and dphi=0. This solution is analog to the predicted velocity and not constrained by the conservation of mass. The plot is saved in the output folder with the name format ‘<simulation id>-diff_adv-t=<current time>s-mu=<dynamic viscosity>Pa-s.<graphics_format>’.

Parameters
  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

plotFluidPressuresY(y=-1, graphics_format='png', verbose=True)

Plot fluid pressures in a plane normal to the second axis. The plot is saved in the current folder with the format ‘p_f-<simulation id>-y<y value>.<graphics_format>’.

Parameters
  • y (int) – Plot pressures in fluid cells with these y axis values. If this value is -1, the center y position is used.

  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

See also: writeFluidVTK() and plotFluidPressuresZ()

plotFluidPressuresZ(z=-1, graphics_format='png', verbose=True)

Plot fluid pressures in a plane normal to the third axis. The plot is saved in the current folder with the format ‘p_f-<simulation id>-z<z value>.<graphics_format>’.

Parameters
  • z (int) – Plot pressures in fluid cells with these z axis values. If this value is -1, the center z position is used.

  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

See also: writeFluidVTK() and plotFluidPressuresY()

plotFluidVelocitiesY(y=-1, graphics_format='png', verbose=True)

Plot fluid velocities in a plane normal to the second axis. The plot is saved in the current folder with the format ‘v_f-<simulation id>-z<z value>.<graphics_format>’.

Parameters
  • y (int) – Plot velocities in fluid cells with these y axis values. If this value is -1, the center y position is used.

  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

See also: writeFluidVTK() and plotFluidVelocitiesZ()

plotFluidVelocitiesZ(z=-1, graphics_format='png', verbose=True)

Plot fluid velocities in a plane normal to the third axis. The plot is saved in the current folder with the format ‘v_f-<simulation id>-z<z value>.<graphics_format>’.

Parameters
  • z (int) – Plot velocities in fluid cells with these z axis values. If this value is -1, the center z position is used.

  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

See also: writeFluidVTK() and plotFluidVelocitiesY()

plotLoadCurve(graphics_format='png', verbose=True)

Plot the load curve (log time vs. upper wall movement). The plot is saved in the current folder with the file name ‘<simulation id>-loadcurve.<graphics_format>’. The consolidation coefficient calculations are done on the base of Bowles 1992, p. 129–139, using the “Casagrande” method. It is assumed that the consolidation has stopped at the end of the simulation (i.e. flat curve).

Parameters
  • graphics_format (str) – Save the plot in this format

  • verbose (bool) – Print output filename after saving

plotPrescribedFluidPressures(graphics_format='png', verbose=True)

Plot the prescribed fluid pressures through time that may be modulated through the class parameters p_mod_A, p_mod_f, and p_mod_phi. The plot is saved in the output folder with the file name ‘<simulation id>-pres.<graphics_format>’.

plotSinFunction(baseval, A, f, phi=0.0, xlabel='$t$ [s]', ylabel='$y$', plotstyle='.', outformat='png')

Plot the values of a sinusoidal modulated base value. Saves the output as a plot in the current folder. The time values will range from self.time_current to self.time_total.

Parameters
  • baseval (float) – The center value which the sinusoidal fluctuations are modulating

  • A (float) – The fluctuation amplitude

  • phi (float) – The phase shift [s]

  • xlabel (str) – The label for the x axis

  • ylabel (str) – The label for the y axis

  • plotstyle (str) – Matplotlib-string for specifying plotting style

  • outformat (str) – File format of the output plot

  • verbose (bool) – Print output filename after saving

porosities(graphics_format='pdf', zslices=16)

Plot the averaged porosities with depth. The plot is saved in the format ‘<simulation id>-porosity.<graphics_format>’.

Parameters
  • graphics_format (str) – Save the plot in this format

  • zslices (int) – The number of points along the vertical axis to sample the porosity in

porosity(slices=10, verbose=False)

Calculates the porosity as a function of depth, by averaging values in horizontal slabs. Returns porosity values and their corresponding depth. The values are calculated using the external porosity program.

Parameters
  • slices (int) – The number of vertical slabs to find porosities in.

  • verbose (bool) – Show the file name of the temporary file written to disk

Returns

A 2d array of depths and their averaged porosities

Return type

numpy.array

randomBondPairs(ratio=0.3, spacing=-0.1)

Bond an amount of particles in two-particle clusters. The particles should be initialized beforehand. Note: The actual number of bonds is likely to be somewhat smaller than specified, due to the random selection algorithm.

Parameters
  • ratio (float) – The amount of particles to bond, values in ]0.0;1.0]

  • spacing (float) – The distance relative to the sum of radii between bonded particles, neg. values denote an overlap. Values in ]0.0,inf[.

readTime(time, verbose=True)

Read the output file most closely corresponding to the time given as an argument.

Parameters

time (float) – The desired current time [s]

See also readbin(), readfirst(), readsecond(), and readstep().

readbin(targetbin, verbose=True, bonds=True, sigma0mod=True, esysparticle=False)

Reads a target sphere binary file.

See also writebin(), readfirst(), readlast(), readsecond(), and readstep().

Parameters
  • targetbin (str) – The path to the binary sphere file

  • verbose (bool) – Show diagnostic information (default=True)

  • bonds (bool) – The input file contains bond information (default=True). This parameter should be true for all recent sphere versions.

  • sigma0mod (bool) – The input file contains information about modulating stresses at the top wall (default=True). This parameter should be true for all recent sphere versions.

  • esysparticle (bool) – Stop reading the file after reading the kinematics, which is useful for reading output files from other DEM programs. (default=False)

readfirst(verbose=True)

Read the first output file from the ../output/ folder, corresponding to the object simulation id (self.sid).

Parameters

verbose (bool) – Display diagnostic information (default=True)

See also readbin(), readlast(), readsecond(), and readstep().

readlast(verbose=True)

Read the last output file from the ../output/ folder, corresponding to the object simulation id (self.sid).

Parameters

verbose (bool) – Display diagnostic information (default=True)

See also readbin(), readfirst(), readsecond(), and readstep().

readsecond(verbose=True)

Read the second output file from the ../output/ folder, corresponding to the object simulation id (self.sid).

Parameters

verbose (bool) – Display diagnostic information (default=True)

See also readbin(), readfirst(), readlast(), and readstep().

readstep(step, verbose=True)

Read a output file from the ../output/ folder, corresponding to the object simulation id (self.sid).

Parameters
  • step (int) – The output file number to read, starting from 0.

  • verbose (bool) – Display diagnostic information (default=True)

See also readbin(), readfirst(), readlast(), and readsecond().

render(method='pres', max_val=1000.0, lower_cutoff=0.0, graphics_format='png', verbose=True)

Using the built-in ray tracer, render all output files that belong to the simulation, determined by the simulation id (sid).

Parameters
  • method (str) – The color visualization method to use for the particles. Possible values are: ‘normal’: color all particles with the same color, ‘pres’: color by pressure, ‘vel’: color by translational velocity, ‘angvel’: color by rotational velocity, ‘xdisp’: color by total displacement along the x-axis, ‘angpos’: color by angular position.

  • max_val (float) – The maximum value of the color bar

  • lower_cutoff (float) – Do not render particles with a value below this value, of the field selected by method

  • graphics_format (str) – Convert the PPM images generated by the ray tracer to this image format using Imagemagick

  • verbose (bool) – Show verbose information during ray tracing

rotationalEnergy(idx)

Returns the rotational energy for a particle.

Parameters

idx (int) – Particle index

Returns

The rotational kinetic energy of the particle [J]

Return type

float

run(verbose=True, hideinputfile=False, dry=False, valgrind=False, cudamemcheck=False, device=-1)

Start sphere calculations on the sim object

Parameters
  • verbose (bool) – Show sphere output

  • hideinputfile (bool) – Hide the file name of the sphere input file

  • dry (bool) – Perform a dry run. Important parameter values are shown by the sphere program, and it exits afterwards.

  • valgrind (bool) – Run the program with valgrind in order to check memory leaks in the host code. This causes a significant increase in computational time.

  • cudamemcheck (bool) – Run the program with cudamemcheck in order to check for device memory leaks and errors. This causes a significant increase in computational time.

  • device (int) – Specify the GPU device to execute the program on. If not specified, sphere will use the device with the most CUDA cores. To see a list of devices, run nvidia-smi in the system shell.

scaleSize(factor)

Scale the positions, linear velocities, forces, torques and radii of all particles and mobile walls.

Parameters

factor (float) – Spatial scaling factor ]0;inf[

setBeta(beta)

Beta is a fluid solver parameter, used in velocity prediction and pressure iteration 1.0: Use old pressures for fluid velocity prediction (see Langtangen et al. 2002) 0.0: Do not use old pressures for fluid velocity prediction (Chorin’s original projection method, see Chorin (1968) and “Projection method (fluid dynamics)” page on Wikipedia. The best results precision and performance-wise are obtained by using a beta of 0 and a low tolerance criteria value.

The default and recommended value is 0.0.

Other solver parameter setting functions: setGamma(), setTheta(), setTolerance(), setDEMstepsPerCFDstep() and setMaxIterations()

setDEMstepsPerCFDstep(ndem)

A fluid solver parameter, the value of the maxiter parameter denotes the number of DEM time steps to be performed per CFD time step.

The default value is 1.

Parameters

ndem (int) – The DEM/CFD time step ratio

Other solver parameter setting functions: setGamma(), setTheta(), setBeta(), setTolerance() and setMaxIterations().

setDampingNormal(gamma, over_damping=False)

Set the dampening coefficient (gamma) in the normal direction of the particle-particle contact model. The function will print the fraction between the chosen damping and the critical damping value.

Parameters
  • gamma (float) – The viscous damping constant [N/(m/s)]

  • over_damping (boolean) – Accept overdampening

See also: setDampingTangential(gamma)()

setDampingTangential(gamma, over_damping=False)

Set the dampening coefficient (gamma) in the tangential direction of the particle-particle contact model. The function will print the fraction between the chosen damping and the critical damping value.

Parameters
  • gamma (float) – The viscous damping constant [N/(m/s)]

  • over_damping (boolean) – Accept overdampening

See also: setDampingNormal(gamma)()

setDynamicFriction(mu_d)

Set the dynamic friction coefficient for particle-particle interactions (self.mu_d). This value describes the resistance to a shearing motion while it is happening (contact tangential velocity larger than 0). Strain softening can be introduced by having a smaller dynamic frictional coefficient than the static fricion coefficient. Usually this value is identical to the static friction coefficient.

Parameters

mu_d (float) – Value of the dynamic friction coefficient, in [0;inf[. Usually between 0 and 1.

See also: setStaticFriction(mu_s)()

setFluidBottomFixedFlux(specific_flux)

Define a constant fluid flux normal to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidBottomFixedPressure().

Parameters

specific_flux – Specific flux values across boundary (positive values upwards), [m/s]

setFluidBottomFixedPressure()

Set the lower boundary of the fluid domain to follow the fixed pressure value (Dirichlet) boundary condition.

This is the default behavior for the boundary. See also setFluidBottomNoFlow()

setFluidBottomNoFlow()

Set the lower boundary of the fluid domain to follow the no-flow (Neumann) boundary condition with free slip parallel to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidBottomFixedPressure().

setFluidBottomNoFlowNoSlip()

Set the lower boundary of the fluid domain to follow the no-flow (Neumann) boundary condition with no slip parallel to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidBottomFixedPressure().

setFluidCompressibility(beta_f)

Set the fluid adiabatic compressibility [1/Pa]. This value is equal to 1/K where K is the bulk modulus [Pa]. The value for water is 5.1e-10 for water at 0 degrees Celcius. This parameter is used for the Darcy solver exclusively.

Parameters

beta_f (float) – The fluid compressibility [1/Pa]

See also: setFluidDensity() and setFluidViscosity()

setFluidDensity(rho_f)

Set the fluid density [kg/(m*m*m)]. The value for water is 1000. This parameter is used for the Navier-Stokes fluid solver exclusively.

Parameters

rho_f (float) – The fluid density [kg/(m*m*m)]

See also: setFluidViscosity() and

setFluidCompressibility()

setFluidPressureModulation(A, f, phi=0.0, plot=False)

Set the parameters for the sine wave modulating the fluid pressures at the top boundary. Note that a cos-wave is obtained with phi=pi/2.

Parameters
  • A (float) – Fluctuation amplitude [Pa]

  • f (float) – Fluctuation frequency [Hz]

  • phi (float) – Fluctuation phase shift (default=0.0) [rad]

  • plot (bool) – Show a plot of the resulting modulation

See also: setTopWallNormalStressModulation() and disableFluidPressureModulation()

setFluidTopFixedFlux(specific_flux)

Define a constant fluid flux normal to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidBottomFixedPressure().

Parameters

specific_flux – Specific flux values across boundary (positive values upwards), [m/s]

setFluidTopFixedPressure()

Set the upper boundary of the fluid domain to follow the fixed pressure value (Dirichlet) boundary condition.

This is the default behavior for the boundary. See also setFluidTopNoFlow()

setFluidTopNoFlow()

Set the upper boundary of the fluid domain to follow the no-flow (Neumann) boundary condition with free slip parallel to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidTopFixedPressure().

setFluidTopNoFlowNoSlip()

Set the upper boundary of the fluid domain to follow the no-flow (Neumann) boundary condition with no slip parallel to the boundary.

The default behavior for the boundary is fixed value (Dirichlet), see setFluidTopFixedPressure().

setFluidViscosity(mu)

Set the fluid dynamic viscosity [Pa*s]. The value for water is 1.797e-3 at 0 degrees Celcius. This parameter is used for both the Darcy and Navier-Stokes fluid solver.

Parameters

mu (float) – The fluid dynamic viscosity [Pa*s]

See also: setFluidDensity() and

setFluidCompressibility()

setFluidXFixedPressure()

Set the X boundaries of the fluid domain to follow the fixed pressure value (Dirichlet) boundary condition.

This is not the default behavior for the boundary. See also setFluidXFixedPressure(), setFluidXNoFlow(), and setFluidXPeriodic() (default)

setFluidXNoFlow()

Set the X boundaries of the fluid domain to follow the no-flow (Neumann) boundary condition.

This is not the default behavior for the boundary. See also setFluidXFixedPressure(), setFluidXNoFlow(), and setFluidXPeriodic() (default)

setFluidXPeriodic()

Set the X boundaries of the fluid domain to follow the periodic (cyclic) boundary condition.

This is the default behavior for the boundary. See also setFluidXFixedPressure() and setFluidXNoFlow()

setFluidYFixedPressure()

Set the Y boundaries of the fluid domain to follow the fixed pressure value (Dirichlet) boundary condition.

This is not the default behavior for the boundary. See also setFluidYNoFlow() and setFluidYPeriodic() (default)

setFluidYNoFlow()

Set the Y boundaries of the fluid domain to follow the no-flow (Neumann) boundary condition.

This is not the default behavior for the boundary. See also setFluidYFixedPressure() and setFluidYPeriodic() (default)

setFluidYPeriodic()

Set the Y boundaries of the fluid domain to follow the periodic (cyclic) boundary condition.

This is the default behavior for the boundary. See also setFluidYFixedPressure() and setFluidYNoFlow()

setGamma(gamma)

Gamma is a fluid solver parameter, used for smoothing the pressure values. The epsilon (pressure) values are smoothed by including the average epsilon value of the six closest (face) neighbor cells. This parameter should be in the range [0.0;1.0[. The higher the value, the more averaging is introduced. A value of 0.0 disables all averaging.

The default and recommended value is 0.0.

Parameters

theta (float) – The smoothing parameter value

Other solver parameter setting functions: setTheta(), setBeta(), setTolerance(), setDEMstepsPerCFDstep() and setMaxIterations()

setMaxIterations(maxiter)

A fluid solver parameter, the value of the maxiter parameter denotes the maximal allowed number of fluid solver iterations before ending the fluid solver loop prematurely. The residual values are at that point not fulfilling the tolerance criteria. The parameter is included to avoid infinite hangs.

The default and recommended value is 1e4.

Parameters

maxiter (int) – The maximum number of Jacobi iterations in the fluid solver

Other solver parameter setting functions: setGamma(), setTheta(), setBeta(), setDEMstepsPerCFDstep() and setTolerance()

setPermeabilityGrainSize(verbose=True)

Set the permeability prefactor based on the mean grain size (Damsgaard et al., 2015, eq. 10).

Parameters

verbose (bool) – Print information about the realistic permeabilities hydraulic conductivities to expect with the chosen permeability prefactor.

setPermeabilityPrefactor(k_c, verbose=True)

Set the permeability prefactor from Goren et al 2011, eq. 24. The function will print the limits of permeabilities to be simulated. This parameter is only used in the Darcy solver.

Parameters
  • k_c (float) – Permeability prefactor value [m*m]

  • verbose (bool) – Print information about the realistic permeabilities and hydraulic conductivities to expect with the chosen permeability prefactor.

setStaticFriction(mu_s)

Set the static friction coefficient for particle-particle interactions (self.mu_s). This value describes the resistance to a shearing motion while it is not happenind (contact tangential velocity zero).

Parameters

mu_s (float) – Value of the static friction coefficient, in [0;inf[. Usually between 0 and 1.

See also: setDynamicFriction(mu_d)()

setStiffnessNormal(k_n)

Set the elastic stiffness (k_n) in the normal direction of the contact.

Parameters

k_n (float) – The elastic stiffness coefficient [N/m]

setStiffnessTangential(k_t)

Set the elastic stiffness (k_t) in the tangential direction of the contact.

Parameters

k_t (float) – The elastic stiffness coefficient [N/m]

setTheta(theta)

Theta is a fluid solver under-relaxation parameter, used in solution of Poisson equation. The value should be within the range ]0.0;1.0]. At a value of 1.0, the new estimate of epsilon values is used exclusively. At lower values, a linear interpolation between new and old values is used. The solution typically converges faster with a value of 1.0, but instabilities may be avoided with lower values.

The default and recommended value is 1.0.

Parameters

theta (float) – The under-relaxation parameter value

Other solver parameter setting functions: setGamma(), setBeta(), setTolerance(), setDEMstepsPerCFDstep() and setMaxIterations()

setTolerance(tolerance)

A fluid solver parameter, the value of the tolerance parameter denotes the required value of the maximum normalized residual for the fluid solver.

The default and recommended value is 1.0e-3.

Parameters

tolerance (float) – The tolerance criteria for the maximal normalized residual

Other solver parameter setting functions: setGamma(), setTheta(), setBeta(), setDEMstepsPerCFDstep() and setMaxIterations()

setTopWallNormalStressModulation(A, f, plot=False)

Set the parameters for the sine wave modulating the normal stress at the top wall. Note that a cos-wave is obtained with phi=pi/2.

Parameters
  • A (float) – Fluctuation amplitude [Pa]

  • f (float) – Fluctuation frequency [Hz]

  • plot (bool) – Show a plot of the resulting modulation

See also: setFluidPressureModulation() and disableTopWallNormalStressModulation()

setYoungsModulus(E)

Set the elastic Young’s modulus (E) for the contact model. This parameter is used over normal stiffness (k_n) and tangential stiffness (k_t) when its value is greater than zero. Using this parameter produces size-invariant behavior.

Example values are ~70e9 Pa for quartz, http://www.engineeringtoolbox.com/young-modulus-d_417.html

Parameters

E (float) – The elastic modulus [Pa]

shear(shear_strain_rate=1.0, shear_stress=False)

Setup shear experiment either by a constant shear rate or a constant shear stress. The shear strain rate is the shear velocity divided by the initial height per second. The shear movement is along the positive x axis. The function zeroes the tangential wall viscosity (gamma_wt) and the wall friction coefficients (mu_ws, mu_wn).

Parameters
  • shear_strain_rate (float) – The shear strain rate [-] to use if shear_stress isn’t False.

  • shear_stress (float or bool) – The shear stress value to use [Pa].

shearDisplacement()

Calculates and returns the current shear displacement. The displacement is found by determining the total x-axis displacement of the upper, fixed particles.

Returns

The total shear displacement [m]

Return type

float

See also: shearStrain() and shearVelocity()

shearStrain()

Calculates and returns the current shear strain (gamma) value of the experiment. The shear strain is found by determining the total x-axis displacement of the upper, fixed particles.

Returns

The total shear strain [-]

Return type

float

See also: shearStrainRate() and shearVel()

shearStrainRate()

Calculates the shear strain rate (dot(gamma)) value of the experiment.

Returns

The value of dot(gamma)

Return type

float

See also: shearStrain() and shearVel()

shearStress(type='effective')

Calculates the sum of shear stress values measured on any moving particles with a finite and fixed velocity.

Parameters

type (str) – Find the ‘defined’ or ‘effective’ (default) shear stress

Returns

The shear stress in Pa

Return type

numpy.array

shearVel()

Alias of shearVelocity()

shearVelocity()

Calculates and returns the current shear velocity. The displacement is found by determining the total x-axis velocity of the upper, fixed particles.

Returns

The shear velocity [m/s]

Return type

float

See also: shearStrainRate() and shearDisplacement()

sheardisp(graphics_format='pdf', zslices=32)

Plot the particle x-axis displacement against the original vertical particle position. The plot is saved in the current directory with the file name ‘<simulation id>-sheardisp.<graphics_format>’.

Parameters

graphics_format (str) – Save the plot in this format

show(coloring=array([], dtype=float64), resolution=6)

Show a rendering of all particles in a window.

Parameters
  • coloring (numpy.array) – Color the particles from red to white to blue according to the values in this array.

  • resolution (int) – The resolution of the rendered spheres. Larger values increase the performance requirements.

smallestMass()

Returns the mass of the leightest particle.

Parameters

idx (int) – Particle index

Returns

The mass of the particle [kg]

Return type

float

staticGrid()

Set the height of the fluid grid to be constant as set in self.L[2].

See also adaptiveGrid()

status()

Returns the current simulation status by using the simulation id (sid) as an identifier.

Returns

The number of the last output file written

Return type

int

surfaceArea(idx)

Returns the surface area of a particle.

Parameters

idx (int) – Particle index

Returns

The surface area of the particle [m^2]

Return type

float

thinsection_x1x3(x2='center', graphics_format='png', cbmax=None, arrowscale=0.01, velarrowscale=1.0, slipscale=1.0, verbose=False)

Produce a 2D image of particles on a x1,x3 plane, intersecting the second axis at x2. Output is saved as ‘<sid>-ts-x1x3.txt’ in the current folder.

An upper limit to the pressure color bar range can be set by the cbmax parameter.

The data can be plotted in gnuplot with:

gnuplot> set size ratio -1 gnuplot> set palette defined (0 “blue”, 0.5 “gray”, 1 “red”) gnuplot> plot ‘<sid>-ts-x1x3.txt’ with circles palette fs transparent solid 0.4 noborder

This function also saves a plot of the inter-particle slip angles.

Parameters
  • x2 (foat) – The position along the second axis of the intersecting plane

  • graphics_format (str) – Save the slip angle plot in this format

  • cbmax (float) – The maximal value of the pressure color bar range

  • arrowscale (float) – Scale the rotational arrows by this value

  • velarrowscale (float) – Scale the translational arrows by this value

  • slipscale (float) – Scale the slip arrows by this value

  • verbose (bool) – Show function output during calculations

torqueScript(email='adc@geo.au.dk', email_alerts='ae', walltime='24:00:00', queue='qfermi', cudapath='/com/cuda/4.0.17/cuda', spheredir='/home/adc/code/sphere', use_workdir=False, workdir='/scratch')

Creates a job script for the Torque queue manager for the simulation object.

Parameters
  • email (str) – The e-mail address that Torque messages should be sent to

  • email_alerts (str) – The type of Torque messages to send to the e-mail address. The character ‘b’ causes a mail to be sent when the execution begins. The character ‘e’ causes a mail to be sent when the execution ends normally. The character ‘a’ causes a mail to be sent if the execution ends abnormally. The characters can be written in any order.

  • walltime (str) – The maximal allowed time for the job, in the format ‘HH:MM:SS’.

  • queue (str) – The Torque queue to schedule the job for

  • cudapath (str) – The path of the CUDA library on the cluster compute nodes

  • spheredir (str) – The path to the root directory of sphere on the cluster

  • use_workdir (bool) – Use a different working directory than the sphere folder

  • workdir (str) – The working directory during the calculations, if use_workdir=True

totalFrictionalEnergy()

Returns the total frictional dissipated energy for all particles.

Returns

The total frictional energy lost of all particles [J]

Return type

float

totalKineticEnergy()

Returns the total linear kinetic energy for all particles.

Returns

The kinetic energy of all particles [J]

totalMass()

Returns the total mass of all particles.

Returns

The total mass in [kg]

totalMomentum()

Returns the sum of particle momentums.

Returns

The sum of particle momentums (m*v) [N*s]

Return type

numpy.array

totalRotationalEnergy()

Returns the total rotational kinetic energy for all particles.

Returns

The rotational energy of all particles [J]

totalViscousEnergy()

Returns the total viscous dissipated energy for all particles.

Returns

The normal viscous energy lost by all particles [J]

Return type

float

triaxial(wvel=-0.001, normal_stress=10000.0)

Setup triaxial experiment. The upper wall is moved at a fixed velocity in m/s, default values is -0.001 m/s (i.e. downwards). The side walls are exerting a defined normal stress.

Parameters
  • wvel (float) – Upper wall velocity. Negative values mean that the wall moves downwards.

  • normal_stress (float) – The normal stress to apply from the upper wall.

uniaxialStrainRate(wvel=-0.001)

Setup consolidation experiment. Specify the upper wall velocity in m/s, default value is -0.001 m/s (i.e. downwards).

Parameters

wvel (float) – Upper wall velocity. Negative values mean that the wall moves downwards.

video(out_folder='./', video_format='mp4', graphics_folder='../img_out/', graphics_format='png', fps=25, qscale=1, bitrate=1800, verbose=False)

Uses ffmpeg to combine images to animation. All images should be rendered beforehand using render().

Parameters
  • out_folder (str) – The output folder for the video file

  • video_format (str) – The format of the output video

  • graphics_folder (str) – The folder containing the rendered images

  • graphics_format (str) – The format of the rendered images

  • fps (int) – The number of frames per second to use in the video

  • qscale (float) – The output video quality, in ]0;1]

  • bitrate (int) – The bitrate to use in the output video

  • verbose (bool) – Show ffmpeg output

viscousEnergy(idx)

Returns the viscous dissipated energy for a particle.

Parameters

idx (int) – Particle index

Returns

The energy lost by the particle by viscous dissipation [J]

Return type

float

visualize(method='energy', savefig=True, outformat='png', figsize=False, pickle=False, xlim=False, firststep=0, f_min=None, f_max=None, cmap=None, smoothing=0, smoothing_window='hanning')

Visualize output from the simulation, where the temporal progress is of interest. The output will be saved in the current folder with a name combining the simulation id of the simulation, and the visualization method.

Parameters
  • method (str) – The type of plot to render. Possible values are ‘energy’, ‘walls’, ‘triaxial’, ‘inertia’, ‘mean-fluid-pressure’, ‘fluid-pressure’, ‘shear’, ‘shear-displacement’, ‘porosity’, ‘rate-dependence’, ‘contacts’

  • savefig (bool) – Save the image instead of showing it on screen

  • outformat – The output format of the plot data. This can be an image format, or in text (‘txt’).

  • figsize (array) – Specify output figure size in inches

  • pickle (bool) – Save all figure content as a Python pickle file. It can be opened later using fig=pickle.load(open(‘file.pickle’,’rb’)).

  • xlim (array) – Set custom limits to the x axis. If not specified, the x range will correspond to the entire data interval.

  • firststep (int) – The first output file step to read (default: 0)

  • cmap (matplotlib.colors.LinearSegmentedColormap) – Choose custom color map, e.g. cmap=matplotlib.cm.get_cmap(‘afmhot’)

  • smoothing (int) – Apply smoothing across a number of output files to the method=’shear’ plot. A value of less than 3 means that no smoothing occurs.

  • smoothing_window (str) – Type of smoothing to use when smoothing >= 3. Valid values are ‘flat’, ‘hanning’ (default), ‘hamming’, ‘bartlett’, and ‘blackman’.

voidRatio()

Calculates the current void ratio

Returns

The void ratio (pore volume relative to solid volume)

Return type

float

volume(idx)

Returns the volume of a particle.

Parameters

idx (int) – Particle index

Returns

The volume of the particle [m^3]

Return type

float

wall0iz()

Returns the cell index of wall 0 along z.

Returns

z cell index

Return type

int

wet()

Set the simulation to be wet (total fluid saturation).

See also dry()

writeFluidVTK(folder='../output/', cell_centered=True, verbose=True)

Writes a VTK file for the fluid grid to the ../output/ folder by default. The file name will be in the format fluid-<self.sid>.vti. The vti files can be used for visualizing the fluid in ParaView.

The scalars (pressure, porosity, porosity change) and the velocity vectors are either placed in a grid where the grid corners correspond to the computational grid center (cell_centered=False). This results in a grid that doesn’t appears to span the simulation domain, and values are smoothly interpolated on the cell faces. Alternatively, the visualization grid is equal to the computational grid, and cells face colors are not interpolated (cell_centered=True, default behavior).

The fluid grid is visualized by opening the vti files, and pressing “Apply” to import all fluid field properties. To visualize the scalar fields, such as the pressure, the porosity, the porosity change or the velocity magnitude, choose “Surface” or “Surface With Edges” as the “Representation”. Choose the desired property as the “Coloring” field. It may be desirable to show the color bar by pressing the “Show” button, and “Rescale” to fit the color range limits to the current file. The coordinate system can be displayed by checking the “Show Axis” field. All adjustments by default require the “Apply” button to be pressed before regenerating the view.

The fluid vector fields (e.g. the fluid velocity) can be visualizing by e.g. arrows. To do this, select the fluid data in the “Pipeline Browser”. Press “Glyph” from the “Common” toolbar, or go to the “Filters” mennu, and press “Glyph” from the “Common” list. Make sure that “Arrow” is selected as the “Glyph type”, and “Velocity” as the “Vectors” value. Adjust the “Maximum Number of Points” to be at least as big as the number of fluid cells in the grid. Press “Apply” to visualize the arrows.

To visualize the cell-centered data with smooth interpolation, and in order to visualize fluid vector fields, the cell-centered mesh is selected in the “Pipeline Browser”, and is filtered using “Filters” -> “Alphabetical” -> “Cell Data to Point Data”.

If several data files are generated for the same simulation (e.g. using the writeVTKall() function), it is able to step the visualization through time by using the ParaView controls.

Parameters
  • folder (str) – The folder where to place the output binary file (default (default=’../output/’)

  • cell_centered (bool) – put scalars and vectors at cell centers (True) or cell corners (False), (default=True)

  • verbose (bool) – Show diagnostic information (default=True)

writeVTK(folder='../output/', verbose=True)

Writes a VTK file with particle information to the ../output/ folder by default. The file name will be in the format <self.sid>.vtu. The vtu files can be used to visualize the particles in ParaView.

After opening the vtu files, the particle fields will show up in the “Properties” list. Press “Apply” to import all fields into the ParaView session. The particles are visualized by selecting the imported data in the “Pipeline Browser”. Afterwards, click the “Glyph” button in the “Common” toolbar, or go to the “Filters” menu, and press “Glyph” from the “Common” list. Choose “Sphere” as the “Glyph Type”, choose “scalar” as the “Scale Mode”. Check the “Edit” checkbox, and set the “Set Scale Factor” to 1.0. The field “Maximum Number of Points” may be increased if the number of particles exceed the default value. Finally press “Apply”, and the particles will appear in the main window.

The sphere resolution may be adjusted (“Theta resolution”, “Phi resolution”) to increase the quality and the computational requirements of the rendering. All adjustments by default require the “Apply” button to be pressed before regenerating the view.

If several vtu files are generated for the same simulation (e.g. using the writeVTKall() function), it is able to step the visualization through time by using the ParaView controls.

Parameters
  • folder (str) – The folder where to place the output binary file (default (default=’../output/’)

  • verbose (bool) – Show diagnostic information (default=True)

writeVTKall(cell_centered=True, verbose=True, forces=False)

Writes a VTK file for each simulation output file with particle information and the fluid grid to the ../output/ folder by default. The file name will be in the format <self.sid>.vtu and fluid-<self.sid>.vti. The vtu files can be used to visualize the particles, and the vti files for visualizing the fluid in ParaView.

After opening the vtu files, the particle fields will show up in the “Properties” list. Press “Apply” to import all fields into the ParaView session. The particles are visualized by selecting the imported data in the “Pipeline Browser”. Afterwards, click the “Glyph” button in the “Common” toolbar, or go to the “Filters” menu, and press “Glyph” from the “Common” list. Choose “Sphere” as the “Glyph Type”, set “Radius” to 1.0, choose “scalar” as the “Scale Mode”. Check the “Edit” checkbox, and set the “Set Scale Factor” to 1.0. The field “Maximum Number of Points” may be increased if the number of particles exceed the default value. Finally press “Apply”, and the particles will appear in the main window.

The sphere resolution may be adjusted (“Theta resolution”, “Phi resolution”) to increase the quality and the computational requirements of the rendering.

The fluid grid is visualized by opening the vti files, and pressing “Apply” to import all fluid field properties. To visualize the scalar fields, such as the pressure, the porosity, the porosity change or the velocity magnitude, choose “Surface” or “Surface With Edges” as the “Representation”. Choose the desired property as the “Coloring” field. It may be desirable to show the color bar by pressing the “Show” button, and “Rescale” to fit the color range limits to the current file. The coordinate system can be displayed by checking the “Show Axis” field. All adjustments by default require the “Apply” button to be pressed before regenerating the view.

The fluid vector fields (e.g. the fluid velocity) can be visualizing by e.g. arrows. To do this, select the fluid data in the “Pipeline Browser”. Press “Glyph” from the “Common” toolbar, or go to the “Filters” mennu, and press “Glyph” from the “Common” list. Make sure that “Arrow” is selected as the “Glyph type”, and “Velocity” as the “Vectors” value. Adjust the “Maximum Number of Points” to be at least as big as the number of fluid cells in the grid. Press “Apply” to visualize the arrows.

If several data files are generated for the same simulation (e.g. using the writeVTKall() function), it is able to step the visualization through time by using the ParaView controls.

Parameters
  • verbose (bool) – Show diagnostic information (default=True)

  • cell_centered (bool) – Write fluid values to cell centered positions (default=true)

  • forces (bool) – Write contact force files (slow) (default=False)

writeVTKforces(folder='../output/', verbose=True)

Writes a VTK file with particle-interaction information to the ../output/ folder by default. The file name will be in the format <self.sid>.vtp. The vtp files can be used to visualize the particle interactions in ParaView. First use the “Cell Data to Point Data” filter, and afterwards show the contact network with the “Tube” filter.

Parameters
  • folder (str) – The folder where to place the output file (default (default=’../output/’)

  • verbose (bool) – Show diagnostic information (default=True)

writebin(folder='../input/', verbose=True)

Writes a sphere binary file to the ../input/ folder by default. The file name will be in the format <self.sid>.bin.

See also readbin().

Parameters
  • folder (str) – The folder where to place the output binary file

  • verbose (bool) – Show diagnostic information (default=True)

zeroKinematics()

Zero all kinematic parameters of the particles. This function is useful when output from one simulation is reused in another simulation.

sphere.status(project)

Check the status.dat file for the target project, and return the last output file number.

Parameters

project (str) – The simulation id of the target project

Returns

The last output file written in the simulation calculations

Return type

int

sphere.thinsectionVideo(project, out_folder='./', video_format='mp4', fps=25, qscale=1, bitrate=1800, verbose=False)

Uses ffmpeg to combine thin section images to an animation. This function will implicity render the thin section images beforehand.

Parameters
  • project (str) – The simulation id of the project to render

  • out_folder (str) – The output folder for the video file

  • video_format (str) – The format of the output video

  • fps (int) – The number of frames per second to use in the video

  • qscale (float) – The output video quality, in ]0;1]

  • bitrate (int) – The bitrate to use in the output video

  • verbose (bool) – Show ffmpeg output

sphere.torqueScriptParallel3(obj1, obj2, obj3, email='adc@geo.au.dk', email_alerts='ae', walltime='24:00:00', queue='qfermi', cudapath='/com/cuda/4.0.17/cuda', spheredir='/home/adc/code/sphere', use_workdir=False, workdir='/scratch')

Create job script for the Torque queue manager for three binaries, executed in parallel, ideally on three GPUs.

Parameters
  • email (str) – The e-mail address that Torque messages should be sent to

  • email_alerts (str) – The type of Torque messages to send to the e-mail address. The character ‘b’ causes a mail to be sent when the execution begins. The character ‘e’ causes a mail to be sent when the execution ends normally. The character ‘a’ causes a mail to be sent if the execution ends abnormally. The characters can be written in any order.

  • walltime (str) – The maximal allowed time for the job, in the format ‘HH:MM:SS’.

  • queue (str) – The Torque queue to schedule the job for

  • cudapath (str) – The path of the CUDA library on the cluster compute nodes

  • spheredir (str) – The path to the root directory of sphere on the cluster

  • use_workdir (bool) – Use a different working directory than the sphere folder

  • workdir (str) – The working directory during the calculations, if use_workdir=True

Returns

The filename of the script

Return type

str

See also torqueScript()

sphere.video(project, out_folder='./', video_format='mp4', graphics_folder='../img_out/', graphics_format='png', fps=25, verbose=True)

Uses ffmpeg to combine images to animation. All images should be rendered beforehand using render().

Parameters
  • project (str) – The simulation id of the project to render

  • out_folder (str) – The output folder for the video file

  • video_format (str) – The format of the output video

  • graphics_folder (str) – The folder containing the rendered images

  • graphics_format (str) – The format of the rendered images

  • fps (int) – The number of frames per second to use in the video

  • qscale (float) – The output video quality, in ]0;1]

  • bitrate (int) – The bitrate to use in the output video

  • verbose (bool) – Show ffmpeg output