Mechanica Library Python API Reference

This is the API Reference page for the module: mechanica

mechanica.init(*args, **kwargs)

Initialize a simulation in Python

Parameters
  • args (PyObject) – positional arguments; first argument is name of simulation (if any)

  • kwargs (PyObject) –

    keyword arguments; currently supported are

    dim: (3-component list of floats) the dimensions of the spatial domain; default is [10., 10., 10.]

    cutoff: (float) simulation cutoff distance; default is 1.

    cells: (3-component list of ints) the discretization of the spatial domain; default is [4, 4, 4]

    threads: (int) number of threads; default is hardware maximum

    integrator: (int) simulation integrator; default is FORWARD_EULER

    dt: (float) time discretization; default is 0.01

    bc: (int or dict) boundary conditions; default is everywhere periodic

    window_size: (2-component list of ints) size of application window; default is [800, 600]

    seed: (int) seed for pseudo-random number generator

    load_file: (str) path to saved simulation state to initialize

    logger_level: (int) logger level; default is no logging

    clip_planes: (list of tuple of (MxVector3f, MxVector3f)) list of point-normal pairs of clip planes; default is no planes

mechanica.run(*args, **kwargs)

Runs the event loop until all windows close or simulation time expires. Automatically performs universe time propogation.

Parameters

args (float) – final time (default runs infinitly)

mechanica.irun()

Alias of mechanica.mechanica.MxSimulatorPy.irun

mechanica.close()

Alias of mechanica.mechanica.MxSimulatorPy.close

mechanica.show()

Alias of mechanica.mechanica.MxSimulatorPy.show

mechanica.step(until: double const & = 0, dt: double const & = 0) HRESULT

Alias of mechanica.mechanica.MxUniverse.step

mechanica.stop() HRESULT

Alias of mechanica.mechanica.MxUniverse.stop

mechanica.start() HRESULT

Alias of mechanica.mechanica.MxUniverse.start

class mechanica.version
build_date

Package build date

compiler

Package compiler ID

compiler_version

Package compiler version

dev

Mechanica development stage

major

Mechanica major version

minor

Mechanica minor version

patch

Mechanica patch version

system_name

System name

system_version

System version

version

Mechanica version

mechanica.has_cuda
Type

boolean

Flag signifying whether CUDA support is installed.

Simulator

mechanica.Simulator

alias of MxSimulatorPy

class mechanica.MxSimulator

The Simulator is the entry point to simulation, this is the very first object that needs to be initialized before any other method can be called. All the methods of the Simulator are static, but the constructor needs to be called first to initialize everything.

The Simulator manages all of the operating system interface, it manages window creation, end user input events, GPU access, threading, inter-process messaging and so forth. All ‘physical’ modeling concepts go in the Universe.

static get() MxSimulator *

gets the global simulator object, returns NULL if fail.

static run(et: double) HRESULT

Runs the event loop until all windows close or simulation time expires. Automatically performs universe time propogation.

Parameters

et (float) – final time; a negative number runs infinitely

Return type

int

Returns

HRESULT

static show() HRESULT

Shows any windows that were specified in the config. Works just like MatPlotLib’s show method. The show method does not start the universe time propagation unlike run and irun.

Return type

int

Returns

HRESULT

static close() HRESULT

Closes the main window, while the application / simulation continues to run.

Return type

int

Returns

HRESULT

static getCUDAConfig()

Gets the Simulator CUDA runtime control interface.

Only available in CUDA-supported installations.

Return type

MxSimulatorCUDAConfig

class mechanica.MxSimulatorPy

Bases: MxSimulator

static irun() HRESULT

Interactive python version of the run loop. This checks the ipython context and lets ipython process keyboard input, while we also running the simulator and processing window messages.

Return type

int

Returns

HRESULT

Universe

mechanica.Universe

Global universe instance.

class mechanica.MxUniverse

The universe is a top level singleton object, and is automatically initialized when the simulator loads. The universe is a representation of the physical universe that we are simulating, and is the repository for all physical object representations.

All properties and methods on the universe are static, and you never actually instantiate a universe.

Universe has a variety of properties such as boundary conditions, and stores all the physical objects such as particles, bonds, potentials, etc.

property temperature

Universe temperature

property time

Current time

property dt

Time step

property boundary_conditions

Boundary conditions

property kinetic_energy

Universe kinetic energy

property center: MxVector3f

Universe center point

property num_types: int

Number of particle types

property cutoff: float

Global interaction cutoff distance

static origin() MxVector3f

Gets the origin of the universe

Return type

MxVector3f

Returns

MxVector3f

static dim() MxVector3f

Gets the dimensions of the universe

Return type

MxVector3f

Returns

MxVector3f

property name
static virial(origin: MxVector3f = None, radius: float * = None, types: std::vector< MxParticleType *, std::allocator< MxParticleType * > > * = None) MxMatrix3f *

Computes the virial tensor for the either the entire simulation domain, or a specific local virial tensor at a location and radius. Optionally can accept a list of particle types to restrict the virial calculation for specify types.

Parameters
  • origin (MxVector3f) – An optional length-3 array for the origin. Defaults to the center of the simulation domain if not given.

  • radius (float) – An optional number specifying the size of the region to compute the virial tensor for. Defaults to the entire simulation domain.

  • types (std::vector< MxParticleType *,std::allocator< MxParticleType * > >) – An optional list of Particle types to include in the calculation. Defaults to every particle type.

Return type

MxMatrix3f

Returns

MxMatrix3f*

static step(until: double const & = 0, dt: double const & = 0) HRESULT

Performs a single time step dt of the universe if no arguments are given. Optionally runs until until, and can use a different timestep of dt.

Parameters
  • until (float) – runs the timestep for this length of time, optional.

  • dt (float) – overrides the existing time step, and uses this value for time stepping; currently not supported.

Return type

int

Returns

HRESULT

static stop() HRESULT

Stops the universe time evolution. This essentially freezes the universe, everything remains the same, except time no longer moves forward.

Return type

int

Returns

HRESULT

static start() HRESULT

Starts the universe time evolution, and advanced the universe forward by timesteps in dt. All methods to build and manipulate universe objects are valid whether the universe time evolution is running or stopped.

Return type

int

Returns

HRESULT

static particles() MxParticleList *

Gets all particles in the universe

Return type

MxParticleList

Returns

MxParticleList*

static grid(shape: MxVector3i) std::vector< std::vector< std::vector< MxParticleList *,std::allocator< MxParticleList * > >,std::allocator< std::vector< MxParticleList *,std::allocator< MxParticleList * > > > >,std::allocator< std::vector< std::vector< MxParticleList *,std::allocator< MxParticleList * > >,std::allocator< std::vector< MxParticleList *,std::allocator< MxParticleList * > > > > > >

Gets a three-dimesional array of particle lists, of all the particles in the system.

Parameters

shape (MxVector3i) – shape of grid

Return type

std::vector< std::vector< std::vector< MxParticleList *,std::allocator< MxParticleList * > >,std::allocator< std::vector< MxParticleList *,std::allocator< MxParticleList * > > > >,std::allocator< std::vector< std::vector< MxParticleList *,std::allocator< MxParticleList * > >,std::allocator< std::vector< MxParticleList *,std::allocator< MxParticleList * > > > > > >

Returns

std::vector<std::vector<std::vector<MxParticleList*> > >

static bonds() std::vector< MxBondHandle *,std::allocator< MxBondHandle * > > *

Get all bonds in the universe

Return type

std::vector< MxBondHandle *,std::allocator< MxBondHandle * > >

Returns

std::vector<MxBondHandle*>*

static angles() std::vector< MxAngleHandle *,std::allocator< MxAngleHandle * > > *

Get all angles in the universe

Return type

std::vector< MxAngleHandle *,std::allocator< MxAngleHandle * > >

Returns

std::vector<MxAngleHandle*>*

static dihedrals() std::vector< MxDihedralHandle *,std::allocator< MxDihedralHandle * > > *

Get all dihedrals in the universe

Return type

std::vector< MxDihedralHandle *,std::allocator< MxDihedralHandle * > >

Returns

std::vector<MxDihedral*>*

Boundary Conditions

mechanica.BoundaryCondition

alias of MxBoundaryCondition

class mechanica.MxBoundaryCondition

A condition on a boundary of the universe.

property kind_str: str

The name of the kind of boundary condition.

restore

restoring percent.

When objects hit this boundary, they get reflected back at restore percent, so if restore is 0.5, and object hitting the boundary at 3 length / time recoils with a velocity of 1.5 lengths / time.

velocity

the velocity on the boundary

name

name of the boundary

normal

vector normal to the boundary

mechanica.BoundaryConditions

alias of MxBoundaryConditions

class mechanica.MxBoundaryConditions(*args)

The BoundaryConditions class serves as a container for the six instances of the MxBoundaryCondition object

left

The left boundary

right

The right boundary

front

The front boundary

back

The back boundary

bottom

The bottom boundary

top

The top boundary

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxBoundaryConditions *

Create from a JSON string representation.

Parameters

str (string) –

Return type

MxBoundaryConditions

Returns

MxBoundaryConditions*

__reduce__()

Helper for pickle.

Constants

Geometry Constants

class mechanica.PointsType
Cube

Unit hollow cube

Disk

Unit disk

Ring

Unit ring

SolidCube

Unit solid cube

SolidSphere

Unit sphere shell

Sphere

Unit sphere

Boundary Condition Constants

mechanica.BOUNDARY_NONE

no boundary conditions

mechanica.PERIODIC_X

periodic in the x (first) direction

mechanica.PERIODIC_Y

periodic in the y (second) direction

mechanica.PERIODIC_Z

periodic in the z (third) direction

mechanica.PERIODIC_FULL

periodic in the all directions

mechanica.FREESLIP_X

free slip in the x (first) direction

mechanica.FREESLIP_Y

free slip in the y (second) direction

mechanica.FREESLIP_Z

free slip in the z (third) direction

mechanica.FREESLIP_FULL

free slip in the all directions

Integrator Constants

mechanica.FORWARD_EULER

Integrator constant: Forward Euler.

Recomended, most tested, standard single-step.

mechanica.RUNGE_KUTTA_4

Integrator constant: Runge-Kutta.

Experimental Runge-Kutta-4.

Particle Dynamics Constants

mechanica.Newtonian

Newtonian dynamics.

mechanica.Overdamped

Overdamped dynamics.

Potential Constants

mechanica.MxPotential.Kind.potential

Potential kind

mechanica.MxPotential.Kind.dpd

Dissipative particle dynamics kind

Particles and Clusters

mechanica.Particle

alias of MxParticle

mechanica.ParticleHandle

alias of MxParticleHandle

class mechanica.MxParticle

The particle data structure.

Instance vars for each particle.

Note that the arrays for x, v and f are 4 entries long for proper alignment.

All particles are stored in a series of contiguous blocks of memory that are owned by the space cells. Each space cell has a array of particle structs.

If you’re building a model, you should probably instead be working with a MxParticleHandle.

py_particle() MxParticleHandle *

Get a handle for this particle.

Return type

MxParticleHandle

Returns

struct MxParticleHandle*

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxParticle *

Create from a JSON string representation.

The returned particle is not automatically registered with the engine.

To properly register a particle from a string, pass the string to the particle constructor of the appropriate particle type or cluster.

Parameters

str (string) –

Return type

MxParticle

Returns

MxParticle*

__reduce__()

Helper for pickle.

class mechanica.MxParticleHandle(*args)

A handle to a particle.

The engine allocates particle memory in blocks, and particle values get moved around all the time, so their addresses change.

The partlist is always ordered by id, i.e. partlist[id] always points to the same particle, even though that particle may move from cell to cell.

This is a safe way to work with a particle.

property charge

Particle charge

property mass

Particle mass

property frozen

Particle frozen flag

property frozen_x

Particle frozen flag along x

property frozen_y

Particle frozen flag along y

property frozen_z

Particle frozen flag along z

property style

Particle style

property age

Particle age

property radius

Particle radius

property name

Particle name

property position

Particle position

property velocity

Particle velocity

property force

Net force acting on particle

property force_init

Persistent force acting on particle

property id

Particle id

property type_id

Particle type id

property cluster_id

Cluster particle id, if any; -1 if particle is not in a cluster

property species

Particle species

property bonds

Bonds attached to particle

property angles

Angles attached to particle

property dihedrals

Dihedrals attached to particle

part() MxParticle *

Gets the actual particle of this handle.

Return type

MxParticle

Returns

MxParticle*

type() MxParticleType *

Gets the particle type of this handle.

Return type

MxParticleType

Returns

MxParticleType*

split() MxParticleHandle *

Splits a single particle into two. Returns the new particle.

Return type

MxParticleHandle

Returns

MxParticleHandle*

destroy() HRESULT

Destroys the particle, and removes it from inventory.

Subsequent references to a destroyed particle result in an error.

Return type

int

Returns

HRESULT

sphericalPosition(particle: Optional[MxParticle] = None, origin: Optional[MxVector3f] = None) MxVector3f

Calculates the particle’s coordinates in spherical coordinates.

By default, calculations are made with respect to the center of the universe.

Parameters
  • particle (MxParticle) – a particle to use as the origin, optional

  • origin (MxVector3f) – a point to use as the origin, optional

Return type

MxVector3f

Returns

MxVector3f

virial(radius: float * = None) MxMatrix3f

Computes the virial tensor. Optionally pass a distance to include a neighborhood.

Parameters

radius (float) – A distance to define a neighborhood, optional

Return type

MxMatrix3f

Returns

MxMatrix3f

become(type: MxParticleType) HRESULT

Dynamically changes the type of an object. We can change the type of a MxParticleType-derived object to anyther pre-existing MxParticleType-derived type. What this means is that if we have an object of say type A, we can change it to another type, say B, and and all of the forces and processes that acted on objects of type A stip and the forces and processes defined for type B now take over.

Parameters

type (MxParticleType) – new particle type

Return type

int

Returns

HRESULT

neighbors(distance: float const * = None, types: vectorParticleType = None) MxParticleList *

Gets a list of nearby particles.

Parameters
  • distance (float) – optional search distance; default is simulation cutoff

  • types (std::vector< MxParticleType,std::allocator< MxParticleType > >) – optional list of particle types to search by; default is all types

Return type

MxParticleList

Returns

MxParticleList*

getBondedNeighbors() MxParticleList *

Gets a list of all bonded neighbors.

Return type

MxParticleList

Returns

MxParticleList*

distance(_other: MxParticleHandle) float

Calculates the distance to another particle

Parameters

_other (MxParticleHandle) – another particle.

Return type

float

Returns

float

to_cluster() MxClusterParticleHandle *

Limits casting to cluster by type

class mechanica.ParticleType

Interface for class-centric design of MxParticleType

mass = None

Particle type mass

charge = None

Particle type charge

radius = None

Particle type radius

target_energy = None

Particle type target energy

minimum_radius = None

Particle type minimum radius

eps = None

Particle type nonbonded interaction parameter

rmin = None

Particle type nonbonded interaction parameter

dynamics = None

Particle type dynamics flag

frozen = None

Particle type frozen flag

name = None

Particle type name

name2 = None

Particle type second name

style = None

Particle type style dictionary specification.

Basic rendering details can be specified as a dictionary, like color and visibility,

style = {'color': 'CornflowerBlue', 'visible': False}

This declaration is the same as performing operations on a type after registration,

ptype: MxParticleType
ptype.style.setColor('CornflowerBlue')
ptype.style.setVisible(False)

Rendering instead by species and species amount uses specification for a color mapper,

style = {'colormap': {'species': 'S1', 'map': 'rainbow', 'range': (0, 10)}}

This declaration is the same as performing operations on a type after registration,

ptype: MxParticleType
ptype.style.newColorMapper(partType=ptype, speciesName='S1', name='rainbow', min=0, max=10)
species = None

Particle type list of species by name, if any. Species are automatically created and populated in the state vector of the type and all created particles.

classmethod get()

Get the engine type that corresponds to this class.

The type is automatically registered as necessary.

Returns

registered type instance

Return type

mechanica.MxParticleType

class mechanica.MxParticleType(noReg: bool const & = False)

Structure containing information on each particle type.

This is only a definition for a type of particle, and not an actual particle with position, velocity, etc. However, particles of this type can be created with one of these.

property frozen

Particle type frozen flag

property frozen_x

Particle type frozen flag along x

property frozen_y

Particle type frozen flag along y

property frozen_z

Particle type frozen flag along z

property temperature

Particle type temperature

property target_temperature

Particle type target temperature

id

ID of this type

mass

Default mass of particles

charge

Default charge of particles

radius

Default radius of particles

kinetic_energy

Kinetic energy of all particles of this type.

potential_energy

Potential energy of all particles of this type.

target_energy

Target energy of all particles of this type.

minimum_radius

Default minimum radius of this type.

If a split event occurs, resulting particles will have a radius at least as great as this value.

dynamics

Default dynamics of particles of this type.

name

Name of this particle type.

style

style pointer, optional.

species

optional pointer to species list. This is the metadata for the species

parts

list of particles that belong to this type.

particle(i: int) MxParticle *

get the i’th particle that’s a member of this type.

Parameters

i (int) – index of particle to get

Return type

MxParticle

Returns

MxParticle*

static particleTypeIds() std::set< short,std::less< short >,std::allocator< short > >

Get all current particle type ids, excluding clusters

Return type

std::set< short,std::less< short >,std::allocator< short > >

Returns

std::set<int>

__call__(*args, **kwargs)

Call self as a function.

Alias of _call

_call(*args) MxParticleHandle *

Overload 1:

Particle constructor.

Automatically updates when running on a CUDA device.

Parameters
  • position (MxVector3f) – position of new particle, optional

  • velocity (MxVector3f) – velocity of new particle, optional

  • clusterId (int) – id of parent cluster, optional

Return type

MxParticleHandle

Returns

MxParticleHandle*


Overload 2:

Particle constructor.

Automatically updates when running on a CUDA device.

Parameters
  • str (string) – JSON string

  • clusterId (int) – id of parent cluster, optional

Return type

MxParticleHandle

Returns

MxParticleHandle*

factory(nr_parts=0, positions=None, velocities=None, cluster_ids=None)
newType(_name: char const *) MxParticleType *

Particle type constructor.

New type is constructed from the definition of the calling type.

Parameters

_name (string) – name of the new type

Return type

MxParticleType

Returns

MxParticleType*

registerType() HRESULT

Registers a type with the engine.

Note that this occurs automatically, unless noReg==true in constructor.

Return type

int

Returns

HRESULT

on_register() void

A callback for when a type is registered

isRegistered() bool

Tests whether this type is registered

Return type

boolean

Returns

true if registered

get() MxParticleType *

Get the type engine instance

Return type

MxParticleType

Returns

MxParticleType*

items() MxParticleList *

Get all particles of this type.

Return type

MxParticleList

Returns

MxParticleList*

isCluster() bool
to_cluster() MxClusterParticleType *

Limits casting to cluster by type

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxParticleType *

Create from a JSON string representation.

The returned type is automatically registered with the engine.

Parameters

str (string) –

Return type

MxParticleType

Returns

MxParticleType*

__reduce__()

Helper for pickle.

mechanica.Cluster

alias of MxCluster

mechanica.ClusterHandle

alias of MxClusterParticleHandle

class mechanica.MxCluster

Bases: MxParticle

The cluster analogue to MxParticle.

class mechanica.MxClusterParticleHandle(*args)

Bases: MxParticleHandle

The cluster analogue to MxParticleHandle.

These are special in that they can create particles of their constituent particle types, much like a MxParticleType.

property radius_of_gyration

Radius of gyration

property center_of_mass

Center of mass

property centroid

Centroid

property moment_of_inertia

Moment of inertia

items = <function MxClusterParticleHandle.items>
__call__(particle_type, *args, **kwargs)

Call self as a function.

Alias of _call

_call(*args) MxParticleHandle *

Overload 1:

Constituent particle constructor.

The created particle will belong to this cluster.

Automatically updates when running on a CUDA device.

Parameters
  • partType (MxParticleType) – type of particle to create

  • position (MxVector3f) – position of new particle, optional

  • velocity (MxVector3f) – velocity of new particle, optional

Return type

MxParticleHandle

Returns

MxParticleHandle*


Overload 2:

Constituent particle constructor.

The created particle will belong to this cluster.

Automatically updates when running on a CUDA device.

Parameters
  • partType (MxParticleType) – type of particle to create

  • str (string) – JSON string

Return type

MxParticleHandle

Returns

MxParticleHandle*

cluster() MxCluster *

Gets the actual cluster of this handle.

Return type

MxCluster

Returns

MxParticle*

split(axis: MxVector3f = None, random: bool * = None, time: float * = None, normal: MxVector3f = None, point: MxVector3f = None) MxParticleHandle *

Split the cluster.

Parameters
  • axis (MxVector3f) – axis of split, optional

  • random (boolean) – divide by randomly and evenly allocating constituent particles, optional

  • time (float) – time at which to implement the split; currently not supported

  • normal (MxVector3f) – normal vector of cleavage plane, optional

  • point (MxVector3f) – point on cleavage plane, optional

Return type

MxParticleHandle

Returns

MxParticleHandle*

class mechanica.ClusterType

Bases: ParticleType

Interface for class-centric design of MxClusterParticleType

types = None

List of constituent types of the cluster, if any

class mechanica.MxClusterParticleType(noReg: bool const & = False)

Bases: MxParticleType

The cluster analogue to MxParticleType.

types

list of particle types that belong to this type.

hasType(type: MxParticleType) bool

Tests where this cluster has a particle type

Parameters

type (MxParticleType) – type to test

Return type

boolean

Returns

true if this cluster has the type

get() MxClusterParticleType *

Get the type engine instance

Return type

MxClusterParticleType

Returns

MxClusterParticleType*

ParticleList and ParticleTypeList

mechanica.ParticleList

alias of MxParticleList

class mechanica.MxParticleList(*args)

A special list with convenience methods for working with sets of particles.

property virial

Virial tensor of particles in list

property radius_of_gyration

Radius of gyration of particles in list

property center_of_mass

Center of mass of particles in list

property centroid

Centroid of particles in list

property moment_of_inertia

Moment of inertia of particles in list

property positions

Position of each particle in list

property velocities

Velocity of each particle in list

property forces

Net forces acting on each particle in list

__len__() int
__getitem__(i: int)
reserve(_nr_parts: size_t) HRESULT

Reserve enough storage for a given number of items.

Parameters

_nr_parts (int) – number of items

Return type

int

Returns

HRESULT

insert(*args) uint16_t

Inserts the given particle into the list, returns the index of the item.

Parameters

particle (MxParticleHandle) – particle to insert

Return type

int

Returns

uint16_t

remove(id: int32_t) uint16_t

looks for the item with the given id and deletes it form the list

Parameters

id (int) – id to remove

Return type

int

Returns

uint16_t

extend(other: MxParticleList) void

inserts the contents of another list

Parameters

other (MxParticleList) – another list

item(i: int32_t const &) MxParticleHandle *

looks for the item at the given index and returns it if found, otherwise returns NULL

Parameters

i (int) – index of lookup

Return type

MxParticleHandle

Returns

MxParticleHandle*

static all() MxParticleList *

returns an instance populated with all current particles

Return type

MxParticleList

Returns

MxParticleList*

sphericalPositions(origin: MxVector3f = None) std::vector< MxVector3f,std::allocator< MxVector3f > >

Get the spherical coordinates of each particle

Parameters

origin (MxVector3f) – optional origin of coordinates; default is center of universe

Return type

std::vector< MxVector3f,std::allocator< MxVector3f > >

Returns

std::vector<MxVector3f>

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxParticleList *

Create from a JSON string representation

Parameters

str (string) –

Return type

MxParticleList

Returns

MxParticleList*

__reduce__()

Helper for pickle.

mechanica.ParticleTypeList

alias of MxParticleTypeList

class mechanica.MxParticleTypeList(*args)

A special list with convenience methods for working with sets of particle types.

property virial

Virial tensor of particles corresponding to all types in list

property radius_of_gyration

Radius of gyration of particles corresponding to all types in list

property center_of_mass

Center of mass of particles corresponding to all types in list

property centroid

Centroid of particles corresponding to all types in list

property moment_of_inertia

Moment of inertia of particles corresponding to all types in list

property positions

Position of each particle corresponding to all types in list

property velocities

Velocity of each particle corresponding to all types in list

property forces

Total net force acting on each particle corresponding to all types in list

__len__() int
__getitem__(i: int)
reserve(_nr_parts: size_t) HRESULT

Reserve enough storage for a given number of items.

Parameters

_nr_parts (int) – number of items

Return type

int

Returns

HRESULT

insert(*args) uint16_t

Inserts the given particle type into the list, returns the index of the item.

Parameters

ptype (MxParticleType) –

Return type

int

Returns

uint16_t

remove(id: int32_t) uint16_t

looks for the item with the given id and deletes it form the list

Parameters

id (int) – id to remove

Return type

int

Returns

uint16_t

extend(other: MxParticleTypeList) void

inserts the contents of another list

Parameters

other (MxParticleTypeList) – another list

item(i: int32_t const &) MxParticleType *

looks for the item at the given index and returns it if found, otherwise returns NULL

Parameters

i (int) – index of lookup

Return type

MxParticleType

Returns

MxParticleType*

static all() MxParticleTypeList *

returns an instance populated with all current particle types

Return type

MxParticleTypeList

Returns

MxParticleTypeList*

sphericalPositions(origin: MxVector3f = None) std::vector< MxVector3f,std::allocator< MxVector3f > >

Get the spherical coordinates of each particle

Parameters

origin (MxVector3f) – optional origin of coordinates; default is center of universe

Return type

std::vector< MxVector3f,std::allocator< MxVector3f > >

Returns

std::vector<MxVector3f>

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxParticleTypeList *

Create from a JSON string representation

Parameters

str (string) –

Return type

MxParticleTypeList

Returns

MxParticleTypeList*

__reduce__()

Helper for pickle.

Potentials

mechanica.Potential

alias of MxPotentialPy

class mechanica.MxPotential

A Potential object is a compiled interpolation of a given function. The Universe applies potentials to particles to calculate the net force on them.

For performance reasons, Mechanica implements potentials as interpolations, which can be much faster than evaluating the function directly.

A potential can be treated just like any callable object.

property min: float

Minimum distance of evaluation

property max: float

Maximum distance of evaluation

property cutoff: float

Cutoff distance

property domain: (<class 'float'>, <class 'float'>)

Evaluation domain

property intervals: int

Evaluation intervals

property bound: bool

Bound flag

property r0: float

Potential r0 value

property shifted: bool

Shifted flag

property periodic: bool

Periodic flag

property r_square: bool

Potential r2 value

__call__()

Alias of _call

_call(*args) float
plot(s=None, force=True, potential=False, show=True, ymin=None, ymax=None, *args, **kwargs)

Potential plot function

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxPotential *

Create from a JSON string representation

Parameters

str (string) –

Return type

MxPotential

Returns

MxPotential*

__reduce__()

Helper for pickle.

static lennard_jones_12_6(min: double, max: double, A: double, B: double, tol: double * = None) MxPotential *

Creates a 12-6 Lennard-Jones potential.

The Lennard Jones potential has the form:

\[\left( \frac{A}{r^{12}} - \frac{B}{r^6} \right)\]
Parameters
  • min (float) – The smallest radius for which the potential will be constructed.

  • max (float) – The largest radius for which the potential will be constructed.

  • A (float) – The first parameter of the Lennard-Jones potential.

  • B (float) – The second parameter of the Lennard-Jones potential.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001 * (max - min).

Return type

MxPotential

Returns

MxPotential*

static lennard_jones_12_6_coulomb(min: double, max: double, A: double, B: double, q: double, tol: double * = None) MxPotential *

Creates a potential of the sum of a 12-6 Lennard-Jones potential and a shifted Coulomb potential.

The 12-6 Lennard Jones - Coulomb potential has the form:

\[\left( \frac{A}{r^{12}} - \frac{B}{r^6} \right) + q \left( \frac{1}{r} - \frac{1}{max} \right)\]
Parameters
  • min (float) – The smallest radius for which the potential will be constructed.

  • max (float) – The largest radius for which the potential will be constructed.

  • A (float) – The first parameter of the Lennard-Jones potential.

  • B (float) – The second parameter of the Lennard-Jones potential.

  • q (float) – The charge scaling of the potential.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001 * (max - min).

Return type

MxPotential

Returns

MxPotential*

static ewald(min: double, max: double, q: double, kappa: double, tol: double * = None, periodicOrder: unsigned int * = None) MxPotential *

Creates a real-space Ewald potential.

The Ewald potential has the form:

\[q \frac{\mathrm{erfc}\, ( \kappa r)}{r}\]
Parameters
  • min (float) – The smallest radius for which the potential will be constructed.

  • max (float) – The largest radius for which the potential will be constructed.

  • q (float) – The charge scaling of the potential.

  • kappa (float) – The screening distance of the Ewald potential.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001 * (max - min).

  • periodicOrder (int) – Order of lattice periodicity along all periodic dimensions. Defaults to 0.

Return type

MxPotential

Returns

MxPotential*

static coulomb(q: double, min: double * = None, max: double * = None, tol: double * = None, periodicOrder: unsigned int * = None) MxPotential *

Creates a Coulomb potential.

The Coulomb potential has the form:

\[\frac{q}{r}\]
Parameters
  • q (float) – The charge scaling of the potential.

  • min (float) – The smallest radius for which the potential will be constructed. Default is 0.01.

  • max (float) – The largest radius for which the potential will be constructed. Default is 2.0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001 * (max - min).

  • periodicOrder (int) – Order of lattice periodicity along all periodic dimensions. Defaults to 0.

Return type

MxPotential

Returns

MxPotential*

static coulombR(q: double, kappa: double, min: double, max: double, modes: unsigned int * = None) MxPotential *

Creates a Coulomb reciprocal potential.

The Coulomb reciprocal potential has the form:

\[\frac{\pi q}{V} \sum_{||\mathbf{m}|| \neq 0} \frac{1}{||\mathbf{m}||^2} \exp \left( \left( i \mathbf{r}_{jk} - \left( \frac{\pi}{\kappa} \right)^{2} \mathbf{m} \right) \cdot \mathbf{m} \right)\]

Here \(V\) is the volume of the domain and \(\mathbf{m}\) is a reciprocal vector of the domain.

Parameters
  • q (float) – Charge scaling of the potential.

  • kappa (float) – Screening distance.

  • min (float) – Smallest radius for which the potential will be constructed.

  • max (float) – Largest radius for which the potential will be constructed.

  • modes (int) – Number of Fourier modes along each periodic dimension. Default is 1.

Return type

MxPotential

Returns

MxPotential*

static harmonic(k: double, r0: double, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a harmonic bond potential.

The harmonic potential has the form:

\[k \left( r-r_0 \right)^2\]
Parameters
  • k (float) – The energy of the bond.

  • r0 (float) – The bond rest length.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to \(r_0 - r_0 / 2\).

  • max (float) – The largest radius for which the potential will be constructed. Defaults to \(r_0 + r_0 /2\).

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to \(0.01 \abs(max-min)\).

Return type

MxPotential

Returns

MxPotential*

static linear(k: double, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a linear potential.

The linear potential has the form:

\[k r\]
Parameters
  • k (float) – interaction strength; represents the potential energy peak value.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to 0.0.

  • max (float) – The largest radius for which the potential will be constructed. Defaults to 10.0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001.

Return type

MxPotential

Returns

MxPotential*

static harmonic_angle(k: double, theta0: double, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a harmonic angle potential.

The harmonic angle potential has the form:

\[k \left(\theta-\theta_{0} \right)^2\]
Parameters
  • k (float) – The energy of the angle.

  • theta0 (float) – The minimum energy angle.

  • min (float) – The smallest angle for which the potential will be constructed. Defaults to zero.

  • max (float) – The largest angle for which the potential will be constructed. Defaults to PI.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.005 * (max - min).

Return type

MxPotential

Returns

MxPotential*

static harmonic_dihedral(k: double, delta: double, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a harmonic dihedral potential.

The harmonic dihedral potential has the form:

\[k \left( \theta - \delta \right) ^2\]
Parameters
  • k (float) – energy of the dihedral.

  • delta (float) – minimum energy dihedral.

  • min (float) – The smallest angle for which the potential will be constructed. Defaults to zero.

  • max (float) – The largest angle for which the potential will be constructed. Defaults to PI.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.005 * (max - min).

Return type

MxPotential

Returns

MxPotential*

static cosine_dihedral(k: double, n: int, delta: double, tol: double * = None) MxPotential *

Creates a cosine dihedral potential.

The cosine dihedral potential has the form:

\[k \left( 1 + \cos( n \theta-\delta ) \right)\]
Parameters
  • k (float) – energy of the dihedral.

  • n (int) – multiplicity of the dihedral.

  • delta (float) – minimum energy dihedral.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.01.

Return type

MxPotential

Returns

MxPotential*

static well(k: double, n: double, r0: double, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a well potential.

Useful for binding a particle to a region.

The well potential has the form:

\[\frac{k}{\left(r_0 - r\right)^{n}}\]
Parameters
  • k (float) – potential prefactor constant, should be decreased for larger n.

  • n (float) – exponent of the potential, larger n makes a sharper potential.

  • r0 (float) – The extents of the potential, length units. Represents the maximum extents that a two objects connected with this potential should come apart.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to zero.

  • max (float) – The largest radius for which the potential will be constructed. Defaults to r0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.01 * abs(min-max).

Return type

MxPotential

Returns

MxPotential*

static glj(e: double, m: double * = None, n: double * = None, k: double * = None, r0: double * = None, min: double * = None, max: double * = None, tol: double * = None, shifted: bool * = None) MxPotential *

Creates a generalized Lennard-Jones potential.

The generalized Lennard-Jones potential has the form:

\[\frac{\epsilon}{n-m} \left[ m \left( \frac{r_0}{r} \right)^n - n \left( \frac{r_0}{r} \right)^m \right]\]
Parameters
  • e (float) – effective energy of the potential.

  • m (float) – order of potential. Defaults to 3

  • n (float) – order of potential. Defaults to 2*m.

  • k (float) – mimumum of the potential. Defaults to 1.

  • r0 (float) – mimumum of the potential. Defaults to 1.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to 0.05 * r0.

  • max (float) – The largest radius for which the potential will be constructed. Defaults to 5 * r0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.01.

  • shifted (boolean) – Flag for whether using a shifted potential. Defaults to true.

Return type

MxPotential

Returns

MxPotential*

static morse(d: double * = None, a: double * = None, r0: double * = None, min: double * = None, max: double * = None, tol: double * = None, shifted: bool * = None) MxPotential *

Creates a Morse potential.

The Morse potential has the form:

\[d \left(1 - e^{ -a \left(r - r_0 \right) } \right)^2\]
Parameters
  • d (float) – well depth. Defaults to 1.0.

  • a (float) – potential width. Defaults to 6.0.

  • r0 (float) – equilibrium distance. Defaults to 0.0.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to 0.0001.

  • max (float) – The largest radius for which the potential will be constructed. Defaults to 3.0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001.

  • shifted (boolean) – Flag for whether using a shifted potential. Defaults to true.

Return type

MxPotential

Returns

MxPotential*

static overlapping_sphere(mu: double * = None, kc: double * = None, kh: double * = None, r0: double * = None, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates an overlapping-sphere potential from [OFPF+17].

The overlapping-sphere potential has the form:

\[\mu_{ij} s_{ij}(t) \hat{\mathbf{r}}_{ij} \log \left( 1 + \frac{||\mathbf{r}_{ij}|| - s_{ij}(t)}{s_{ij}(t)} \right) \text{ if } ||\mathbf{r}_{ij}|| < s_{ij}(t) ,\]
\[\mu_{ij}\left(||\mathbf{r}_{ij}|| - s_{ij}(t)\right) \hat{\mathbf{r}}_{ij} \exp \left( -k_c \frac{||\mathbf{r}_{ij}|| - s_{ij}(t)}{s_{ij}(t)} \right) \text{ if } s_{ij}(t) \leq ||\mathbf{r}_{ij}|| \leq r_{max} ,\]
\[0 \text{ otherwise} .\]

Osborne refers to \(\mu_{ij}\) as a “spring constant”, this controls the size of the force, and is the potential energy peak value. \(\hat{\mathbf{r}}_{ij}\) is the unit vector from particle \(i\) center to particle \(j\) center, \(k_C\) is a parameter that defines decay of the attractive force. Larger values of \(k_C\) result in a shaper peaked attraction, and thus a shorter ranged force. \(s_{ij}(t)\) is the is the sum of the radii of the two particles.

Parameters
  • mu (float) – interaction strength, represents the potential energy peak value. Defaults to 1.0.

  • kc (float) – decay strength of long range attraction. Larger values make a shorter ranged function. Defaults to 1.0.

  • kh (float) – Optionally add a harmonic long-range attraction, same as glj function. Defaults to 0.0.

  • r0 (float) – Optional harmonic rest length, only used if kh is non-zero. Defaults to 0.0.

  • min (float) – The smallest radius for which the potential will be constructed. Defaults to 0.001.

  • max (float) – The largest radius for which the potential will be constructed. Defaults to 10.0.

  • tol (float) – The tolerance to which the interpolation should match the exact potential. Defaults to 0.001.

Return type

MxPotential

Returns

MxPotential*

static power(k: double * = None, r0: double * = None, alpha: double * = None, min: double * = None, max: double * = None, tol: double * = None) MxPotential *

Creates a power potential.

The power potential the general form of many of the potential functions, such as linear, etc. power has the form:

\[k (r-r_0)^{\alpha}\]
Parameters
  • k (float) – interaction strength, represents the potential energy peak value. Defaults to 1

  • r0 (float) – potential rest length, zero of the potential, defaults to 0.

  • alpha (float) – Exponent, defaults to 1.

  • min (float) – minimal value potential is computed for, defaults to r0 / 2.

  • max (float) – cutoff distance, defaults to 3 * r0.

  • tol (float) – Tolerance, defaults to 0.01.

Return type

MxPotential

Returns

MxPotential*

static dpd(alpha: double * = None, gamma: double * = None, sigma: double * = None, cutoff: double * = None, shifted: bool * = None) MxPotential *

Creates a Dissipative Particle Dynamics potential.

The Dissipative Particle Dynamics force has the form:

\[\mathbf{F}_{ij} = \mathbf{F}^C_{ij} + \mathbf{F}^D_{ij} + \mathbf{F}^R_{ij}\]

The conservative force is:

\[\mathbf{F}^C_{ij} = \alpha \left(1 - \frac{r_{ij}}{r_c}\right) \mathbf{e}_{ij}\]

The dissapative force is:

\[\mathbf{F}^D_{ij} = -\gamma \left(1 - \frac{r_{ij}}{r_c}\right)^{2}(\mathbf{e}_{ij} \cdot \mathbf{v}_{ij}) \mathbf{e}_{ij}\]

The random force is:

\[\mathbf{F}^R_{ij} = \sigma \left(1 - \frac{r_{ij}}{r_c}\right) \xi_{ij}\Delta t^{-1/2}\mathbf{e}_{ij}\]
Parameters
  • alpha (float) – interaction strength of the conservative force. Defaults to 1.0.

  • gamma (float) – interaction strength of dissapative force. Defaults to 1.0.

  • sigma (float) – strength of random force. Defaults to 1.0.

  • cutoff (float) – cutoff distance. Defaults to 1.0.

  • shifted (boolean) – Flag for whether using a shifted potential. Defaults to false.

Return type

MxPotential

Returns

MxPotential*

class mechanica.DPDPotential(alpha: float, gamma: float, sigma: float, cutoff: float, shifted: bool)

Bases: MxPotential

alpha

strength of conserative interaction

gamma

strength of dissapative interaction

sigma

strength of random interaction

static fromPot(pot: MxPotential) DPDPotential *

Convert basic potential to DPD.

If the basic potential is not DPD, then NULL is returned.

Parameters

pot (MxPotential) –

Return type

DPDPotential

Returns

DPDPotential*

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) DPDPotential *

Create from a JSON string representation

Parameters

str (string) –

Return type

DPDPotential

Returns

MxPotential*

__reduce__()

Helper for pickle.

class mechanica.MxPotentialPy

Bases: MxPotential

custom = <function MxPotentialPy.custom>

Forces

mechanica.Force

alias of MxForce

class mechanica.MxForce

MxForce is a metatype, in that Mechanica has lots of different instances of force functions, that have different attributes, but only have one base type.

Forces are one of the fundamental processes in Mechanica that cause objects to move.

bind_species(a_type: MxParticleType, coupling_symbol: std::string const &) HRESULT

Bind a force to a species.

When a force is bound to a species, the magnitude of the force is scaled by the concentration of the species.

Parameters
  • a_type (MxParticleType) – particle type containing the species

  • coupling_symbol (string) – symbol of the species

Return type

int

Returns

HRESULT

static berendsen_tstat(tau: float const &) Berendsen *

Creates a Berendsen thermostat.

The thermostat uses the target temperature \(T_0\) from the object to which it is bound. The Berendsen thermostat effectively re-scales the velocities of an object in order to make the temperature of that family of objects match a specified temperature.

The Berendsen thermostat force has the function form:

\[\frac{\mathbf{p}}{\tau_T} \left(\frac{T_0}{T} - 1 \right),\]

where \(\mathbf{p}\) is the momentum, \(T\) is the measured temperature of a family of particles, \(T_0\) is the control temperature, and \(\tau_T\) is the coupling constant. The coupling constant is a measure of the time scale on which the thermostat operates, and has units of time. Smaller values of \(\tau_T\) result in a faster acting thermostat, and larger values result in a slower acting thermostat.

Parameters

tau (float) – time constant that determines how rapidly the thermostat effects the system.

Return type

Berendsen

Returns

Berendsen*

static random(std: float const &, mean: float const &, duration: float const & = 0.01) Gaussian *

Creates a random force.

A random force has a randomly selected orientation and magnitude.

Orientation is selected according to a uniform distribution on the unit sphere.

Magnitude is selected according to a prescribed mean and standard deviation.

Parameters
  • std (float) – standard deviation of magnitude

  • mean (float) – mean of magnitude

  • duration (float) – duration of force. Defaults to 0.01.

Return type

Gaussian

Returns

Gaussian*

static friction(coef: float const &) Friction *

Creates a friction force.

A friction force has the form:

\[- \frac{|| \mathbf{v} ||}{\tau} \mathbf{v} ,\]

where \(\mathbf{v}\) is the velocity of a particle and \(\tau\) is a time constant.

Parameters

coef (float) – time constant

Return type

Friction

Returns

Friction*

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxForce *

Create from a JSON string representation

Parameters

str (string) –

Return type

MxForce

Returns

MxForce*

__reduce__()

Helper for pickle.

mechanica.ConstantForce

alias of MxConstantForcePy

class mechanica.MxConstantForce(*args)

Bases: MxForce

A custom force function.

The force is updated according to an update frequency.

This object acts like a constant force, but also acts like a time event, in that it periodically calls a custom function to update the applied force.

static fromForce(f: MxForce) MxConstantForce *

Convert basic force to MxConstantForce.

If the basic force is not a MxConstantForce, then NULL is returned.

Parameters

f (MxForce) –

Return type

MxConstantForce

Returns

MxConstantForce*

class mechanica.MxConstantForcePy(*args)

Bases: MxConstantForce

Creates an instance from an underlying custom python function

Parameters
  • f (PyObject) – python function. Takes no arguments and returns a three-component vector.

  • period (float) – period at which the force is updated.

static fromForce(f: MxForce) MxConstantForcePy *

Convert basic force to MxConstantForcePy.

If the basic force is not a MxConstantForcePy, then NULL is returned.

Parameters

f (MxForce) –

Return type

MxConstantForcePy

Returns

MxConstantForcePy*

mechanica.ForceSum

alias of MxForceSum

class mechanica.MxForceSum

Bases: MxForce

f1
f2
static fromForce(f: MxForce) MxForceSum *

Convert basic force to force sum.

If the basic force is not a force sum, then NULL is returned.

Parameters

f (MxForce) –

Return type

MxForceSum

Returns

MxForceSum*

class mechanica.Berendsen

Bases: MxForce

Berendsen force.

Create one with MxForce.berendsen_tstat.

itau

time constant

static fromForce(f: MxForce) Berendsen *

Convert basic force to Berendsen.

If the basic force is not a Berendsen, then NULL is returned.

Parameters

f (MxForce) –

Return type

Berendsen

Returns

Berendsen*

class mechanica.Gaussian

Bases: MxForce

Random force.

Create one with MxForce.random.

std

standard deviation of magnitude

mean

mean of magnitude

durration_steps

duration of force.

static fromForce(f: MxForce) Gaussian *

Convert basic force to Gaussian.

If the basic force is not a Gaussian, then NULL is returned.

Parameters

f (MxForce) –

Return type

Gaussian

Returns

Gaussian*

class mechanica.Friction

Bases: MxForce

Friction force.

Create one with MxForce.friction.

coef

time constant

static fromForce(f: MxForce) Friction *

Convert basic force to Friction.

If the basic force is not a Friction, then NULL is returned.

Parameters

f (MxForce) –

Return type

Friction

Returns

Friction*

Reactions and Species

mechanica.Species

alias of MxSpecies

class mechanica.MxSpecies(*args)

The Mechanica species object.

Mostly, this is a wrap of libSBML Species.

__str__() str

Return str(self).

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxSpecies *

Create from a JSON string representation.

Parameters

str (string) –

Return type

MxSpecies

Returns

MxSpecies*

__reduce__()

Helper for pickle.

property id: str
property name: str
property species_type: str
property compartment: str
property initial_amount: float
property initial_concentration: float
property substance_units: str
property spatial_size_units: str
property units: str
property has_only_substance_units: bool
property boundary_condition: bool
property charge: int
property constant: bool
property conversion_factor: str
mechanica.SpeciesValue

alias of MxSpeciesValue

class mechanica.MxSpeciesValue(*args)

A working valued-object of an underlying MxSpecies attached to an object.

property boundary_condition: bool
property initial_amount: float
property initial_concentration: float
property constant: bool
secrete(amount, to=None, distance=None)

Secrete this species into a neighborhood.

Requires either a list of neighboring particles or neighborhood distance.

Parameters
  • amount (float) – Amount to secrete.

  • to (MxParticleList) – Optional list of particles to secrete to.

  • distance (float) – Neighborhood distance.

Returns

Amount actually secreted, accounting for availability and other subtleties.

Return type

float

mechanica.SpeciesList

alias of MxSpeciesList

class mechanica.MxSpeciesList
__str__() str

Return str(self).

__len__() int
__getattr__(item: str)
__setattr__(item: str, value) None

Implement setattr(self, name, value).

__getitem__(item) MxSpecies
__setitem__(item, value) None
item(*args) MxSpecies *

Overload 1:

Get a species by index

Parameters

index (int) – index of the species

Return type

MxSpecies

Returns

MxSpecies*


Overload 2:

Get a species by name

Parameters

s (string) – name of species

Return type

MxSpecies

Returns

MxSpecies*

insert(*args) HRESULT

Overload 1:

Insert a species

Return type

int

Returns

HRESULT


Overload 2:

Insert a species by name

Parameters

s (string) – name of the species

Return type

int

Returns

HRESULT

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxSpeciesList *

Create from a JSON string representation.

Parameters

str (string) –

Return type

MxSpeciesList

Returns

MxSpeciesList*

__reduce__()

Helper for pickle.

mechanica.StateVector

alias of MxStateVector

class mechanica.MxStateVector(*args)

A state vector of an object.

__str__() str

Return str(self).

__len__() int
__getattr__(item: str)
__setattr__(item: str, value: float) None

Implement setattr(self, name, value).

__getitem__(item: int)
__setitem__(item: int, value: float) None
toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxStateVector *

Create from a JSON string representation.

Parameters

str (string) –

Return type

MxStateVector

Returns

MxStateVector*

__reduce__()

Helper for pickle.

species

Species of the state vector

Fluxes

mechanica.Fluxes

alias of MxFluxes

class mechanica.MxFluxes

A flux is defined between a pair of types, and acts on the state vector between a pair of instances.

The indices of the species in each state vector are most likely different, so Mechanica tracks the indices in each type, and the transport constatants.

A flux between a pair of types, and pair of respective species needs:

(1) type A, (2) type B, (3) species id in A, (4) species id in B, (5) transport constant.

Allocates Flux as a single block, member pointers point to offsets in these blocks.

Allocated size is: sizeof(MxFluxes) + 2 * alloc_size * sizeof(int32) + alloc_size * sizeof(float)

static flux(A: MxParticleType, B: MxParticleType, name: std::string const &, k: float const &, decay: float const & = 0.0) MxFluxes *

Alias of fluxFick.

Parameters
  • A (MxParticleType) – first type

  • B (MxParticleType) – second type

  • name (string) – name of species

  • k (float) – transport coefficient

  • decay (float) – optional decay. Defaults to 0.0.

Return type

MxFluxes

Returns

MxFluxes*

static fluxFick(A: MxParticleType, B: MxParticleType, name: std::string const &, k: float const &, decay: float const & = 0.0) MxFluxes *

Creates and binds a Fickian diffusion flux.

Fickian diffusion flux implements the analogous reaction:

\[a.S \leftrightarrow b.S ; k \left(1 - \frac{r}{r_{cutoff}} \right)\left(a.S - b.S\right) ,\]
\[a.S \rightarrow 0 ; \frac{d}{2} a.S ,\]
\[b.S \rightarrow 0 ; \frac{d}{2} b.S ,\]

where \(a.S\) is a chemical species located at object \(a\), and likewise for \(b\), \(k\) is the flux constant, \(r\) is the distance between the two objects, \(r_{cutoff}\) is the global cutoff distance, and \(d\) is an optional decay term.

Automatically updates when running on a CUDA device.

Parameters
  • A (MxParticleType) – first type

  • B (MxParticleType) – second type

  • name (string) – name of species

  • k (float) – transport coefficient

  • decay (float) – optional decay. Defaults to 0.0.

Return type

MxFluxes

Returns

MxFluxes*

static secrete(A: MxParticleType, B: MxParticleType, name: std::string const &, k: float const &, target: float const &, decay: float const & = 0.0) MxFluxes *

Creates a secretion flux by active pumping.

Secretion flux implements the analogous reaction:

\[a.S \rightarrow b.S ; k \left(1 - \frac{r}{r_{cutoff}} \right)\left(a.S - a.S_{target} \right) ,\]
\[a.S \rightarrow 0 ; \frac{d}{2} a.S ,\]
\[b.S \rightarrow 0 ; \frac{d}{2} b.S ,\]

where \(a.S\) is a chemical species located at object \(a\), and likewise for \(b\), \(k\) is the flux constant, \(r\) is the distance between the two objects, \(r_{cutoff}\) is the global cutoff distance, and \(d\) is an optional decay term.

Automatically updates when running on a CUDA device.

Parameters
  • A (MxParticleType) – first type

  • B (MxParticleType) – second type

  • name (string) – name of species

  • k (float) – transport coefficient

  • target (float) – target concentration

  • decay (float) – optional decay. Defaults to 0.0

Return type

MxFluxes

Returns

MxFluxes*

static uptake(A: MxParticleType, B: MxParticleType, name: std::string const &, k: float const &, target: float const &, decay: float const & = 0.0) MxFluxes *

Creates an uptake flux by active pumping.

Uptake flux implements the analogous reaction:

\[a.S \rightarrow b.S ; k \left(1 - \frac{r}{r_{cutoff}}\right)\left(b.S - b.S_{target} \right)\left(a.S\right) ,\]
\[a.S \rightarrow 0 ; \frac{d}{2} a.S ,\]
\[b.S \rightarrow 0 ; \frac{d}{2} b.S ,\]

where \(a.S\) is a chemical species located at object \(a\), and likewise for \(b\), \(k\) is the flux constant, \(r\) is the distance between the two objects, \(r_{cutoff}\) is the global cutoff distance, and \(d\) is an optional decay term.

Automatically updates when running on a CUDA device.

Parameters
  • A (MxParticleType) – first type

  • B (MxParticleType) – second type

  • name (string) – name of species

  • k (float) – transport coefficient

  • target (float) – target concentration

  • decay (float) – optional decay. Defaults to 0.0

Return type

MxFluxes

Returns

MxFluxes*

Binding

mechanica.bind

alias of MxBind

class mechanica.MxBind
static particles(p: MxPotential, a: MxParticle, b: MxParticle) HRESULT

Bind a potential to a pair of particles

Parameters
Return type

int

Returns

HRESULT

static types(p: MxPotential, a: MxParticleType, b: MxParticleType, bound: bool = False) HRESULT

Bind a potential to a pair of particle types.

Automatically updates when running on a CUDA device.

Parameters
  • p (MxPotential) – The potential

  • a (MxParticleType) – The first type

  • b (MxParticleType) – The second type

  • bound (boolean) – Flag signifying whether this potential exclusively operates on particles of different clusters, optional

Return type

int

Returns

HRESULT

static boundaryConditions(p: MxPotential, t: MxParticleType) HRESULT

Bind a potential to a pair of particle type and all boundary conditions.

Automatically updates when running on a CUDA device.

Parameters
Return type

int

Returns

HRESULT

static boundaryCondition(p: MxPotential, bc: MxBoundaryCondition, t: MxParticleType) HRESULT

Bind a potential to a pair of particle type and a boundary conditions.

Automatically updates when running on a CUDA device.

Parameters
Return type

int

Returns

HRESULT

static force(*args) HRESULT

Overload 1:

Bind a force to a particle type

Parameters
Return type

int

Returns

HRESULT


Overload 2:

Bind a force to a particle type with magnitude proportional to a species amount

Parameters
  • force (MxForce) – The force

  • a_type (MxParticleType) – The particle type

  • coupling_symbol (string) – The symbol of the species

Return type

int

Returns

HRESULT

static bonds(potential, particles, cutoff, pairs=None, half_life=None, bond_energy=None, flags=0)

Bonds

mechanica.Bond

alias of MxBond

class mechanica.MxBond

Bonds apply a potential to a particular set of particles.

If you’re building a model, you should probably instead be working with a MxBondHandle.

static create(potential: MxPotential, i: MxParticleHandle, j: MxParticleHandle, half_life: double * = None, dissociation_energy: double * = None, flags: uint32_t = 0) MxBondHandle *

Construct a new bond handle and underlying bond.

Automatically updates when running on a CUDA device.

Parameters
  • potential (MxPotential) – bond potential

  • i (MxParticleHandle) – ith particle

  • j (MxParticleHandle) – jth particle

  • half_life (float) – bond half life

  • dissociation_energy (float) – dissociation energy

  • flags (int) – bond flags

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxBond *

Create from a JSON string representation.

The returned bond is not automatically registered with the engine.

Parameters

str (string) –

Return type

MxBond

Returns

MxBond*

__reduce__()

Helper for pickle.

mechanica.BondHandle

alias of MxBondHandle

class mechanica.MxBondHandle(*args)

Handle to a bond

This is a safe way to work with a bond.

Overload 1:

Construct a new bond handle and do nothing Subsequent usage will require a call to ‘init’


Overload 2:

Construct a new bond handle from an existing bond id

Parameters

id (int) – id of existing bond


Overload 3:

Construct a new bond handle and underlying bond.

Automatically updates when running on a CUDA device.

Parameters
  • potential (MxPotential) – bond potential

  • i (int) – id of ith particle

  • j (int) – id of jth particle

  • half_life (float) – bond half life

  • bond_energy (float) – bond energy

  • flags (int) – bond flags

property energy

bond energy

property parts

bonded particles

property potential

bond potential

property id

bond id

property dissociation_energy

bond dissociation energy

property half_life

bond half life

property active

active flag

property style

bond style

property age

bond age

__str__() str

Return str(self).

__getitem__(index: int)
get() MxBond *

Gets the underlying bond

Return type

MxBond

Returns

MxBond*

static pairwise(pot: MxPotential, parts: MxParticleList, cutoff: double const &, ppairs: vectorPairParticleType_ParticleType, half_life: double const &, bond_energy: double const &, flags: uint32_t) std::vector< MxBondHandle *,std::allocator< MxBondHandle * > > *

Apply bonds to a list of particles.

Automatically updates when running on a CUDA device.

Parameters
  • pot (MxPotential) – the potential of the created bonds

  • parts (MxParticleList) – list of particles

  • cutoff (float) – cutoff distance of particles that are bonded

  • ppairs (std::vector< std::pair< MxParticleType *,MxParticleType * > *,std::allocator< std::pair< MxParticleType *,MxParticleType * > * > >) – type pairs of bonds

  • half_life (float) – bond half life

  • bond_energy (float) – bond energy

  • flags (int) – bond flags

Return type

std::vector< MxBondHandle *,std::allocator< MxBondHandle * > >

Returns

std::vector<MxBondHandle*>*

destroy() HRESULT

Destroy the bond.

Automatically updates when running on a CUDA device.

Return type

int

Returns

HRESULT

static items() std::vector< MxBondHandle *,std::allocator< MxBondHandle * > >

Gets all bonds in the universe

Return type

std::vector< MxBondHandle *,std::allocator< MxBondHandle * > >

Returns

std::vector<MxBondHandle*>

decays() bool

Tests whether this bond decays

Return type

boolean

Returns

true when the bond should decay

mechanica.Angle

alias of MxAngle

class mechanica.MxAngle

A bond concerning an angle

If you’re building a model, you should probably instead be working with a MxAngleHandle.

static create(potential: MxPotential, p1: MxParticleHandle, p2: MxParticleHandle, p3: MxParticleHandle, flags: uint32_t = 0) MxAngleHandle *

Creates an angle bond.

Automatically updates when running on a CUDA device.

Parameters
Return type

MxAngleHandle

Returns

MxAngleHandle*

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxAngle *

Create from a JSON string representation.

The returned angle is not automatically registered with the engine.

Parameters

str (string) –

Return type

MxAngle

Returns

MxAngle*

__reduce__()

Helper for pickle.

mechanica.AngleHandle

alias of MxAngleHandle

class mechanica.MxAngleHandle(*args)

A handle to an angle bond

This is a safe way to work with an angle bond.

property energy

angle energy

property parts

bonded particles

property potential

angle potential

property id

angle id

property dissociation_energy

bond dissociation energy

property half_life

angle half life

property active

active flag

property style

angle style

property age

angle age

__str__() str

Return str(self).

__getitem__(index: int)
get() MxAngle *

Gets the angle of this handle

Return type

MxAngle

Returns

MxAngle*

destroy() HRESULT

Destroy the angle.

Automatically updates when running on a CUDA device.

Return type

int

Returns

HRESULT

static items() std::vector< MxAngleHandle *,std::allocator< MxAngleHandle * > >

Gets all angles in the universe

Return type

std::vector< MxAngleHandle *,std::allocator< MxAngleHandle * > >

Returns

std::vector<MxAngleHandle*>

decays() bool

Tests whether this bond decays

Return type

boolean

Returns

true when the bond should decay

mechanica.Dihedral

alias of MxDihedral

class mechanica.MxDihedral

The dihedral structure

static create(potential: MxPotential, p1: MxParticleHandle, p2: MxParticleHandle, p3: MxParticleHandle, p4: MxParticleHandle) MxDihedralHandle *

Creates a dihedral bond

Parameters
Return type

MxDihedralHandle

Returns

MxDihedralHandle*

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxDihedral *

Create from a JSON string representation.

The returned dihedral is not automatically registered with the engine.

Parameters

str (string) –

Return type

MxDihedral

Returns

MxDihedral*

__reduce__()

Helper for pickle.

mechanica.DihedralHandle

alias of MxDihedralHandle

class mechanica.MxDihedralHandle(*args)

A handle to a dihedral bond

This is a safe way to work with a dihedral bond.

property energy

angle energy

property parts

bonded particles

property potential

angle potential

property id

angle id

property dissociation_energy

bond dissociation energy

property half_life

angle half life

property active

active flag

property style

angle style

property age

angle age

get() MxDihedral *

Gets the dihedral of this handle

Return type

MxDihedral

Returns

MxDihedral*

__str__() str

Return str(self).

__getitem__(index: int)
destroy() HRESULT

Destroy the dihedral

Return type

int

Returns

HRESULT

static items() std::vector< MxDihedralHandle *,std::allocator< MxDihedralHandle * > >

Gets all dihedrals in the universe

Return type

std::vector< MxDihedralHandle *,std::allocator< MxDihedralHandle * > >

Returns

std::vector<MxDihedralHandle*>

decays() bool

Tests whether this bond decays

Return type

boolean

Returns

true when the bond should decay

Events

class mechanica.MxEventBase(*args, **kwargs)
last_fired

Record of last time fired

times_fired

Record of how many times fired

remove() void

Designates event for removal

mechanica.Event

alias of MxEventPy

class mechanica.MxEvent(*args)

Bases: MxEventBase

Construct an instance using functions

Parameters
  • invokeMethod (MxEventMethod) – an invoke function

  • predicateMethod (MxEventMethod) – a predicate function

class mechanica.MxEventPy(invokeExecutor: MxEventPyInvokePyExecutor, predicateExecutor: Optional[MxEventPyPredicatePyExecutor] = None)

Bases: MxEventBase

mechanica.on_event(invoke_method, predicate_method=None)

Creates and registers an event using prescribed invoke and predicate python function executors

Parameters
  • invoke_method (PyObject) – an invoke method; evaluated when an event occurs. Takes an MxEvent instance as argument and returns 0 on success, 1 on error

  • predicate_method – optional predicate method; decides if an event occurs. Takes a MxEvent instance as argument and returns 1 to trigger event, -1 on error and 0 otherwise

mechanica.TimeEvent

alias of MxTimeEventPy

class mechanica.MxTimeEventPy(period: double const &, invokeExecutor: MxTimeEventPyInvokePyExecutor, predicateExecutor: MxTimeEventPyPredicatePyExecutor = None, nextTimeSetter: MxTimeEventNextTimeSetter * = None, start_time: double const & = 0, end_time: double const & = -1)

Bases: MxEventBase

next_time

Next time of evaluation

period

Period of evaluation

start_time

Start time of evaluations

end_time

End time of evaluations

mechanica.on_time(period, invoke_method, predicate_method=None, distribution='default', start_time=0.0, end_time=- 1.0)

Like on_event, but for an event that occurs at regular intervals.

Parameters
  • period (float) – period of event

  • invoke_method (PyObject) – an invoke method; evaluated when an event occurs. Takes an MxTimeEvent instance as argument and returns 0 on success, 1 on error

  • predicate_method – optional predicate method; decides if an event occurs. Takes a MxTimeEvent instance as argument and returns 1 to trigger event, -1 on error and 0 otherwise

  • distribution (str) – distribution by which the next event time is selected

  • start_time (float) – time after which the event can occur

  • end_time (float) – time before which the event can occur; a negative value is interpreted as until ‘forever’

mechanica.ParticleEvent

alias of MxParticleEventPy

class mechanica.MxParticleEvent(*args)

Bases: MxEventBase

targetType

Target particle type of this event

targetParticle

Target particle of an event evaluation

class mechanica.MxParticleEventPy(*args)

Bases: MxParticleEvent

mechanica.on_particle(ptype, invoke_method, predicate_method=None, selector='default', single: bool = False)

Like on_event, but for a particle of a particular particle type.

Parameters
  • ptype (MxParticleType) – the type of particle to select

  • invoke_method (PyObject) – an invoke method; evaluated when an event occurs. Takes an MxParticleEvent instance as argument and returns 0 on success, 1 on error

  • predicate_method – optional predicate method; decides if an event occurs. Takes a MxParticleEvent instance as argument and returns 1 to trigger event, -1 on error and 0 otherwise

  • selector (str) – name of particle selector

  • single (bool) – flag to only trigger event once and then return

mechanica.ParticleTimeEvent

alias of MxParticleTimeEventPy

class mechanica.MxParticleTimeEvent(*args)

Bases: MxEventBase

targetType

Target particle type of this event

targetParticle

Target particle of an event evaluation

next_time

Next time at which an evaluation occurs

period

Period of event evaluations

start_time

Time at which evaluations begin

end_time

Time at which evaluations stop

class mechanica.MxParticleTimeEventPy(*args)

Bases: MxParticleTimeEvent

mechanica.on_particletime(ptype, period, invoke_method, predicate_method=None, distribution='default', start_time=0.0, end_time=- 1.0, selector='default')

A combination of on_time and on_particle.

Parameters
  • ptype (MxParticleType) – the type of particle to select

  • period (float) – period of event

  • invoke_method (PyObject) – an invoke method; evaluated when an event occurs. Takes an MxTimeEvent instance as argument and returns 0 on success, 1 on error

  • predicate_method – optional predicate method; decides if an event occurs. Takes a MxTimeEvent instance as argument and returns 1 to trigger event, -1 on error and 0 otherwise

  • distribution (str) – distribution by which the next event time is selected

  • start_time (str) – time after which the event can occur

  • end_time (float) – time before which the event can occur; a negative value is interpreted as until ‘forever’

  • selector (str) – name of particle selector

mechanica.KeyEvent

alias of MxKeyEvent

class mechanica.MxKeyEvent(glfw_event: Magnum::Platform::GlfwApplication::KeyEvent * = None)
property key_name: str

Key pressed for this event

property key_alt: bool

Flag for whether Alt key is pressed

property key_ctrl: bool

Flag for whether Ctrl key is pressed

property key_shift: bool

Flag for whether Shift key is pressed

mechanica.on_keypress(invoke_method)

Registers a callback for handling keyboard events

Parameters

invoke_method (PyObject) – an invoke method; evaluated when an event occurs. Takes an MxKeyEvent instance as argument and returns None

Lattices

class mechanica.lattice.BondRule(func: Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], part_ids: Tuple[int, int], cell_offset: Tuple[int, int, int])

Simple container for info to create a bond when constructing a lattice

Parameters
  • func – function of func(p1, p2) that accepts two particle handles and returns a newly created bond.

  • part_ids – pair of particle ids in current current and other unit cell.

  • cell_offset – offset vector of other unit cell relative to current unit cell.

class mechanica.lattice.unitcell(N: int, a1: List[float], a2: List[float], a3: List[float], dimensions: int = 3, position: Optional[List[List[float]]] = None, types: Optional[List[MxParticleType]] = None, bonds: Optional[List[BondRule]] = None)

A unit cell

A unit cell is a box definition (a1, a2, a3, dimensions), and particle properties for N particles. You do not need to specify all particle properties. Any property omitted will be initialized to defaults. The function create_lattice initializes the system with many copies of a unit cell.

unitcell is a completely generic unit cell representation. See other classes in the lattice module for convenience wrappers for common lattices.

Example:

uc = lattice.unitcell(N=2,
                      a1=[1, 0, 0],
                      a2=[0.2, 1.2, 0],
                      a3=[-0.2, 0, 1.0],
                      dimensions=3,
                      position=[[0, 0, 0], [0.5, 0.5, 0.5]],
                      types=[A, B])
Note:

a1, a2, a3 must define a right handed coordinate system.

Parameters
  • N (int) – Number of particles in the unit cell.

  • a1 (List[float]) – Lattice vector (3-vector).

  • a2 (List[float]) – Lattice vector (3-vector).

  • a3 (List[float]) – Lattice vector (3-vector).

  • dimensions (int) – Dimensionality of the lattice (2 or 3).

  • position (List[List[float]]) – List of particle positions.

  • types (List[m.MxParticleType]) – List of particle types

  • bonds (List[BondRule]) – bond constructors rules

mechanica.lattice.sc(a: float, types: Optional[MxParticleType] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True, True)) unitcell

Create a unit cell for a simple cubic lattice (3D).

The simple cubic lattice unit cell has one particle:

  • [0, 0, 0]

And the box matrix:

  • [[a, 0, 0] [0, a, 0] [0, 0, a]]

Example:

uc = mechanica.lattice.sc(1.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • types – particle type

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds in the 1-, 2-, and 3-directions

Returns

a simple cubic lattice unit cell

mechanica.lattice.bcc(a: float, types: Optional[Union[MxParticleType, List[MxParticleType]]] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True)) unitcell

Create a unit cell for a body centered cubic lattice (3D).

The body centered cubic lattice unit cell has two particles:

  • [0, 0, 0]

  • [a/2, a/2, a/2]

And the box matrix:

  • [[a, 0, 0] [0, a, 0] [0, 0, a]]

Example:

uc = mechanica.lattice.bcc(1.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • types – particle type or list of particle types

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds - between the corner particles - between the corner and center particles

Returns

a body centered cubic lattice unit cell

mechanica.lattice.fcc(a: float, types: Optional[Union[MxParticleType, List[MxParticleType]]] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True)) unitcell

Create a unit cell for a face centered cubic lattice (3D).

The face centered cubic lattice unit cell has four particles:

  • [0, 0, 0]

  • [0, a/2, a/2]

  • [a/2, 0, a/2]

  • [a/2, a/2, 0]]

And the box matrix:

  • [[a, 0, 0] [0, a, 0] [0, 0, a]]

Example:

uc = mechanica.lattice.fcc(1.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • types – particle type or list of particle types

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds - between the corner particles - between the corner and the center particles

Returns

a face centered cubic lattice unit cell

mechanica.lattice.sq(a: float, types: Optional[Union[MxParticleType, List[MxParticleType]]] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True, False)) unitcell

Create a unit cell for a square lattice (2D).

The square lattice unit cell has one particle:

  • [0, 0]

And the box matrix:

  • [[a, 0] [0, a]]

Example:

uc = mechanica.lattice.sq(1.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • types – particle type or list of particle types

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds along the 1-, 2- and 3-directions

Returns

a square lattice unit cell

mechanica.lattice.hex2d(a: float, types: Optional[Union[MxParticleType, List[MxParticleType]]] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True, False)) unitcell

Create a unit cell for a hexagonal lattice (2D).

The hexagonal lattice unit cell has two particles:

  • [0, 0]

  • [0, a*sqrt(3)/2]

And the box matrix:

  • [[a, 0] [0, a*sqrt(3)]]

Example:

uc = mechanica.lattice.hex2d(1.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • types – particle type or list of particle types

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds along the 1-, 2- and 3-directions

Returns

a hexagonal lattice unit cell

mechanica.lattice.hcp(a: float, c: Optional[float] = None, types: Optional[Union[MxParticleType, List[MxParticleType]]] = None, bond: Optional[Union[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle], List[Callable[[MxParticleHandle, MxParticleHandle], MxBondHandle]]]] = None, bond_vector: Tuple[bool] = (True, True, True)) unitcell

Create a unit cell for a hexagonal close pack lattice (3D).

The hexagonal close pack lattice unit cell has seven particles:

  • [0, a*sqrt(3)/2, 0]

  • [a/2, 0, 0]

  • [a, a*sqrt(3)/2, 0]

  • [a*3/2, 0, 0]

  • [a/2, a*2/sqrt(3), c/2]

  • [a, a/2/sqrt(3), c/2]

  • [a*3/2, a*2/sqrt(3), c/2]

And the box matrix:

  • [[2*a, 0, 0] [0, a*sqrt(3), 0] [0, 0, c]]

Example:

uc = mechanica.lattice.hcp(1.0, 2.0, A, lambda i, j: mx.Bond.create(pot, i, j, dissociation_energy=100.0))
Parameters
  • a – lattice constant

  • c – height of lattice (default a)

  • types – particle type or list of particle types

  • bond – bond constructor(s)

  • bond_vector – flags for creating bonds - between the outer particles - between the inner particles - between the outer and inner particles

Returns

a hexagonal close pack lattice unit cell

mechanica.lattice.create_lattice(uc: unitcell, n: Union[int, List[int]], origin: Optional[List[float]] = None) ndarray

Create a lattice

Takes a unit cell and replicates it the requested number of times in each direction. A generic unitcell may have arbitrary vectors a1, a2, and a3. create_lattice will rotate the unit cell so that a1 points in the x direction and a2 is in the xy plane so that the lattice may be represented as a simulation box. When n is a single value, the lattice is replicated n times in each direction. When n is a list, the lattice is replicated n[i] times in each ``i``th direction.

Examples:

mechanica.lattice.create_lattice(uc=mechanica.lattice.sc(a=1.0), n=[2,4,2])
mechanica.lattice.create_lattice(uc=mechanica.lattice.bcc(a=1.0), n=10)
mechanica.lattice.create_lattice(uc=mechanica.lattice.sq(a=1.2), n=[100,10])
mechanica.lattice.create_lattice(uc=mechanica.lattice.hex2d(a=1.0), n=[100,58])
Parameters
  • uc – unit cell

  • n – number of unit cells to create along all/each direction(s)

  • origin – origin to begin creating lattice (default centered about simulation origin)

Returns

particles created in every unit cell

Style

mechanica.Style

alias of MxStyle

class mechanica.MxStyle(*args)

The Mechanica style type

property visible: bool

Visibility flag

property colormap

Style color map

property mapper

Color mapper of this style

setColor(colorName: std::string const &) HRESULT

Set the color by name

Parameters

colorName (string) – name of color

Return type

int

Returns

HRESULT

newColorMapper(*args, **kwargs) void

Construct and apply a new color map for a particle type and species

Parameters
  • partType (MxParticleType) – particle type

  • speciesName (string) – name of species

  • name (string) – name of color map

  • min (float) – minimum value of map

  • max (float) – maximum value of map

toString() std::string

Get a JSON string representation

Return type

string

Returns

std::string

static fromString(str: std::string const &) MxStyle *

Create from a JSON string representation.

Parameters

str (string) –

Return type

MxStyle

Returns

MxStyle*

__reduce__()

Helper for pickle.

mechanica.ColorMapper

alias of MxColorMapper

class mechanica.MxColorMapper(*args)

The color mapping type

Construct a new color map for a particle type and species

Parameters
  • partType (MxParticleType) – particle type

  • speciesName (string) – name of species

  • name (string) – name of color mapper function

  • min (float) – minimum value of map

  • max (float) – maximum value of map

property names

Names of available color maps

property min_val

minimum value of map

property max_val

maximum value of map

set_colormap(s: std::string const &) bool

Try to set the colormap.

If the map doesn’t exist, does not do anything and returns false.

Parameters

s (string) – name of color map

Return type

boolean

Returns

true on success

Rendering

mechanica.ClipPlane

alias of MxClipPlane

class mechanica.MxClipPlane(i: int)
property index

Index of the clip plane. Less than zero if clip plane has been destroyed.

property point: MxVector3f
property normal: MxVector3f
getEquation() MxVector4f

Get the coefficients of the plane equation of the clip plane

Return type

MxVector4f

Returns

MxVector4f

setEquation(*args) HRESULT

Overload 1:

Set the coefficients of the plane equation of the clip plane

Parameters

pe (MxVector4f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the coefficients of the plane equation of the clip plane using a point on the plane and its normal

Parameters
Return type

int

Returns

HRESULT

destroy() HRESULT

Destroy the clip plane

Return type

int

Returns

HRESULT

mechanica.ClipPlanes

alias of MxClipPlanes

class mechanica.MxClipPlanes
static len() int

Get the number of clip planes

Return type

int

Returns

int

static getClipPlaneEquation(index: unsigned int const &) MxVector4f const &

Get the coefficients of the equation of a clip plane

Parameters

index (int) – index of the clip plane

Return type

MxVector4f

Returns

const MxVector4f&

static setClipPlaneEquation(index: unsigned int const &, pe: MxVector4f) HRESULT

Set the coefficients of the equation of a clip plane.

The clip plane must already exist

Parameters
  • index (int) – index of the clip plane

  • pe (MxVector4f) – coefficients of the plane equation of the clip plane

Return type

int

Returns

HRESULT

static item(index: unsigned int const &) MxClipPlane

Get a clip plane by index

Parameters

index (int) – index of the clip plane

Return type

MxClipPlane

Returns

MxClipPlane

static create(*args) MxClipPlane

Overload 1:

Create a clip plane

Parameters

pe (MxVector4f) – coefficients of the equation of the plane

Return type

MxClipPlane

Returns

MxClipPlane


Overload 2:

Create a clip plane

Parameters
Return type

MxClipPlane

Returns

MxClipPlane

class mechanica.SubRendererFlags(value)

Flags for referencing subrenderers in select methods

angle = 1

Angle subrenderer

arrow = 2

Arrow subrenderer

bond = 4

Bond subrenderer

dihedral = 8

Dihedral subrenderer

System

mechanica.system

alias of MxSystemPy

class mechanica.MxSystem

Provides various methods to interact with the rendering engine and host CPU.

subrenderer = <enum 'SubRendererFlags'>

Subrenderer flags

static screenshot(filepath: str, decorate: Optional[bool] = None, bgcolor=None)

Save a screenshot of the current scene

Parameters
  • filepath (str) – path of file to save

  • decorate (bool) – flag to decorate the scene in the screenshot

  • bgcolor (MxVector3f or [float, float, float] or (float, float, float) or float) – background color of the scene in the screenshot

Return type

int

Returns

HRESULT

static cameraMoveTo(*args) HRESULT

Overload 1:

Set the camera view parameters

Parameters
Return type

int

Returns

HRESULT


Overload 2:

Set the camera view parameters

Parameters
  • center (MxVector3f) – target camera view center position

  • rotation (MxQuaternionf) – target camera rotation

  • zoom (float) – target camera zoom

Return type

int

Returns

HRESULT

static cameraViewBottom() HRESULT

Move the camera to view the domain from the bottm

Return type

int

Returns

HRESULT

static cameraViewTop() HRESULT

Move the camera to view the domain from the top

Return type

int

Returns

HRESULT

static cameraViewLeft() HRESULT

Move the camera to view the domain from the left

Return type

int

Returns

HRESULT

static cameraViewRight() HRESULT

Move the camera to view the domain from the right

Return type

int

Returns

HRESULT

static cameraViewBack() HRESULT

Move the camera to view the domain from the back

Return type

int

Returns

HRESULT

static cameraViewFront() HRESULT

Move the camera to view the domain from the front

Return type

int

Returns

HRESULT

static cameraReset() HRESULT

Reset the camera

Return type

int

Returns

HRESULT

static cameraTranslateDown() HRESULT

Translate the camera down

Return type

int

Returns

HRESULT

static cameraTranslateUp() HRESULT

Translate the camera up

Return type

int

Returns

HRESULT

static cameraTranslateRight() HRESULT

Translate the camera right

Return type

int

Returns

HRESULT

static cameraTranslateLeft() HRESULT

Translate the camera left

Return type

int

Returns

HRESULT

static cameraTranslateForward() HRESULT

Translate the camera forward

Return type

int

Returns

HRESULT

static cameraTranslateBackward() HRESULT

Translate the camera backward

Return type

int

Returns

HRESULT

static cameraRotateDown() HRESULT

Rotate the camera down

Return type

int

Returns

HRESULT

static cameraRotateUp() HRESULT

Rotate the camera up

Return type

int

Returns

HRESULT

static cameraRotateLeft() HRESULT

Rotate the camera left

Return type

int

Returns

HRESULT

static cameraRotateRight() HRESULT

Rotate the camera right

Return type

int

Returns

HRESULT

static cameraRollLeft() HRESULT

Roll the camera left

Return type

int

Returns

HRESULT

static cameraRollRight() HRESULT

Rotate the camera right

Return type

int

Returns

HRESULT

static cameraZoomIn() HRESULT

Zoom the camera in

Return type

int

Returns

HRESULT

static cameraZoomOut() HRESULT

Zoom the camera out

Return type

int

Returns

HRESULT

static cameraZoomBy(delta: float const &) HRESULT

Zoom the camera by an increment in distance.

Positive values zoom in.

Parameters

delta (float) – zoom increment

Return type

int

Returns

HRESULT

static cameraZoomTo(distance: float const &) HRESULT

Zoom the camera to a distance.

Parameters

distance (float) – zoom distance

Return type

int

Returns

HRESULT

static cameraRotateToAxis(axis: MxVector3f, distance: float const &) HRESULT

Rotate the camera to a point from the view center a distance along an axis.

Only rotates the view to the given eye position.

Parameters
  • axis (MxVector3f) – axis from the view center

  • distance (float) – distance along the axis

Return type

int

Returns

HRESULT

static cameraRotateToEulerAngle(angles: MxVector3f) HRESULT

Rotate the camera to a set of Euler angles.

Rotations are Z-Y-X.

Parameters

angles (MxVector3f) –

Return type

int

Returns

HRESULT

static cameraCenter() MxVector3f

Get the current camera view center position

Return type

MxVector3f

Returns

MxVector3f

static cameraRotation() MxQuaternionf

Get the current camera rotation

Return type

MxQuaternionf

Returns

MxQuaternionf

static cameraZoom() float

Get the current camera zoom

Return type

float

Returns

float

static getAmbientColor() MxVector3f

Get the ambient color

Return type

MxVector3f

Returns

MxVector3f

static setAmbientColor(*args) HRESULT

Overload 1:

Set the ambient color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the ambient color of a subrenderer

Parameters
Return type

int

Returns

HRESULT

static getDiffuseColor() MxVector3f

Get the diffuse color

Return type

MxVector3f

Returns

MxVector3f

static setDiffuseColor(*args) HRESULT

Overload 1:

Set the diffuse color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the diffuse color of a subrenderer

Parameters
Return type

int

Returns

HRESULT

static getSpecularColor() MxVector3f

Get specular color

Return type

MxVector3f

Returns

MxVector3f

static setSpecularColor(*args) HRESULT

Overload 1:

Set the specular color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the specular color of a subrenderer

Parameters
Return type

int

Returns

HRESULT

static getShininess() float

Get the shininess

Return type

float

Returns

float

static setShininess(*args) HRESULT

Overload 1:

Set the shininess

Parameters

shininess (float) –

Return type

int

Returns

HRESULT


Overload 2:

Set the shininess of a subrenderer

Parameters
  • shininess (float) –

  • srFlag (int) –

Return type

int

Returns

HRESULT

static getGridColor() MxVector3f

Get the grid color

Return type

MxVector3f

Returns

MxVector3f

static setGridColor(color: MxVector3f) HRESULT

Set the grid color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT

static getSceneBoxColor() MxVector3f

Get the scene box color

Return type

MxVector3f

Returns

MxVector3f

static setSceneBoxColor(color: MxVector3f) HRESULT

Set the scene box color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT

static getLightDirection() MxVector3f

Get the light direction

Return type

MxVector3f

Returns

MxVector3f

static setLightDirection(*args) HRESULT

Overload 1:

Set the light direction

Parameters

lightDir (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the light direction of a subrenderer

Parameters
Return type

int

Returns

HRESULT

static getLightColor() MxVector3f

Get the light color

Return type

MxVector3f

Returns

MxVector3f

static setLightColor(*args) HRESULT

Overload 1:

Set the light color

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Set the light color of a subrenderer

Parameters
Return type

int

Returns

HRESULT

static decorated() bool

Test whether the rendered scene is decorated

Return type

boolean

Returns

true

Return type

boolean

Returns

false

static decorateScene(decorate: bool const &) HRESULT

Set flag to draw/not draw scene decorators (e.g., grid)

Parameters

decorate (boolean) – flag; true says to decorate

Return type

int

Returns

HRESULT

static showingDiscretization() bool

Test whether discretization is current shown

Return type

boolean

Returns

true

Return type

boolean

Returns

false

static showDiscretization(show: bool const &) HRESULT

Set flag to draw/not draw discretization

Parameters

show (boolean) – flag; true says to show

Return type

int

Returns

HRESULT

static getDiscretizationColor() MxVector3f

Get the current color of the discretization grid

Return type

MxVector3f

Returns

MxVector3f

static setDiscretizationColor(color: MxVector3f) HRESULT

Set the color of the discretization grid

Parameters

color (MxVector3f) –

Return type

int

Returns

HRESULT

static cpu_info() dict

Dictionary of CPU info

static compile_flags() dict

Dictionary of compiler flags

static gl_info() dict

Dictionary of OpenGL info

static egl_info() std::string

Get EGL info

Return type

string

Returns

std::string

class mechanica.MxSystemPy

Bases: MxSystem

static is_terminal_interactive() bool

Test whether Mechanica is running in an interactive terminal

Return type

boolean

Returns

true if running in an interactive terminal

Return type

boolean

Returns

false

static is_jupyter_notebook() bool

Test whether Mechanica is running in a Jupyter notebook

Return type

boolean

Returns

true if running in a Jupyter notebook

Return type

boolean

Returns

false

Logging

Mechanica has a detailed logging system. Many internal methods will log extensive details to either the clog (typically stderr) or a user specified file path. The logging system can be configured to log events at various levels of detail. All methods of the Logger are static, they are available immediately upon loading the Mechanica package.

To display logging at the lowest level (TRACE), where every logging message is displayed, is as simple as,

import mechanica as mx
mx.Logger.setLevel(mx.Logger.TRACE)

Enabling logging to terminal and disabling are also single commands,

mx.Logger.enableConsoleLogging(mx.Logger.DEBUG)
...
mx.Logger.disableConsoleLogging()

Messages can also be added to the log by logging level.

mx.Logger.log(mx.Logger.FATAL, "A fatal message. This is the highest priority.")
mx.Logger.log(mx.Logger.CRITICAL, "A critical message")
mx.Logger.log(mx.Logger.ERROR, "An error message")
mx.Logger.log(mx.Logger.WARNING, "A warning message")
mx.Logger.log(mx.Logger.NOTICE, "A notice message")
mx.Logger.log(mx.Logger.INFORMATION, "An informational message")
mx.Logger.log(mx.Logger.DEBUG, "A debugging message.")
mx.Logger.log(mx.Logger.TRACE,  "A tracing message. This is the lowest priority.")
mechanica.Logger

alias of MxLogger

class mechanica.MxLogger

The Mechanica logger.

A set of static method for setting the logging level.

static setLevel(level: int = 0) void

Set the Level objectsets the logging level to one a value from Logger::Level

Parameters

level (int) – logging level

static getLevel() int

Get the Level objectget the current logging level.

Return type

int

Returns

int

static disableLogging() void

Suppresses all logging output

static enableConsoleLogging(level: int = 0) void

turns on console logging at the given level.

Parameters

level (int) – logging level

static disableConsoleLogging() void

stops logging to the console, but file logging may continue.

static enableFileLogging(*args, **kwargs) void

turns on file logging to the given file as the given level.

If fileName is an empty string, then nothing occurs.

Parameters
  • fileName (string) – path to log file

  • level (int) – logging level

static disableFileLogging() void

turns off file logging, but has no effect on console logging.

static getCurrentLevelAsString() std::string

get the textural form of the current logging level.

Return type

string

Returns

std::string

static getFileName() std::string

Get the File Name objectget the name of the currently used log file.

Return type

string

Returns

std::string

static levelToString(level: int) std::string

gets the textual form of a logging level Enum for a given value.

static stringToLevel(str: std::string const &) MxLogLevel

parses a string and returns a Logger::Level

static log(level: MxLogLevel, msg: std::string const &) void

logs a message to the log.

Parameters
  • level (int) – logging level

  • msg (string) – log message

Utilities

mechanica.random_point(kind: int, dr: Optional[float] = None, phi0: Optional[float] = None, phi1: Optional[float] = None)

Get the coordinates of a random point in a kind of shape.

Currently supports PointsType.Sphere, PointsType.Disk, PointsType.SolidCube and PointsType.SolidSphere.

Parameters
  • kind – kind of shape

  • dr – thickness parameter; only applicable to solid sphere kind

  • phi0 – angle lower bound; only applicable to solid sphere kind

  • phi1 – angle upper bound; only applicable to solid sphere kind

Returns

coordinates of random points

Return type

MxVector3f

mechanica.random_points(kind: int, n: int = 1, dr: Optional[float] = None, phi0: Optional[float] = None, phi1: Optional[float] = None)

Get the coordinates of random points in a kind of shape.

Currently supports PointsType.Sphere, PointsType.Disk, PointsType.SolidCube and PointsType.SolidSphere.

Parameters
  • kind – kind of shape

  • n – number of points

  • dr – thickness parameter; only applicable to solid sphere kind

  • phi0 – angle lower bound; only applicable to solid sphere kind

  • phi1 – angle upper bound; only applicable to solid sphere kind

Returns

coordinates of random points

Return type

list of MxVector3f

mechanica.points(kind: int, n: int = 1)

Get the coordinates of uniform points in a kind of shape.

Currently supports PointsType.Ring and PointsType.Sphere.

Parameters
  • kind – kind of shape

  • n – number of points

Returns

coordinates of uniform points

Return type

list of MxVector3f

mechanica.filled_cube_uniform(corner1, corner2, num_parts_x: int = 2, num_parts_y: int = 2, num_parts_z: int = 2)

Get the coordinates of a uniformly filled cube.

Parameters
  • corner1 (list of float or MxVector3f) – first corner of cube

  • corner2 (list of float or MxVector3f) – second corner of cube

  • num_parts_x – number of particles along x-direction of filling axes (>=2)

  • num_parts_y – number of particles along y-direction of filling axes (>=2)

  • num_parts_z – number of particles along z-direction of filling axes (>=2)

Returns

coordinates of uniform points

Return type

list of MxVector3f

mechanica.filled_cube_random(corner1, corner2, num_particles: int)

Get the coordinates of a randomly filled cube.

Parameters
  • corner1 (list of float or MxVector3f) – first corner of cube

  • corner2 (list of float or MxVector3f) – second corner of cube

  • num_particles – number of particles

Returns

coordinates of random points

Return type

list of MxVector3f

mechanica.icosphere(subdivisions: int, phi0: float, phi1: float)

Get the coordinates of an icosphere.

Parameters
  • subdivisions – number of subdivisions

  • phi0 – angle lower bound

  • phi1 – angle upper bound

Returns

vertices and indices

Return type

(list of MxVector3f, list of int)

mechanica.color3_names()

Get the names of all available colors

Return type

list of str

mechanica.primes(start_prime: int, n: int)

Get prime numbers, beginning with a starting prime number.

Parameters
  • start_prime – Starting prime number

  • n – Number of prime numbers to get

Returns

Requested prime numbers

Return type

list of int

mechanica.random_vector(mean: float, std: float) MxVector3f

Generates a randomly oriented vector with random magnitude with given mean and standard deviation according to a normal distribution.

Parameters
  • mean (float) – magnitude mean

  • std (float) – magnitude standard deviation

Return type

MxVector3f

Returns

MxVector3f

mechanica.random_unit_vector() MxVector3f

Generates a randomly oriented unit vector.

Return type

MxVector3f

Returns

MxVector3f

mechanica.get_seed() unsigned int

Get the current seed for the pseudo-random number generator

mechanica.set_seed(_seed: unsigned int const * = None) HRESULT

Set the current seed for the pseudo-random number generator

Parameters

_seed (int) –

Return type

int

Returns

HRESULT

Basic Mechanica Types

Mechanica uses some basic types that provide support and convenience methods for particular operations, especially concerning vector and tensor operations. Some of these types are completely native to Mechanica, and others constructed partially or completely from types distributed in various Mechanica dependencies (e.g., MxVector3f from Vector3, from Magnum.

class mechanica.MxVector2d(*args)

A 2D vector with double elements

static xAxis(*args, **kwargs) mx::type::MxVector2< double >
static yAxis(*args, **kwargs) mx::type::MxVector2< double >
static xScale(scale: double) mx::type::MxVector2< double >
static yScale(scale: double) mx::type::MxVector2< double >
x(*args) double
y(*args) double
flipped() mx::type::MxVector2< double >
dot(*args) double
__len__() int
__iadd__(*args) mx::type::MxVector2< double > &
__add__(*args) mx::type::MxVector2< double >
__isub__(*args) mx::type::MxVector2< double > &
__sub__(*args) mx::type::MxVector2< double >
__imul__(*args) mx::type::MxVector2< double > &
__mul__(*args) mx::type::MxVector2< double >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(line_start_pt, line_end_pt)

distance from a line defined by two points

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector2f(*args)

A 2D vector with float elements

static xAxis(*args, **kwargs) mx::type::MxVector2< float >
static yAxis(*args, **kwargs) mx::type::MxVector2< float >
static xScale(scale: float) mx::type::MxVector2< float >
static yScale(scale: float) mx::type::MxVector2< float >
x(*args) float
y(*args) float
flipped() mx::type::MxVector2< float >
dot(*args) float
__len__() int
__iadd__(*args) mx::type::MxVector2< float > &
__add__(*args) mx::type::MxVector2< float >
__isub__(*args) mx::type::MxVector2< float > &
__sub__(*args) mx::type::MxVector2< float >
__imul__(*args) mx::type::MxVector2< float > &
__mul__(*args) mx::type::MxVector2< float >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(line_start_pt, line_end_pt)

distance from a line defined by two points

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector2i(*args)

A 2D vector with int elements

static xAxis(*args, **kwargs) mx::type::MxVector2< int >
static yAxis(*args, **kwargs) mx::type::MxVector2< int >
static xScale(scale: int) mx::type::MxVector2< int >
static yScale(scale: int) mx::type::MxVector2< int >
x(*args) int
y(*args) int
flipped() mx::type::MxVector2< int >
dot(*args) int
__len__() int
__iadd__(*args) mx::type::MxVector2< int > &
__add__(*args) mx::type::MxVector2< int >
__isub__(*args) mx::type::MxVector2< int > &
__sub__(*args) mx::type::MxVector2< int >
__imul__(*args) mx::type::MxVector2< int > &
__mul__(*args) mx::type::MxVector2< int >
__itruediv__(*args)
__truediv__(*args)
__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector3d(*args)

A 3D vector with double elements

static xAxis(*args, **kwargs) mx::type::MxVector3< double >
static yAxis(*args, **kwargs) mx::type::MxVector3< double >
static zAxis(*args, **kwargs) mx::type::MxVector3< double >
static xScale(scale: double) mx::type::MxVector3< double >
static yScale(scale: double) mx::type::MxVector3< double >
static zScale(scale: double) mx::type::MxVector3< double >
x(*args) double
y(*args) double
z(*args) double
r(*args) double
g(*args) double
b(*args) double
xy()
flipped() mx::type::MxVector3< double >
dot(*args) double
__len__() int
__iadd__(*args) mx::type::MxVector3< double > &
__add__(*args) mx::type::MxVector3< double >
__isub__(*args) mx::type::MxVector3< double > &
__sub__(*args) mx::type::MxVector3< double >
__imul__(*args) mx::type::MxVector3< double > &
__mul__(*args) mx::type::MxVector3< double >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(line_start_pt, line_end_pt)

distance from a line defined by two points

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector3f(*args)

A 3D vector with float elements

static xAxis(*args, **kwargs) mx::type::MxVector3< float >
static yAxis(*args, **kwargs) mx::type::MxVector3< float >
static zAxis(*args, **kwargs) mx::type::MxVector3< float >
static xScale(scale: float) mx::type::MxVector3< float >
static yScale(scale: float) mx::type::MxVector3< float >
static zScale(scale: float) mx::type::MxVector3< float >
x(*args) float
y(*args) float
z(*args) float
r(*args) float
g(*args) float
b(*args) float
xy()
flipped() mx::type::MxVector3< float >
dot(*args) float
__len__() int
__iadd__(*args) mx::type::MxVector3< float > &
__add__(*args) mx::type::MxVector3< float >
__isub__(*args) mx::type::MxVector3< float > &
__sub__(*args) mx::type::MxVector3< float >
__imul__(*args) mx::type::MxVector3< float > &
__mul__(*args) mx::type::MxVector3< float >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(line_start_pt, line_end_pt)

distance from a line defined by two points

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector3i(*args)

A 3D vector with int elements

static xAxis(*args, **kwargs) mx::type::MxVector3< int >
static yAxis(*args, **kwargs) mx::type::MxVector3< int >
static zAxis(*args, **kwargs) mx::type::MxVector3< int >
static xScale(scale: int) mx::type::MxVector3< int >
static yScale(scale: int) mx::type::MxVector3< int >
static zScale(scale: int) mx::type::MxVector3< int >
x(*args) int
y(*args) int
z(*args) int
r(*args) int
g(*args) int
b(*args) int
xy(*args) mx::type::MxVector2< int > const
flipped() mx::type::MxVector3< int >
dot(*args) int
__len__() int
__iadd__(*args) mx::type::MxVector3< int > &
__add__(*args) mx::type::MxVector3< int >
__isub__(*args) mx::type::MxVector3< int > &
__sub__(*args) mx::type::MxVector3< int >
__imul__(*args) mx::type::MxVector3< int > &
__mul__(*args) mx::type::MxVector3< int >
__itruediv__(*args)
__truediv__(*args)
__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector4d(*args)

A 4D vector with double elements

x(*args) double
y(*args) double
z(*args) double
w(*args) double
r(*args) double
g(*args) double
b(*args) double
a(*args) double
xyz()
rgb(*args) mx::type::MxVector3< double > const
xy(*args) mx::type::MxVector2< double > const
flipped() mx::type::MxVector4< double >
dot(*args) double
__len__() int
__iadd__(*args) mx::type::MxVector4< double > &
__add__(*args) mx::type::MxVector4< double >
__isub__(*args) mx::type::MxVector4< double > &
__sub__(*args) mx::type::MxVector4< double >
__imul__(*args) mx::type::MxVector4< double > &
__mul__(*args) mx::type::MxVector4< double >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(point)

distance from a point

distanceScaled(point)

scaled distance from a point

classmethod planeEquation(*args)

get a plane equation

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector4f(*args)

A 4D vector with float elements

x(*args) float
y(*args) float
z(*args) float
w(*args) float
r(*args) float
g(*args) float
b(*args) float
a(*args) float
xyz()
rgb(*args) mx::type::MxVector3< float > const
xy(*args) mx::type::MxVector2< float > const
flipped() mx::type::MxVector4< float >
dot(*args) float
__len__() int
__iadd__(*args) mx::type::MxVector4< float > &
__add__(*args) mx::type::MxVector4< float >
__isub__(*args) mx::type::MxVector4< float > &
__sub__(*args) mx::type::MxVector4< float >
__imul__(*args) mx::type::MxVector4< float > &
__mul__(*args) mx::type::MxVector4< float >
__itruediv__(*args)
__truediv__(*args)
length()

length of vector

normalized()

vector normalized

resized(length)

resize be a length

projected(other)

project onto another vector

projectedOntoNormalized(other)

project onto a normalized vector

distance(point)

distance from a point

distanceScaled(point)

scaled distance from a point

classmethod planeEquation(*args)

get a plane equation

__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxVector4i(*args)

A 4D vector with int elements

x(*args) int
y(*args) int
z(*args) int
w(*args) int
r(*args) int
g(*args) int
b(*args) int
a(*args) int
xyz(*args) mx::type::MxVector3< int > const
rgb(*args) mx::type::MxVector3< int > const
xy(*args) mx::type::MxVector2< int > const
flipped() mx::type::MxVector4< int >
dot(*args) int
__len__() int
__iadd__(*args) mx::type::MxVector4< int > &
__add__(*args) mx::type::MxVector4< int >
__isub__(*args) mx::type::MxVector4< int > &
__sub__(*args) mx::type::MxVector4< int >
__imul__(*args) mx::type::MxVector4< int > &
__mul__(*args) mx::type::MxVector4< int >
__itruediv__(*args)
__truediv__(*args)
__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxMatrix3d(*args)

A 3x3 square matrix with double elements

static rotation(angle: double) mx::type::MxMatrix3< double >
static shearingX(amount: double) mx::type::MxMatrix3< double >
static shearingY(amount: double) mx::type::MxMatrix3< double >
isRigidTransformation() bool
invertedRigid() mx::type::MxMatrix3< double >
__neg__() mx::type::MxMatrix3< double >
__iadd__(other: MxMatrix3d) mx::type::MxMatrix3< double > &
__add__(other: MxMatrix3d) mx::type::MxMatrix3< double >
__isub__(other: MxMatrix3d) mx::type::MxMatrix3< double > &
__sub__(other: MxMatrix3d) mx::type::MxMatrix3< double >
__imul__(number: double) mx::type::MxMatrix3< double > &
__mul__(*args) mx::type::MxVector3< double >
__itruediv__(*args)
__truediv__(*args)
flippedCols() mx::type::MxMatrix3< double >
flippedRows() mx::type::MxMatrix3< double >
row(row: std::size_t) mx::type::MxVector3< double >
__mul__(*args) mx::type::MxVector3< double >
transposed() mx::type::MxMatrix3< double >
diagonal() mx::type::MxVector3< double >
inverted() mx::type::MxMatrix3< double >
invertedOrthogonal() mx::type::MxMatrix3< double >
__len__() int
__getitem__(index: int)
__setitem__(index: int, val)
as_lists() list

convert to a list of python lists

__str__() str

Return str(self).

class mechanica.MxMatrix3f(*args)

A 3x3 square matrix with float elements

static rotation(angle: float) mx::type::MxMatrix3< float >
static shearingX(amount: float) mx::type::MxMatrix3< float >
static shearingY(amount: float) mx::type::MxMatrix3< float >
isRigidTransformation() bool
invertedRigid() mx::type::MxMatrix3< float >
__neg__() mx::type::MxMatrix3< float >
__iadd__(other: MxMatrix3f) mx::type::MxMatrix3< float > &
__add__(other: MxMatrix3f) mx::type::MxMatrix3< float >
__isub__(other: MxMatrix3f) mx::type::MxMatrix3< float > &
__sub__(other: MxMatrix3f) mx::type::MxMatrix3< float >
__imul__(number: float) mx::type::MxMatrix3< float > &
__mul__(*args) mx::type::MxVector3< float >
__itruediv__(*args)
__truediv__(*args)
flippedCols() mx::type::MxMatrix3< float >
flippedRows() mx::type::MxMatrix3< float >
row(row: std::size_t) mx::type::MxVector3< float >
__mul__(*args) mx::type::MxVector3< float >
transposed() mx::type::MxMatrix3< float >
diagonal() mx::type::MxVector3< float >
inverted() mx::type::MxMatrix3< float >
invertedOrthogonal() mx::type::MxMatrix3< float >
__len__() int
__getitem__(index: int)
__setitem__(index: int, val)
as_lists() list

convert to a list of python lists

__str__() str

Return str(self).

class mechanica.MxMatrix4d(*args)

A 4x4 square matrix with double elements

static rotationX(angle: double) mx::type::MxMatrix4< double >
static rotationY(angle: double) mx::type::MxMatrix4< double >
static rotationZ(angle: double) mx::type::MxMatrix4< double >
static reflection(normal: MxVector3d) mx::type::MxMatrix4< double >
static shearingXY(amountX: double, amountY: double) mx::type::MxMatrix4< double >
static shearingXZ(amountX: double, amountZ: double) mx::type::MxMatrix4< double >
static shearingYZ(amountY: double, amountZ: double) mx::type::MxMatrix4< double >
static orthographicProjection(size: MxVector2d, near: double, far: double) mx::type::MxMatrix4< double >
static perspectiveProjection(*args) mx::type::MxMatrix4< double >
static lookAt(eye: MxVector3d, target: MxVector3d, up: MxVector3d) mx::type::MxMatrix4< double >
isRigidTransformation() bool
rotationScaling() mx::type::MxMatrix3< double >
rotationShear() mx::type::MxMatrix3< double >
rotation(*args) mx::type::MxMatrix3< double >
rotationNormalized() mx::type::MxMatrix3< double >
scalingSquared() mx::type::MxVector3< double >
scaling(*args) mx::type::MxVector3< double >
uniformScalingSquared() double
uniformScaling() double
normalMatrix() mx::type::MxMatrix3< double >
right(*args) mx::type::MxVector3< double >
up(*args) mx::type::MxVector3< double >
backward(*args) mx::type::MxVector3< double >
translation(*args) mx::type::MxVector3< double >
invertedRigid() mx::type::MxMatrix4< double >
transformVector(vector: MxVector3d) mx::type::MxVector3< double >
transformPoint(vector: MxVector3d) mx::type::MxVector3< double >
__neg__() mx::type::MxMatrix4< double >
__iadd__(other: MxMatrix4d) mx::type::MxMatrix4< double > &
__add__(other: MxMatrix4d) mx::type::MxMatrix4< double >
__isub__(other: MxMatrix4d) mx::type::MxMatrix4< double > &
__sub__(other: MxMatrix4d) mx::type::MxMatrix4< double >
__imul__(number: double) mx::type::MxMatrix4< double > &
__itruediv__(*args)
__truediv__(*args)
flippedCols() mx::type::MxMatrix4< double >
flippedRows() mx::type::MxMatrix4< double >
row(row: std::size_t) mx::type::MxVector4< double >
__mul__(*args) mx::type::MxVector4< double >
transposed() mx::type::MxMatrix4< double >
diagonal() mx::type::MxVector4< double >
inverted() mx::type::MxMatrix4< double >
invertedOrthogonal() mx::type::MxMatrix4< double >
__len__() int
__getitem__(index: int)
__setitem__(index: int, val)
as_lists() list

convert to a list of python lists

__str__() str

Return str(self).

class mechanica.MxMatrix4f(*args)

A 4x4 square matrix with float elements

static rotationX(angle: float) mx::type::MxMatrix4< float >
static rotationY(angle: float) mx::type::MxMatrix4< float >
static rotationZ(angle: float) mx::type::MxMatrix4< float >
static reflection(normal: MxVector3f) mx::type::MxMatrix4< float >
static shearingXY(amountX: float, amountY: float) mx::type::MxMatrix4< float >
static shearingXZ(amountX: float, amountZ: float) mx::type::MxMatrix4< float >
static shearingYZ(amountY: float, amountZ: float) mx::type::MxMatrix4< float >
static orthographicProjection(size: MxVector2f, near: float, far: float) mx::type::MxMatrix4< float >
static perspectiveProjection(*args) mx::type::MxMatrix4< float >
static lookAt(eye: MxVector3f, target: MxVector3f, up: MxVector3f) mx::type::MxMatrix4< float >
isRigidTransformation() bool
rotationScaling() mx::type::MxMatrix3< float >
rotationShear() mx::type::MxMatrix3< float >
rotation(*args) mx::type::MxMatrix3< float >
rotationNormalized() mx::type::MxMatrix3< float >
scalingSquared() mx::type::MxVector3< float >
scaling(*args) mx::type::MxVector3< float >
uniformScalingSquared() float
uniformScaling() float
normalMatrix() mx::type::MxMatrix3< float >
right(*args) mx::type::MxVector3< float >
up(*args) mx::type::MxVector3< float >
backward(*args) mx::type::MxVector3< float >
translation(*args) mx::type::MxVector3< float >
invertedRigid() mx::type::MxMatrix4< float >
transformVector(vector: MxVector3f) mx::type::MxVector3< float >
transformPoint(vector: MxVector3f) mx::type::MxVector3< float >
__neg__() mx::type::MxMatrix4< float >
__iadd__(other: MxMatrix4f) mx::type::MxMatrix4< float > &
__add__(other: MxMatrix4f) mx::type::MxMatrix4< float >
__isub__(other: MxMatrix4f) mx::type::MxMatrix4< float > &
__sub__(other: MxMatrix4f) mx::type::MxMatrix4< float >
__imul__(number: float) mx::type::MxMatrix4< float > &
__itruediv__(*args)
__truediv__(*args)
flippedCols() mx::type::MxMatrix4< float >
flippedRows() mx::type::MxMatrix4< float >
row(row: std::size_t) mx::type::MxVector4< float >
__mul__(*args) mx::type::MxVector4< float >
transposed() mx::type::MxMatrix4< float >
diagonal() mx::type::MxVector4< float >
inverted() mx::type::MxMatrix4< float >
invertedOrthogonal() mx::type::MxMatrix4< float >
__len__() int
__getitem__(index: int)
__setitem__(index: int, val)
as_lists() list

convert to a list of python lists

__str__() str

Return str(self).

class mechanica.MxQuaterniond(*args)

A quaternion with double elements

static rotation(angle: double, normalizedAxis: MxVector3d) mx::type::MxQuaternion< double >
static fromMatrix(matrix: MxMatrix3d) mx::type::MxQuaternion< double >
data(*args) double const *
__eq__(other: MxQuaterniond) bool

Return self==value.

__ne__(other: MxQuaterniond) bool

Return self!=value.

isNormalized() bool
vector() mx::type::MxVector3< double > const
scalar() double
angle(*args) double
axis() mx::type::MxVector3< double >
toMatrix() mx::type::MxMatrix3< double >
toEuler() mx::type::MxVector3< double >
__neg__() mx::type::MxQuaternion< double >
__iadd__(other: MxQuaterniond) mx::type::MxQuaternion< double > &
__add__(other: MxQuaterniond) mx::type::MxQuaternion< double >
__isub__(other: MxQuaterniond) mx::type::MxQuaternion< double > &
__sub__(other: MxQuaterniond) mx::type::MxQuaternion< double >
__imul__(scalar: double) mx::type::MxQuaternion< double > &
__itruediv__(*args)
__truediv__(*args)
__mul__(*args) mx::type::MxQuaternion< double >
dot() double
length() double
normalized() mx::type::MxQuaternion< double >
conjugated() mx::type::MxQuaternion< double >
inverted() mx::type::MxQuaternion< double >
invertedNormalized() mx::type::MxQuaternion< double >
transformVector(vector: MxVector3d) mx::type::MxVector3< double >
transformVectorNormalized(vector: MxVector3d) mx::type::MxVector3< double >
__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

class mechanica.MxQuaternionf(*args)

A quaternion with float elements

static rotation(angle: float, normalizedAxis: MxVector3f) mx::type::MxQuaternion< float >
static fromMatrix(matrix: MxMatrix3f) mx::type::MxQuaternion< float >
data(*args) float const *
__eq__(other: MxQuaternionf) bool

Return self==value.

__ne__(other: MxQuaternionf) bool

Return self!=value.

isNormalized() bool
vector() mx::type::MxVector3< float > const
scalar() float
angle(*args) float
axis() mx::type::MxVector3< float >
toMatrix() mx::type::MxMatrix3< float >
toEuler() mx::type::MxVector3< float >
__neg__() mx::type::MxQuaternion< float >
__iadd__(other: MxQuaternionf) mx::type::MxQuaternion< float > &
__add__(other: MxQuaternionf) mx::type::MxQuaternion< float >
__isub__(other: MxQuaternionf) mx::type::MxQuaternion< float > &
__sub__(other: MxQuaternionf) mx::type::MxQuaternion< float >
__imul__(scalar: float) mx::type::MxQuaternion< float > &
__itruediv__(*args)
__truediv__(*args)
__mul__(*args) mx::type::MxQuaternion< float >
dot() float
length() float
normalized() mx::type::MxQuaternion< float >
conjugated() mx::type::MxQuaternion< float >
inverted() mx::type::MxQuaternion< float >
invertedNormalized() mx::type::MxQuaternion< float >
transformVector(vector: MxVector3f) mx::type::MxVector3< float >
transformVectorNormalized(vector: MxVector3f) mx::type::MxVector3< float >
__getitem__(index: int)
__setitem__(index: int, val)
as_list() list

convert to a python list

__str__() str

Return str(self).

File I/O

mechanica.io

alias of MxIO

class mechanica.MxIO

Mechanica import/export interface

static fromFile3DF(filePath: std::string const &) Mx3DFStructure *

Load a 3D format file

Parameters

filePath (string) – path of file

Return type

Mx3DFStructure

Returns

Mx3DFStructure* 3D format data container

static toFile3DF(format: std::string const &, filePath: std::string const &, pRefinements: unsigned int const & = 0) HRESULT

Export engine state to a 3D format file

Parameters
  • format (string) – format of file

  • filePath (string) – path of file

  • pRefinements (int) – mesh refinements applied when generating meshes

Return type

int

Returns

HRESULT

static toFile(saveFilePath: std::string const &) HRESULT

Save a simulation to file

Parameters

saveFilePath (string) – absolute path to file

Return type

int

Returns

HRESULT

static toString() std::string

Return a simulation state as a JSON string

Return type

string

Returns

std::string

static mapImportParticleId(pId: unsigned int const &) int

Get the id of a particle according to import data that corresponds to a particle id of current data.

Only valid between initialization and the first simulation step, after which the import summary data is purged.

Parameters

pId (int) – id of particle in exported data

Return type

int

Returns

int >=0 if particle is found; -1 otherwise

static mapImportParticleTypeId(pId: unsigned int const &) int

Get the id of a particle type according to import data that corresponds to a particle type id of current data.

Only valid between initialization and the first simulation step, after which the import summary data is purged.

Parameters

pId (int) – id of particle type in exported data

Return type

int

Returns

int >=0 if particle type is found; -1 otherwise

class mechanica.Mx3DFRenderData
property color
mechanica.Structure3DF

alias of Mx3DFStructure

class mechanica.Mx3DFStructure

Container for relevant data found in a 3D data file.

The structure object owns all constituent data.

Recursively adds/removes constituent data and all child data. However, the structure enforces no rules on the constituent container data. For example, when an edge is added, all constituent vertices are added. However, no assignment is made to ensure that the parent edge is properly stored in the parent container of the vertices, neither are parent edges added when a vertex is added.

property centroid: MxVector3f

Centroid of all constituent data

property vertices: vectorMx3DFVertexData_p

Constituent vertices

property edges: vectorMx3DFEdgeData_p

Constituent edges

property faces: vectorMx3DFFaceData_p

Constituent faces

property meshes: vectorMx3DFMeshData_p

Constituent meshes

property num_vertices: int

Number of constituent vertices

property num_edges: int

Number of constituent edges

property num_faces: int

Number of constituent faces

property num_meshes: int

Number of constituent meshes

property vRadiusDef

Default radius applied to vertices when generating meshes from point clouds

fromFile(filePath: std::string const &) HRESULT

Load from file

Parameters

filePath (string) – file absolute path

Return type

int

Returns

HRESULT

toFile(format: std::string const &, filePath: std::string const &) HRESULT

Write to file

Parameters
  • format (string) – output format of file

  • filePath (string) – file absolute path

Return type

int

Returns

HRESULT

flush() HRESULT

Flush stucture. All scheduled processes are executed.

extend(s: Mx3DFStructure) HRESULT

Extend a structure

Parameters

s (Mx3DFStructure) – stucture to extend with

clear() HRESULT

Clear all data of the structure

Return type

int

Returns

HRESULT

has(*args) bool

Overload 1:

Test whether a vertex is a constituent

Parameters

v (Mx3DFVertexData) – vertex to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether an edge is a constituent

Parameters

e (Mx3DFEdgeData) – edge to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 3:

Test whether a face is a constituent

Parameters

f (Mx3DFFaceData) – face to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 4:

Test whether a mesh is a constituent

Parameters

m (Mx3DFMeshData) – mesh to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

add(*args) void

Overload 1:

Add a vertex

Parameters

v (Mx3DFVertexData) – vertex to add


Overload 2:

Add an edge and all constituent data

Parameters

e (Mx3DFEdgeData) – edge to add


Overload 3:

Add a face and all constituent data

Parameters

f (Mx3DFFaceData) – face to add


Overload 4:

Add a mesh and all constituent data

Parameters

m (Mx3DFMeshData) – mesh to add

remove(*args) void

Overload 1:

Remove a vertex

Parameters

v (Mx3DFVertexData) – vertex to remove


Overload 2:

Remove a edge and all constituent data

Parameters

e (Mx3DFEdgeData) – edge to remove


Overload 3:

Remove a face and all constituent data

Parameters

f (Mx3DFFaceData) – face to remove


Overload 4:

Remove a mesh and all constituent data

Parameters

m (Mx3DFMeshData) – mesh to remove

translate(displacement: MxVector3f) HRESULT

Translate the structure by a displacement

Parameters

displacement (MxVector3f) –

Return type

int

Returns

HRESULT

translateTo(position: MxVector3f) HRESULT

Translate the structure to a position

Parameters

position (MxVector3f) –

Return type

int

Returns

HRESULT

rotateAt(rotMat: MxMatrix3f, rotPt: MxVector3f) HRESULT

Rotate the structure about a point

Parameters
Return type

int

Returns

HRESULT

rotate(rotMat: MxMatrix3f) HRESULT

Rotate the structure about its centroid

Parameters

rotMat (MxMatrix3f) –

Return type

int

Returns

HRESULT

scaleFrom(*args) HRESULT

Overload 1:

Scale the structure about a point

Parameters
Return type

int

Returns

HRESULT


Overload 2:

Scale the structure uniformly about a point

Parameters
Return type

int

Returns

HRESULT

scale(*args) HRESULT

Overload 1:

Scale the structure about its centroid

Parameters

scales (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Scale the structure uniformly about its centroid

Parameters

scale (float) –

Return type

int

Returns

HRESULT

mechanica.Mesh3DFData

alias of Mx3DFMeshData

class mechanica.Mx3DFMeshData

3D data file mesh data

property structure

Parent structure

property id

ID, if any. Unique to its structure and type

property name

Mesh name

property renderData

Rendering data

property vertices: vectorMx3DFVertexData_p

Constituent vertices

property edges: vectorMx3DFEdgeData_p

Constituent edges

property faces: vectorMx3DFFaceData_p

Constituent faces

property num_vertices: int

Number of constituent vertices

property num_edges: int

Number of constituent edges

property num_faces: int

Number of constituent faces

property centroid: MxVector3f

Centroid of all constituent data

has(*args) bool

Overload 1:

Test whether a vertex is a constituent

Parameters

v (Mx3DFVertexData) – vertex to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether an edge is a constituent

Parameters

e (Mx3DFEdgeData) – edge to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 3:

Test whether a face is a constituent

Parameters

f (Mx3DFFaceData) – face to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

_in(s: Mx3DFStructure) bool

Test whether in a structure

Parameters

s (Mx3DFStructure) – structure to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

is_in(*args, **kwargs) bool

Alias of :meth:_in

translate(displacement: MxVector3f) HRESULT

Translate the mesh by a displacement

Parameters

displacement (MxVector3f) –

Return type

int

Returns

HRESULT

translateTo(position: MxVector3f) HRESULT

Translate the mesh to a position

Parameters

position (MxVector3f) –

Return type

int

Returns

HRESULT

rotateAt(rotMat: MxMatrix3f, rotPt: MxVector3f) HRESULT

Rotate the mesh about a point

Parameters
Return type

int

Returns

HRESULT

rotate(rotMat: MxMatrix3f) HRESULT

Rotate the mesh about its centroid

Parameters

rotMat (MxMatrix3f) –

Return type

int

Returns

HRESULT

scaleFrom(*args) HRESULT

Overload 1:

Scale the mesh about a point

Parameters
Return type

int

Returns

HRESULT


Overload 2:

Scale the mesh uniformly about a point

Parameters
Return type

int

Returns

HRESULT

scale(*args) HRESULT

Overload 1:

Scale the mesh about its centroid

Parameters

scales (MxVector3f) –

Return type

int

Returns

HRESULT


Overload 2:

Scale the mesh uniformly about its centroid

Parameters

scale (float) –

Return type

int

Returns

HRESULT

mechanica.Face3DFData

alias of Mx3DFFaceData

class mechanica.Mx3DFFaceData

3D data file face data

property structure

Parent structure

property normal

Face normal

property id

ID, if any. Unique to its structure and type

property vertices: vectorMx3DFVertexData_p

Constituent vertices

property edges: vectorMx3DFEdgeData_p

Constituent edges

property meshes: vectorMx3DFMeshData_p

Parent meshes

property num_vertices: int

Number of constituent vertices

property num_edges: int

Number of constituent edges

property num_meshes: int

Number of parent meshes

has(*args) bool

Overload 1:

Test whether a vertex is a constituent

Parameters

v (Mx3DFVertexData) – vertex to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether an edge is a constituent

Parameters

e (Mx3DFEdgeData) – edge to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

_in(*args) bool

Overload 1:

Test whether in a mesh

Parameters

m (Mx3DFMeshData) – mesh to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether in a structure

Parameters

s (Mx3DFStructure) – structure to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

is_in(*args, **kwargs) bool

Alias of :meth:_in

mechanica.Edge3DFData

alias of Mx3DFEdgeData

class mechanica.Mx3DFEdgeData(_va: Mx3DFVertexData, _vb: Mx3DFVertexData)

3D data file edge data

property structure

Parent structure

property id

ID, if any. Unique to its structure and type

property vertices: vectorMx3DFVertexData_p

Constituent vertices

property faces: vectorMx3DFFaceData_p

Constituent faces

property meshes: vectorMx3DFMeshData_p

Parent meshes

property num_vertices: int

Number of constituent vertices

property num_faces: int

Number of parent faces

property num_meshes: int

Number of parent meshes

has(v: Mx3DFVertexData) bool

Test whether a vertex is a constituent

Parameters

v (Mx3DFVertexData) – vertex to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

_in(*args) bool

Overload 1:

Test whether in a face

Parameters

f (Mx3DFFaceData) – face to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether in a mesh

Parameters

m (Mx3DFMeshData) – mesh to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 3:

Test whether in a structure

Parameters

s (Mx3DFStructure) – structure to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

is_in(*args, **kwargs) bool

Alias of :meth:_in

mechanica.Vertex3DFData

alias of Mx3DFVertexData

class mechanica.Mx3DFVertexData(_position: MxVector3f, _structure: Optional[Mx3DFStructure] = None)

3D data file vertex data

property structure

Parent structure

property position

Global position

property id

ID, if any. Unique to its structure and type

property edges: vectorMx3DFEdgeData_p

Parent edges

property faces: vectorMx3DFFaceData_p

Parent faces

property meshes: vectorMx3DFMeshData_p

Parent meshes

property num_edges: int

Number of parent edges

property num_faces: int

Number of parent faces

property num_meshes: int

Number of parent meshes

_in(*args) bool

Overload 1:

Test whether in an edge

Parameters

e (Mx3DFEdgeData) – edge to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 2:

Test whether in a face

Parameters

f (Mx3DFFaceData) – face to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 3:

Test whether in a mesh

Parameters

m (Mx3DFMeshData) – mesh to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false


Overload 4:

Test whether in a structure

Parameters

s (Mx3DFStructure) – structure to test

Return type

boolean

Returns

true

Return type

boolean

Returns

false

is_in(*args, **kwargs) bool

Alias of :meth:_in

GPU-Accelerated Modules

Note

This section of the Mechanica API is only available in CUDA-supported installations.