Sailfish logo

Table Of Contents

Previous topic

Examples and test cases

Next topic

About

This Page

External links

Sailfish API

Simulation models

lb_base

Base class for all lattice Boltzman simulations in Sailfish.

class lb_base.FieldPair

FieldPair(abstract, buffer)

abstract

Alias for field number 0

buffer

Alias for field number 1

class lb_base.ForcePair

ForcePair(numeric, symbolic)

numeric

Alias for field number 0

symbolic

Alias for field number 1

class lb_base.KernelPair

KernelPair(primary, secondary)

primary

Alias for field number 0

secondary

Alias for field number 1

class lb_base.LBMixIn

Provides additional functionliaty to a simulation class.

Some attributes of objects descentant from this class are processed in addition to the corresponding attribution from a simulation class (LBSim descentant). These are:

  • aux_code
  • before_main_loop
  • fields
class lb_base.LBSim(config)

Describes a specific type of a lattice Boltzmann simulation.

aux_code = []

List of additional template files or inline code fragments to include

subdomain_runner = None

Set this to a class implementing the SubdomainRunner interface in order

nonlocality = 0

How many layers of nearest neighbors nodes are required by the model.

equilibria = None

Tuple of functions to call to get a list of expressions for the equilibrium

constants()

Returns a dict mapping names to values and defining global constants for the simulation.

update_context(ctx)

Updates the context dicitionary containing variables used for code generation.

verify_fields()

Verifies that fields have not accidentally been overridden.

grid

Returns a grid object representing the connectivity of the lattice used in the simulation. If the simulation uses more than 1 grid, returns the grid with the highest connectivity.

need_output()

Returns True when data will be required for output, based on command line parameters –from –every.

Called from SubdomainRunner.main().

need_sync_fields()

Indicates whether computation/transfer of macroscopic fields is requested.

This is true if either data is to be output after the current step, or data was requested e.g. by after_step(). To get fields on the host in after_step(), set need_sync_flag to True. To get fields on the GPU only, set need_fields_flags to True.

Called from SubdomainRunner.main().

Returns:
tuple of two boolean values; the first is True if synchronization of fields to the host is requested; the second is True if computation of macroscopic fields is requested.
need_checkpoint()

Returns True when a checkpoint is requested after the current iteration.

before_main_loop(runner)

Called from the subdomain runner before entering the main loop of the simulation.

This function can be used to initialize additional buffers and kernels that are then going to be used in after_step().

after_step(runner)

Called from the main loop after the completion of every step.

after_main_loop(runner)

Called after the main loop.

get_compute_kernels(runner, full_output, bulk)
Parameters:
  • runner – SubdomainRunner object
  • full_output – if True, returns kernels that prepare fields for visualization or saving into a file
  • bulk – if True, returns kernels that process the bulk domain, otherwise returns kernels that process the subdomain boundary
class lb_base.LBForcedSim(config)

Adds support for body forces.

This is a mix-in class. When defining a new simulation, inherit from another LBSim-based class first.

add_body_force(force, grid=0, accel=True)

Adds a constant global force field acting on the fluid.

Multiple calls to this function will add the value of force to any previously set value. Forces and accelerations are processed separately and are never mixed in this addition process.

Parameters:
  • force – n-vector representing the force value; this can be a vector of basic Python types, a numpy vector, or a DynamicValue object
  • grid – grid number on which this force is acting
  • accel – if True, the added field is an acceleration field, otherwise it is an actual force field
use_force_for_equilibrium(force_grid, target_grid)

Makes it possible to use acceleration from force_grid when calculating velocity for the equlibrium of target_grid.

For instance, to use the acceleration from grid 0 in relaxation of grid 1, use the parameters (0, 1).

To disable acceleration on a grid, pass an invalid grid ID in force_grid (e.g. None or -1).

Note: this is currently only supported in the free-energy MRT model. The force reassignment will be silently ignored in other models.

Parameters:
  • force_grid – grid ID from which the acceleration will be used
  • target_grid – grid ID on which the acceleration will act
add_force_coupling(grid_a, grid_b, const_name)

Adds a Shan-Chen type coupling between two lattices.

Parameters:
  • grid_a – numerical ID of the first lattice
  • grid_b – numerical ID of the second lattice
  • const_name – name of the global variable containing the value of the coupling constant
class lb_base.ForceObject(start, end)

Used to track momentum exchange between the fluid and a solid object.

The exchanged momentum can be used to compute the value of the force acting on the solid object. See Ladd A. Effects of container walls on the velocity fluctuations of sedimenting spheres. Phys Rev Lett 2002; 88:048301 for more info about this procedure.

Parameters:
  • start – N-tuple indicating lowest coordinates of the bounding box of the object
  • end – N-tuple indicating highest coordinates of the bounding box of the object
force()
Rvalue :N-tuple of force components

lb_single

Classes for single fluid lattice Boltzmann simulations.

class lb_single.LBFluidSim(config)

Simulates a single fluid.

class lb_single.LBEntropicFluidSim(config)

LBFluidSim with alpha field tracking.

The alpha field is 2.0 in areas where the fluid dynamics is fully resolved. alpha < 2.0 means that the flow field is smoothened, while alpha > 2.0 indicates enhancement of flow perturbation.

class lb_single.LBFreeSurface(config)

Free surface lattice Boltzmann model.

class lb_single.LBSingleFluidShanChen(config)

Single-phase Shan-Chen model.

subdomain_runner

alias of NNSubdomainRunner

lb_binary

Classes for binary fluid lattice Boltzmann simulations.

class lb_binary.LBBinaryFluidBase(config)

Base class for binary fluid simulations.

subdomain_runner

alias of NNSubdomainRunner

class lb_binary.LBBinaryFluidFreeEnergy(config)

Binary fluid mixture using the free-energy model.

class lb_binary.LBBinaryFluidShanChen(config)

Binary fluid mixture using the Shan-Chen model.

Geometry

geo

Classes to specify global LB simulation geometry and its partitions.

class geo.LBGeometry(config)

Describes the high-level geometry of a LB simulation.

class geo.LBGeometry2D(config)

Describes the high-level 2D geometry of a LB simulation.

subdomains()

Returns a 1-element list containing a single 2D block covering the whole domain.

class geo.LBGeometry3D(config)

Describes the high-level 3D geometry of a LB simulation.

subdomains()

Returns a 1-element list containing a single 3D block covering the whole domain.

class geo.EqualSubdomainsGeometry2D(config)

Divides a rectangular domain into a configurable number of equal-size subdomains connected along one of the base axes.

class geo.EqualSubdomainsGeometry3D(config)

Divides a cuboid domain into a configurable number of equal-size subdomains connected along one of the base axes.

subdomain

Intra- and inter-subdomain geometry processing.

class subdomain.ConnectionPair

ConnectionPair(src, dst)

dst

Alias for field number 1

src

Alias for field number 0

class subdomain.SubdomainPair

SubdomainPair(real, virtual)

real

Alias for field number 0

virtual

Alias for field number 1

class subdomain.SubdomainSpec(location, size, envelope_size=None, id_=None, *args, **kwargs)

A lightweight class describing the location of a subdomain and its connections to other subdomains in the simulation.

This class does not contain any references to the actual GPU or host data structures necessary to run the simulation for this subdomain.

periodic_x

X-axis periodicity within this subdomain.

periodic_y

Y-axis periodicity within this subdomain.

enable_local_periodicity(axis)

Makes the subdomain locally periodic along a given axis.

get_connection(face, subdomain_id)

Returns a LBConnection object describing the connection to ‘subdomain_id’ via ‘face’.

connecting_subdomains()

Returns a list of pairs: (face, subdomain ID) representing connections to different subdomains.

classmethod face_to_axis(face)

Returns the axis number corresponding to a face constant.

face_to_normal(face)

Returns the normal vector for a face.

connect(pair, grid=None)

Creates a connection between this subdomain and another subdomain.

A connection can only be created when the subdomains are next to each other.

Returns:True if the connection was successful
Return type:bool
class subdomain.Subdomain(grid_shape, spec, grid, *args, **kwargs)

Holds all field and geometry information specific to the subdomain described by the corresponding SubdomainSpec. Objects of this class do not directly know about the details of memory management on the compute device.

Parameters:
  • grid_shape – size of the lattice for the simulation; X dimension is the last element in the tuple
  • spec – SubdomainSpec for this subdomain
  • grid – grid object specifying the connectivity of the lattice
load_active_node_map(*args)

Populates active_node_mask with a dense Boolean array.

The array coreesponds to the volume described by SubdomainSpec, including ghost nodes. Nodes marked True indicate active nodes participating in the simulation.

select_subdomain(array, hx, hy, *args)

Returns part of array corresponding to the subdomain.

Parameters:array – array to select from; the array should cover ghost nodes

Use this with arrays covering all nodes in the global simulation domain. Args are the index arrays hx, hy, [hz].

set_active_node_map_from_wall_map(wall_map)

Sets the active node map from a wall map.

Takes care of ensuring that only a single layer of wall nodes is remains as active nodes. To be used in load_active_node_map().

Parameters:wall_map – Boolean array covering all nodes, including ghosts. True indicates a solid node not participating in the simulation. These nodes would typically be set to NTFullBBWall or similar.
set_node(where, node_type)

Set a boundary condition at selected node(s).

Parameters:
  • where – index expression selecting nodes to set
  • node_type – LBNodeType subclass or instance
update_node(where, node_type)

Updates a boundary condition at selected node(s).

Use this method only to update nodes in a _running_ simulation. See set_node for a description of params.

tag_directions()

Creates direction tags for nodes that support it.

Direction tags are a way of summarizing which distributions at a node will be undefined after streaming.

Rvalue :True if there are any nodes supporting tagging, False otherwise
get_fo_distributions(fo)

Computes an array indicating which distributions correspond to momentum trasferred from the object to the fluid.

Parameters:fo – ForceObject description the object to analyze
Rvalue :dict: distribution index -> N-tuple of arrays indicating coordinates of solid object nodes transferring momentum to the fluid in the direction corresponding to the distribution
scratch_space_size

Node scratch space size expressed in number of floating point values.

visualization_map()

Returns an unencoded type map for visualization/ postprocessing purposes.

fluid_map(wet=True)

Returns a boolean array indicating which nodes are “wet” ( represent fluid and have valid macroscopic fields).

node_type

Supporting code for different node types.

class node_type.ScratchSize

ScratchSize(dim2, dim3)

dim2

Alias for field number 0

dim3

Alias for field number 1

class node_type.LBNodeType(**params)

Base class for node types.

wet_node = False

If True, the node undergoes normal relaxation process.

excluded = False

If True, the node does not participate in the simulation.

propagation_only = False

If True, the node participates in the propagation step only. This is necessary for some schemes that use propagation in shared memory.

standard_macro = False

If True, the node does not require any special processing to calculate macroscopic fluid quantities. Typical examples of nodes requiring special treatment are edge and corner nodes where not all mass fractions are known.

needs_orientation = False

If True, the node needs a basic orientation vector (only primary directions are currently supported).

If True, the node supports tagging of active directions (i.e. of links that connect it to a fluid node.

scratch_space = 0

Number of floating point values that the node needs to keep as additional information in global memory. This can be an int or an instance of ScratchSize.

location = 0.0

Indicates the effective location of the boundary condition along the direction of the normal vector. Positive values indicate offset towards the fluid domain, negative values indicate offset away from the fluid domain.

classmethod scratch_space_size(dim)

Returns the required size (# of floats) of the scratch space.

Parameters:dim – dimensionality of the simulation (2 or 3)
class node_type.NTHalfBBWall(**params)

Half-way bounce-back (no-slip) node.

The effective location of the wall is half a lattice spacing away from the bulk of the fluid. With such a location of the wall, this node type provides 2nd order spatial accuracy.

The idea of a half-way bounce-back node is similar to the full-way bounce-back, but the reflection takes only one time step f_{i}^{pre}(x, t+1) = f_{opp(i)}^{post}(x, t).

For non-stationary flows the half-way bounce-back rule is more accurate than the full-way bounce-back. For stationary flows there is no difference between them as the one step time lag in the full-way bounce-back rule does not impact the amount of momentum and mass transferred between the fluid and the boundary.

The wall normal vector is necessary for the half-way bounce-back rule to work as only the unknown distributions (those for which there is no data streaming from other nodes) at the boundary nodes are replaced.

class node_type.NTFullBBWall(**params)

Full-way bounce-back (no-slip) node.

Use this node type if you need walls whose normal vector is unknown or is not aligned with the Cartesian axes.

The effective location of the wall is half a lattice spacing between the wall node and the fluid node. With such a location of the wall, this node type provides 2nd order spatial accuracy.

Full-way bounce-back works as follows:

  • at time t distributions are propagated from the fluid to the bounce-back node
  • at time t+1 the distributions at the bounce-back node are reflected across the node center, and then streamed in the standard way

This can be summarized as f_{i}^{pre}(x, t+2) = f_{opp(i)}^{post}(x, t) since it takes two time steps for the reflected distributions to reach back the fluid nodes.

class node_type.NTWallTMS(**params)

Wall boundary condition for turbulent flows, based on the Tamm-Mott-Smith approximation.

For more info see: S.S. Chikatamarla, I.V. Karlin, “Entropic lattice Boltzmann method for turbulent flow simulations: Boundary conditions”, Physica A (2013), doi: 10.1016/j.physa.2012.12.034

class node_type.NTEquilibriumDensity(density, orientation=None)

Density boundary condition using the equilibrium distribution.

class node_type.NTRegularizedDensity(density, orientation=None)

Density boundary condition using the regularized LB model and non-equilibrium bounce-back.

See Phys. Rev. E 77, 056703 (2008) for more info.

class node_type.NTGuoDensity(density)

Guo density.

class node_type.NTZouHeDensity(density, orientation=None)

Zou-He density.

Uses bounce-back of the off-equilibrium distributions.

class node_type.NTEquilibriumVelocity(velocity, orientation=None)

Velocity boundary condition using the equilibrium distribution.

class node_type.NTZouHeVelocity(velocity, orientation=None)

Zou-He velocity.

Uses bounce-back of the off-equilibrium distributions.

class node_type.NTRegularizedVelocity(velocity, orientation=None)

Velocity boundary condition using the regularized LB model and non-equilibrium bounce-back.

See Phys. Rev. E 77, 056703 (2008) for more info.

class node_type.NTGradFreeflow(**params)

Outflow node using Grad’s approximation.

Note: this node type currently only works with the AB memory layout.

class node_type.NTDoNothing(**params)

Outflow node without any special processing for undefined distributions.

The value from the previous time step is retained for all undefined distributions (i.e. pointing into the domain at the boundary).

Using this boundary condition is only necessary with the AA memory layout. In the AB memory layout, leaving the outflow nodes defined as NTFluid works just fine.

class node_type.NTCopy(**params)

Copies distributions from another node.

This can be used to implement a crude vanishing gradient boundary condition.

class node_type.NTYuOutflow(**params)

Implements the open boundary condition described in:

Yu, D., Mei, R. and Shyy, W. (2005) ‘Improved treatment of the open boundary in the method of lattice Boltzmann equation’, page 5.

This is an extrapolation based method, using data from next-nearest neighbors:

f_i(x_j) = 2 f_i(x_j - n) - f_i(x_j - 2n)

class node_type.NTNeumann(**params)

Implements a Neumann boundary condition.

This is a nonlocal boundary condition accessing the nearest neighbors. Note that this condition requires a layer of ghost nodes to be present in the direction pointed to by the normal vector.

Based on the NBC description in: Junk M, Yang Z, Outflow boundary conditions for the lattice Boltzmann method, Progress in Computational Fluid Dynamics, Vol. 8, Nos. 1–4, 2008

Implements:

\frac{\partial u}{\partial n (t, x_j)} = \varphi(t, x_j)

via:

\phi(t, x_{j0}) = u(t, x_{j1}) + 2 \varphi (t, x_j)

f_i(t+1, x_{j0}) = f_{\mathrm{\bar{i}}}^c(t, x_{j0} + c_i) +
6 w_i \phi(t, x_{j0}) \cdot c_i

with:

  • x_j: boundary node
  • x_{j0}: ghost node
  • x_{j1}: fluid node at x_{j0} - 2 * normal
  • c_i: incoming distributions
  • \bar{i}: direction opposite to i
  • f_i^c: distribution after collision (prior to streaming)
class node_type.NTSlip(**params)

Full-slip node.

node_type.multifield(values, where=None)

Collapses a list of numpy arrays into a structured field that can be used for setting boundary condition parameters at multiple nodes at the same time.

Parameters:
  • values – iterable of ndarrays or floats
  • where – numpy boolean array or indexing expression to select nodes from the arrays in ‘values’; if you are creating the fields in ‘values’ using mgrid expressions (with hx, hy, ...) which cover the whole subdomain, ‘where’ should be the same array you’re passing to set_node
class node_type.DynamicValue(*params)

A node parameter that is evaluated on the device.

This is typically used for time-dependent boundary conditions.

Parameters:params – sympy expressions
has_symbols(*args)

Returns True if any of the expressions used for this DynamicValue depends on at least one of the symbols provided as arguments.

get_timeseries()

Returns a generator iterating over all time series used in params.

class node_type.LinearlyInterpolatedTimeSeries(data, step_size=1.0)

A time-dependent scalar data source based on a discrete time series.

A continuous scalar data source from a discrete time series.

Time series data points are linearly interpolated in order to generate values for points not present in the time series. The time series is wrapped in order to generate an infinite sequence.

Parameters:
  • data – iterable of scalar values
  • step_size – number of LB iterations corresponding to one unit in the time series (i.e. time distance between two neighboring points).
data_hash()

Returns a hash of the underying data series.

Symbolic computation

sym

Helper code for symbolic processing and RTCG.

sym.alpha_series()

See Phys Rev Lett 97, 010201 (2006) for the expression.

sym.bb_swap_pairs(grid)

Get a set of indices which have to be swapped for a full bounce-back.

sym.missing_dirs_from_tag(grid, tag_code)

Generates a list of missing mass fractions given an orientation tag code.

Useful to debugging.

Parameters:
  • grid – grid object
  • tag_code – encoded map of missing mass fractions; bits set to 1 indicate directions pointing to fluid nodes
sym.get_missing_dists(grid, orientation)

Returns an iterable of missing distribution indices.

Parameters:
  • grid – grid object
  • orientation – orientation code
sym.ex_rho(grid, distp, incompressible, missing_dir=None)

Express density as a function of the distributions.

Parameters:
  • distp – name of the pointer to the distribution structure
  • incompressible – if True, an expression for the incompressible model will be returned
  • missing_dir – direction number specified if an expression for a node where not all distributions are known is necessary. This parameter identifies the normal vector pointing towards the fluid (i.e. the distributions in this direction are unknown).
Return type:

sympy expression for the density

sym.ex_velocity(grid, distp, comp, config, momentum=False, missing_dir=None, par_rho=None)

Express velocity as a function of the distributions.

Parameters:
  • distp – name of the pointer to the distribution structure
  • comp – velocity component number: 0, 1 or 2 (for 3D lattices)
  • config – LBConfig object
  • momentum – if True, an expression for momentum is returned instead of for velocity
  • missing_dir – direction number specified if an expression for a node where not all distributions are known is necessary. This parameter identifies the normal vector pointing towards the fluid (i.e. the distributions in this direction are unknown).
  • par_rho – name of the variable (a string) containing the externally imposed density (e.g. from a boundary condition)
  • roundoff – if True, the round-off optimization model is used and rho should be replaced by (1.0 + rho) in calculations.
Return type:

sympy expression for the velocity in a given direction

sym.get_prop_dists(grid, dir_, axis=0)

Computes a list of base vectors with a specific value of the X component (dir).

sym.get_interblock_dists(grid, direction, opposite=False)

Computes a list of indices of distributions that would be transferred to a node pointed to by the vector ‘direction’.

sym.grad_approx(grid)

Returns expressions for the Grad distributions as defined by Eq. 11 in EPL 74 (2), pp. 215-221 (2006).

Parameters:grid – a grid object
sym.reglb_flux_tensor(grid)

Returns expressions for the non-equilibrium flux tensor contraction with the Q tensor, used for the regularized LB model.

sym.orthogonalize(*vectors)

Ortogonalize a set of vectors.

Given a set of vectors orthogonalize them using the GramSchmidt procedure. The vectors are then simplified (common factors are removed to keep their norm small).

Parameters:vectors – a collection of vectors to orthogonalize
Return type:orthogonalized vectors

Internals

backend_cuda

Sailfish CUDA backend.

subdomain_runner

Code for controlling a single subdomain of a LB simulation.

class subdomain_runner.KernelGrid

KernelGrid(kernel, grid)

grid

Alias for field number 1

kernel

Alias for field number 0

class subdomain_runner.MacroKernels

MacroKernels(distributions, macro)

distributions

Alias for field number 0

macro

Alias for field number 1

class subdomain_runner.GPUBuffer(host_buffer, backend)

Numpy array and a corresponding GPU buffer.

class subdomain_runner.SubdomainRunner(simulation, spec, output, backend, quit_event, summary_addr=None, master_addr=None, summary_channel=None)

Runs the simulation for a single Subdomain.

The simulation proceeds into two streams, which is used for overlapping calculations with data transfers. The subdomain is divided into two regions – boundary and bulk. The nodes in the bulk region are those that do not send information to any nodes in other subdomains. The boundary region includes all the remaining nodes, including the ghost node envelope used for data storage only.:

calc stream                    data stream
-----------------------------------------------
boundary sim. step    --->     collect data
bulk sim. step                 ...
                               distribute data
                   <- sync ->

An arrow above symbolizes a dependency between the two streams.

Parameters:
  • simulation – instance of a simulation class, descendant from LBSim
  • spec – SubdomainSpec that this runner is to handle
  • backend – instance of a Sailfish backend class to handle GPU interaction
  • quit_event – multiprocessing Event object; if set, the master is requesting early termination of the simulation
  • master_addr – if not None, zmq address of the machine master
  • summary_addr – if not None, zmq address string to which summary information will be sent.
update_context(ctx)

Called by the codegen module.

make_scalar_field(dtype=None, name=None, register=True, async=False, gpu_array=False, need_indirect=True, nonghost_view=True)

Allocates a scalar NumPy array.

The array includes padding adjusted for the compute device (hidden from the end user), as well as space for any ghost nodes. The returned object is a view into the underlying array that hides all ghost nodes. Ghost nodes can still be accessed via the ‘base’ attribute of the returned ndarray.

Parameters:register – if True, the field will be registered for output and for automated creation of equivalent field on the compute device.
Rvalue :tuple of: non-ghost view into the backing array, sparse field (only when indirect addressing is enabled; None otherwise)
make_vector_field(name=None, output=False, async=False, gpu_array=False)

Allocates several scalar arrays representing a vector field.

visualization_map()

Returns an unencoded geometry map used for visualization.

num_phys_nodes

Returns the total number of actual nodes (including padding) in the lattice.

num_nodes

Returns the total number of lattice nodes (including ghosts, excluding padding.

gpu_field(field)

Returns the GPU copy of a field.

gpu_dist(num, copy)

Returns a GPU dist array.

update_force_objects()

The kernels called in this function read data after propagation.

class subdomain_runner.NNSubdomainRunner(*args, **kwargs)

Runs a fluid simulation for a single subdomain.

This is a specialization of the SubdomainRunner class for models which require access to macroscopic fields from the nearest neighbor nodes. It changes the steps executed on the GPU as follows:

calc stream                    data stream
-------------------------------------------------------
boundary macro fields    --->  collect macro data
bulk macro fields              ...
boundary sim. step       <---  distribute macro data
                         --->  collect distrib. data
bulk sim. step                 ...
                               distribute distrib. data
                   <- sync ->

TODO(michalj): Try the alternative scheme:

calc stream                    data stream
-------------------------------------------------------
boundary macro fields    --->  collect macro data
bulk macro fields              ...
bulk sim. step
boundary sim. step       <---  distribute macro data
                         --->  collect distrib. data
                               ...
                               distribute distrib. data
                   <- sync ->

An arrow above symbolizes a dependency between the two streams.

step(sync_req)

Runs one simulation step.

codegen

Run-time CUDA/OpenCL code generation.

class codegen.BlockCodeGenerator(simulation)

Generates CUDA/OpenCL code for a simulation of a subdomain.

config

Classes for specifying and processing simulation configuration.

class config.LBConfig(**kwargs)

Specifies the configuration of a LB simulation.

This class carries all settings, specified programmatically from a script or manually via command line parameters.

class config.MachineSpec(host, addr, gpus=[0], iface='eth0', **kwargs)

Declares information about a machine.

Parameters:
  • host – host name (can be a full execnet gateway spec)
  • addr – host address (IP or domain name); this will be used to establish block-block connections
  • gpus – list of GPU IDs on which to run
  • iface – network interface on which to listen for remote connections

Additional keyword parameters will be stored in the machine’s LBConfig instance when a simulation is run.

connector

Connector classes for exchanging data between block runners.

class connector.MPSubdomainConnector(send_array, recv_array, send_ev, recv_ev, conf_ev, remote_conf_ev)

Handles directed data exchange between two subdomains using the multiprocessing module.

init_runner(ctx)

Called from the block runner of the sender block.

class connector.ZMQSubdomainConnector(addr, receiver=False)

Handles directed data exchange between two subdomains using 0MQ.

Parameters:
  • addr – ZMQ address string
  • receiver – used to distinguish between bind/connect
init_runner(ctx)

Called from the block runner of the sender block.

class connector.ZMQRemoteSubdomainConnector(addr, receiver=False)

Handles directed data exchange between two subdomains on two different hosts.

Parameters:
  • addr – if receiver == False, addr is tcp://<interface> or tcp://*, otherwise it is tcp://<remote_node_ip_or_name>
  • receiver – if True, use connect on the socket, otherwise bind it to a random port.
class connector.CompressedZMQRemoteSubdomainConnector(addr, receiver=False)

Like ZMQRemoteSubdomainConnector, but transfers compressed data.

Parameters:
  • addr – if receiver == False, addr is tcp://<interface> or tcp://*, otherwise it is tcp://<remote_node_ip_or_name>
  • receiver – if True, use connect on the socket, otherwise bind it to a random port.

controller

Simulation controller.

controller.split_subdomains_between_nodes(nodes, subdomains)

Assigns subdomains to cluster nodes.

Returns a list of ‘nodes’ lists of subdomains.

class controller.LBGeometryProcessor(subdomains, dim, gsize)

Transforms a set of SubdomainSpecs into a another set covering the same physical domain, but optimized for execution on the available hardware. Initializes logical connections between the subdomains based on their location.

Parameters:
  • subdomains – list of SubdomainSpec objects
  • gsize – tuple specifying the bounding box of the simulation domain
class controller.LBSimulationController(lb_class, lb_geo=None, default_config=None)

Controls the execution of a LB simulation.

Parameters:
  • lb_class – class describing the simulation, derived from LBSim
  • lb_geo – class describing the global geometry in terms of SubdomainSpec, derived from LBGeometry
  • default_config – dictionary mapping command line option names to their new default values
dim

Dimensionality of the simulation: 2 or 3.

run(ignore_cmdline=False)

Runs a simulation.

geo_encoder

Geometry encoding logic.

geo_encoder.bit_len(num)

Returns the minimal number of bits necesary to encode num.

class geo_encoder.GeoEncoder(subdomain)

Takes information about geometry as specified by the simulation and encodes it into buffers suitable for processing on a GPU.

This is an abstract class. Its implementations provide a specific encoding scheme.

class geo_encoder.GeoEncoderConst(subdomain)

Encodes node type and parameters into a single uint32.

Optional parameters such as velocities, densities, etc. are stored in const memory and the packed value in the uint32 only contains an index inside a const memory array.

prepare_encode(type_map, param_map, param_dict, orientation, have_link_tags)
Parameters:
  • type_map – uint32 array of NodeType.ids
  • param_map – array whose entries are keys in param_dict
  • param_dict – maps entries from param_map to LBNodeType objects
encode(orientation)
Parameters:orientation – numpy array with the same layout as _type_map,

indicating the orientation of different nodes; this array will be modified if detect_orientation is True.

get_param(location, values=1)

Returns ‘values’ float values which are pameters of the node at ‘location’.

Parameters:
  • location – location of the node: x, y, [z] in the subdomain coordinate system (including ghost nodes)
  • values – number of floating-point values to retrieve

master

Machine master.

Coordinates simulation of multiple subdomains on a single host.

class master.LBMachineMaster(config, subdomains, lb_class, subdomain_addr_map=None, channel=None, iface=None)

Controls execution of a LB simulation on a single physical machine (possibly with multiple GPUs and multiple LB subdomains being simulated).

Parameters:
  • config – LBConfig object
  • subdomains – list of SubdomainSpec objects assigned to this machine
  • lb_class – simulation class descendant from LBSim
  • subdomain_addr_map – dict mapping subdomain IDs to IP/DNS addresses
  • channel – execnet Channel object for communication with the controller
  • iface – network interface on which to listen for connections from other subdomains

util

Miscellaneous utility functions.

class util.TimingInfo

TimingInfo(comp, bulk, bnd, coll, net_wait, recv, send, total, total_sq, subdomain_id)

bnd

Alias for field number 2

bulk

Alias for field number 1

coll

Alias for field number 3

comp

Alias for field number 0

net_wait

Alias for field number 4

recv

Alias for field number 5

send

Alias for field number 6

subdomain_id

Alias for field number 9

total

Alias for field number 7

total_sq

Alias for field number 8

util.lsf_vars_to_clusterspec(vars, iface='')

Builds a Saiflish cluster definition based on LSF environment variables.

util.gpufile_to_clusterspec(gpufile, iface='')

Builds a Sailfish cluster definition based on a PBS GPUFILE.

util.in_anyd(arr1, arr2)

Wrapper around np.in1d which returns an array with the same shape as arr1

util.in_anyd_fast(arr1, values)

Faster version of in_anyd.

Parameters:
  • arr1 – array to check
  • values – an iterable of values to look for in arr1
util.logpoints(i, min_=1.0, max_=0.1, n=10)

Returns i-th number from a set spaced evenly on a log scale, similar to np.logspace, the difference is that it gets one number, and it take values (not exponents) as min_, max_.

Parameters:
  • i – get i-th number
  • max (min,) – range
  • n – number of samples
util.linpoints(i, min_=1.0, max_=0.1, n=10)

Returns i-th number from a set spaced evenly on a log scale, similar to np.logspace, the difference is that it gets one number, and it take values (not exponents) as min_, max_.

Parameters:
  • i – get i-th number
  • max (min,) – range
  • n – number of samples
util.kinetic_energy(velocity)

Computes the mean kinetic energy of the fluid.

util.vorticity(velocity, dx=1.0)

Computes the vorticity array from a 3D velocity vector array.

util.enstrophy(velocity, dx)

Computes the enstrophy (mean square vorticity).

util.skewness_factor(ux, n)

Computes the longitudinal skewness factor.

Parameters:
  • ux – x component of velocity
  • n – order of the skewness factor
util.energy_spectrum(velocity, buckets=None, density=False)

Calculates the energy spectrum E(k).

Parameters:
  • velocity – velocity field
  • buckets – if not None, an iterable of wavenumber buckets; if n values are provided here, the energy spectrum will contain n-1 values
  • density – if True, an energy density spectrum in k-space will be calculated; if False the energy will simply be integrated
Rvalue :

numpy array with the energy spectrum

Visualization

vis

Base Sailfish visualization classes.

vis_2d

pygame visualization backend.