Model¶
Model¶
This is the main class that is used to assemble all simulation input and configuration. It also provides methods to do initialization, run simulation, and introspect the running simulation.
Example: 1400_rel_site_for_each_it/model.py
Attributes:¶
config: Config¶
Simulation configuration.- default argument value in constructor: Config()
warnings: Warnings¶
Configuration on how to report warnings.- default argument value in constructor: Warnings()
notifications: Notifications¶
Configuration on how to report certain notifications.- default argument value in constructor: Notifications()
species: List[Species]¶
List of species to be included in the model for initialization.Used usually only for simple species (species that are defined using asingle molecule type without components such as ‘A’).Other species may be created inside simulation- default argument value in constructor: None
reaction_rules: List[ReactionRule]¶
- default argument value in constructor: None
surface_classes: List[SurfaceClass]¶
- default argument value in constructor: None
elementary_molecule_types: List[ElementaryMoleculeType]¶
Contains list of elementary molecule types with their diffusion constants and other information.Populated when a BNGL file is loaded and also on initialization from Species objects present inthe species list.- default argument value in constructor: None
release_sites: List[ReleaseSite]¶
List of release sites to be included in the model.- default argument value in constructor: None
geometry_objects: List[GeometryObject]¶
List of geometry objects to be included in the model.- default argument value in constructor: None
checkpointed_molecules: List[BaseChkptMol]¶
Used when resuming simulation from a checkpoint.- default argument value in constructor: None
viz_outputs: List[VizOutput]¶
List of visualization outputs to be included in the model.There is usually just one VizOutput object.- default argument value in constructor: None
counts: List[Count]¶
List of counts to be included in the model.- default argument value in constructor: None
Methods:¶
initialize (print_copyright: bool=True)¶
Initializes model, initialization blocks most of changes tocontained components.
- print_copyright: bool = TruePrints information about MCell.
run_iterations (iterations: float) -> int¶
Runs specified number of iterations. Returns the number of iterationsexecuted (it might be less than the requested number of iterations whena checkpoint was scheduled).
- iterations: floatNumber of iterations to run. Value is truncated to an integer.
end_simulation (print_final_report: bool=True)¶
Generates the last visualization and reaction output (if they are includedin the model), then flushes all buffers and optionally prints simulation report.Buffers are also flushed when the Model object is destroyed such as when Ctrl-Cis pressed during simulation.
- print_final_report: bool = TruePrint information on simulation time and counts of selected events.
add_subsystem (subsystem: Subsystem)¶
Adds all components of a Subsystem object to the model.
- subsystem: Subsystem
add_instantiation (instantiation: Instantiation)¶
Adds all components of an Instantiation object to the model.
- instantiation: Instantiation
add_observables (observables: Observables)¶
Adds all counts and viz outputs of an Observables object to the model.
- observables: Observables
dump_internal_state (with_geometry: bool=False)¶
Prints out the simulation engine’s internal state, mainly for debugging.
- with_geometry: bool = FalseInclude geometry in the dump.
export_data_model (file: str=None)¶
Exports the current state of the model into a data model JSON format.Does not export state of molecules.Must be called after model initialization.Always exports the current state, i.e. with the current geometry and reaction rates.Events (ReleaseSites and VizOutputs) with scheduled time other than zero are not exported correctly yet.
- file: str = NoneIf file is not set, then uses the first VizOutput to determine the target directoryand creates name using the current iteration. Fails if argument file is not set andthere is no VizOutput in the model.
export_viz_data_model (file: str=None)¶
Same as export_data_model, only the created data model will contain only information required for visualizationin CellBlender. This makes the loading of the model by CellBlender faster and also allows to avoid potentialcompatibility issues.Must be called after model initialization.
- file: str = NoneOptional path to the output data model file.Example: 1520_sphere_collision/model.py
export_geometry (output_files_prefix: str=None)¶
Exports model geometry as Wavefront OBJ format.Must be called after model initialization.Does not export material colors (yet).
- output_files_prefix: str = NoneOptional prefix for .obj and .mtl files that will be created on export.If output_files_prefix is not set, then uses the first VizOutput to determine the target directoryand creates names using the current iteration. Fails if argument output_files_prefix is not set andthere is no VizOutput in the model.
release_molecules (release_site: ReleaseSite)¶
Performs immediate release of molecules based on the definition of the release site argument.The ReleaseSite.release_time must not be in the past and must be within the current iterationmeaning that the time must be greater or equal iteration * time_step and less than (iteration + 1) * time_step.The ReleaseEvent must not use a release_pattern because this is an immediate release and it is notscheduled into the global scheduler.
- release_site: ReleaseSiteExample: 2300_immediate_release/model.py
run_reaction (reaction_rule: ReactionRule, reactant_ids: List[int], time: float) -> List[int]¶
Run a single reaction on reactants. Callbacks will be called if they are registered for the given reaction.Returns a list of product IDs.Note: only unimolecular reactions are currently supported.
- reaction_rule: ReactionRuleReaction rule to run.
- reactant_ids: List[int]The number of reactants for a unimolecular reaction must be 1 and for a bimolecular reaction must be 2.Reactants for a bimolecular reaction do not have to be listed in the same order as in the reaction rule definition.
- time: floatPrecise time in seconds when this reaction occurs. Important to know for how long the productswill be diffused when they are created in a middle of a time step.
add_vertex_move (object: GeometryObject, vertex_index: int, displacement: List[float])¶
Appends information about a displacement for given object’s vertex into an internal list of vertex moves.To do the actual geometry change, call Model.apply_vertex_moves.The reason why we first need to collect all changes and then apply them all at the same time is for performancereasons.
- object: GeometryObjectObject whose vertex will be changed.
- vertex_index: intIndex of vertex in object’s vertex list that will be changed.
- displacement: List[float]Change of vertex coordinates [x, y, z] (in um) that will be added to the currentcoordinates of the vertex.
apply_vertex_moves (collect_wall_wall_hits: bool=False, randomize_order: bool=True) -> List[WallWallHitInfo]¶
Applies all the vertex moves specified with Model.add_vertex_move call.All affected vertices are first divided based on to which geometery object they belong.Then each object is manipulated one by one.During vertex moves, collisions are checked:a) When a moved vertex hits a wall of another object, it is stopped at the wall.b) When a second object’s vertex would end up inside the moved object, the vertex movethat would cause it is canceled (its displacement set to 0) because finding the maximumdistance we can move is too computationally expensive. To minimize the impact of thiscancellation, the vertices should be moved only by a small distance.Applying vertex moves also takes paired molecules into account:When moves are applied to an object, all moved molecules that are paired are collected.For each of the paired molecules, we collect displacements for eachof the vertices of the ‘primary’ wall where this molecule is located (that were provided by the userthrough add_vertex_move, and were possibly truncated due to collisions).Then we find the second wall where the second molecule of the pair is located.For each of the vertices of all ‘secondary’ walls, we collect a list of displacementsthat move the vertices of ‘primary’ walls.Then, an average displacement is computed for each vertex, and these average displacementsare used to move the ‘secondary’ walls.When a ‘primary’ wall collides, its displacement is clamped or canceled. This is true even ifit collides with a ‘secondary’ wall that would be otherwise moved. So, the displacement of the‘primary’ wall will mostly just pull the ‘secondary’ wall, not push. Therefore it is neededthat both objects are active and pull each other.This process is well commented in MCell code:partition.cpp in functionsapply_vertex_moves, apply_vertex_moves_per_object, and move_walls_with_paired_molecules.When argument collect_wall_wall_hits is True, a list of wall pairs that collided is returned,when collect_wall_wall_hits is False, an empty list is returned.
- collect_wall_wall_hits: bool = FalseWhen set to True, a list of wall pairs that collided is returned,otherwise an empty list is returned.
- randomize_order: bool = TrueWhen set to True (default), the ordering of the vertex move list created by add_vertex_movecalls is randomized. This allows to avoid any bias in the resulting positions of surfacemolecules.However, the individual vertex moves are then sorted by the object to which the vertex belongsand the moves are applied object by object for correctness. Setting this to True also radomizes theorder of objects to which the vertex moves are applied.
pair_molecules (id1: int, id2: int)¶
Sets that two surface molecules are paired. Paired molecules bind walls togetherand when one wall is moved, the wall that is bound through a paired molecule is moved as well.Throws exception if the molecule ids are not surface molecules.Throws exception if the molecules are on the same object.Throws exception if any of the molecules is already paired.May be called only after model initialization.
- id1: int
- id2: int
unpair_molecules (id1: int, id2: int)¶
Sets that two surface molecules are not paired.Throws exception if the molecule ids are not surface molecules.Throws exception if the molecules are not paired together.May be called only after model initialization.
- id1: int
- id2: intExample: 2900_pair_unpair_molecules/model.py
get_paired_molecule (id: int) -> int¶
Return id of the molecule to which the molecule with ‘id’ is paired.Returns ID_INVALID (-1) when the molecule is not paired.May be called only after model initialization.
- id: intExample: 2900_pair_unpair_molecules/model.py
get_paired_molecules () -> Dict[uint32, uint32]¶
Returns a dictionary that contains all molecules that are paired.Molecule ids are keys and the value associated with the key is the second paired molecule.The returned dictionary is a copy and any changes made to it are ignored by MCell.Note: The reason why uint32 is used as the base type for the dictionary but type int is usedeverywhere else for molecule ids is only for performance reasons.Example: 3170_get_paired_molecules/model.py
load_bngl (file_name: str, observables_path_or_file: str=None, default_release_region: Region=None, parameter_overrides: Dict[str, float]=None, observables_output_format: CountOutputFormat=CountOutputFormat.AUTOMATIC_FROM_EXTENSION)¶
Loads sections: molecule types, reaction rules, seed species, and observables from a BNGL fileand creates objects in the current model according to it.All elementary molecule types used in the seed species section must be defined in subsystem.If an item in the seed species section does not have its compartment set,the argument default_region must be set and the molecules are released into or onto thedefault_region.
- file_name: strPath to the BNGL file to be loaded.
- observables_path_or_file: str = NoneDirectory prefix or file name where observable values will be stored.If a directory such as ‘./react_data/seed_’ + str(SEED).zfill(5) + ‘/’ or an emptystring/unset is used, each observable gets its own file and the output file format for created Countobjects is CountOutputFormat.DAT.When not set, this path is used: ‘./react_data/seed_’ + str(model.config.seed).zfill(5) + ‘/’.If a file has a .gdat extension such as‘./react_data/seed_’ + str(SEED).zfill(5) + ‘/counts.gdat’, all observable are stored in thisfile and the output file format for created Count objects is CountOutputFormat.GDAT.Must not be empty when observables_output_format is explicitly set to CountOutputFormat.GDAT.
- default_release_region: Region = NoneUsed as region for releases for seed species that have no compartments specified.
- parameter_overrides: Dict[str, float] = NoneFor each key k in the parameter_overrides, if it is defined in the BNGL’s parameters section,its value is ignored and instead value parameter_overrides[k] is used.
- observables_output_format: CountOutputFormat = CountOutputFormat.AUTOMATIC_FROM_EXTENSIONSelection of output format. Default setting uses automatic detectionbased on contents of the ‘observables_path_or_file’ attribute.Example: 1400_rel_site_for_each_it/model.py
export_to_bngl (file_name: str, simulation_method: BNGSimulationMethod=BNGSimulationMethod.ODE)¶
Exports all defined species, reaction rules and applicable observablesas a BNGL file that can be then loaded by MCell4 or BioNetGen.The resulting file should be validated that it produces expected results.Many MCell features cannot be exported into BNGL and when such a feature isencountered the export fails with a RuntimeError exception.However, the export code tries to export as much as possible and one can catchthe RuntimeError exception and use the possibly incomplete BNGL file anyway.
- file_name: strOutput file name.
- simulation_method: BNGSimulationMethod = BNGSimulationMethod.ODESelection of the BioNetGen simulation method.Selects BioNetGen action to run with the selected simulation method.For BNGSimulationMethod.NF the export is limited to a single volume anda single surface and the enerated rates use volume and surface area so thatsimulation with NFSim produces corect results.
save_checkpoint (custom_dir: str=None)¶
Saves current model state as checkpoint.The default directory structure is checkpoints/seed_<SEED>/it_<ITERATION>,it can be changed by setting ‘custom_dir’.If used during an iteration such as in a callback, an event is scheduled for thebeginning of the next iteration. This scheduled event saves the checkpoint.
- custom_dir: str = NoneSets custom directory where the checkpoint will be stored.The default is ‘checkpoints/seed_<SEED>/it_<ITERATION>’.
schedule_checkpoint (iteration: int=0, continue_simulation: bool=False, custom_dir: str=None)¶
Schedules checkpoint save event that will occur when an iteration is started.This means that it will be executed right before any other events scheduled forthe given iteration are executed.Can be called asynchronously at any time after initialization.
- iteration: int = 0Specifies iteration number when the checkpoint save will occur.Please note that iterations are counted from 0.To schedule a checkpoint for the closest time as possible, keep the default value 0,this will schedule checkpoint for the beginning of the iteration with number current iteration + 1.If calling schedule_checkpoint from a different thread (e.g. by using threading.Timer),it is highly recommended to keep the default value 0 or choose some time that will befor sure in the future.
- continue_simulation: bool = FalseWhen false, saving the checkpoint means that we want to terminate the simulationright after the save. The currently running function Model.run_iterationswill not simulate any following iterations and execution will return from this functionto execute the next statement which is usually ‘model.end_simulation()’.When true, the checkpoint is saved and simulation continues uninterrupted.
- custom_dir: str = NoneSets custom directory where the checkpoint will be stored.The default is ‘checkpoints/seed_<SEED>/it_<ITERATION>’.
find_species (name: str) -> Species¶
Find a Species object using name in the species list.Returns None if no such species is found.
- name: str
add_reaction_rule (r: ReactionRule)¶
Add a reference to a ReactionRule object to the reaction_rules list.
- r: ReactionRule
find_reaction_rule (name: str) -> ReactionRule¶
Find a ReactionRule object using name in the reaction_rules list.Returns None if no such reaction rule is found.
- name: str
add_surface_class (sc: SurfaceClass)¶
Add a reference to a SurfaceClass object to the surface_classes list.
- sc: SurfaceClass
find_surface_class (name: str) -> SurfaceClass¶
Find a SurfaceClass object using name in the surface_classes list.Returns None if no such surface class is found.
- name: str
add_elementary_molecule_type (mt: ElementaryMoleculeType)¶
Add a reference to an ElementaryMoleculeType object to the elementary_molecule_types list.
- mt: ElementaryMoleculeType
find_elementary_molecule_type (name: str) -> ElementaryMoleculeType¶
Find an ElementaryMoleculeType object using name in the elementary_molecule_types list.Returns None if no such elementary molecule type is found.
- name: str
load_bngl_molecule_types_and_reaction_rules (file_name: str, parameter_overrides: Dict[str, float]=None)¶
Parses a BNGL file, only reads molecule types and reaction rules sections,i.e. ignores observables and seed species.Parameter values are evaluated and the result value is directly used.Compartments names are stored in rxn rules as strings because compartments belongto geometry objects and the subsystem is independent on specific geometry.However, the compartments and their objects must be defined before initialization.
- file_name: strPath to the BNGL file to be loaded.
- parameter_overrides: Dict[str, float] = NoneFor each key k in the parameter_overrides, if it is defined in the BNGL’s parameters section,its value is ignored and instead value parameter_overrides[k] is used.Example: 2100_gradual_bngl_load/model.py
add_release_site (s: ReleaseSite)¶
Adds a reference to the release site s to the list of release sites.
- s: ReleaseSite
find_release_site (name: str) -> ReleaseSite¶
Finds a release site by its name, returns None if no such release site is present.
- name: str
add_geometry_object (o: GeometryObject)¶
Adds a reference to the geometry object o to the list of geometry objects.
- o: GeometryObject
find_geometry_object (name: str) -> GeometryObject¶
Finds a geometry object by its name, returns None if no such geometry object is present.
- name: str
find_volume_compartment_object (name: str) -> GeometryObject¶
Finds a geometry object by its name, the geometry object must be a BNGL compartment.Returns None if no such geometry object is present.
- name: str
find_surface_compartment_object (name: str) -> GeometryObject¶
Finds a geometry object that is a BNGL compartment and its surface name is name.Returns None if no such geometry object is present.
- name: str
load_bngl_compartments_and_seed_species (file_name: str, default_release_region: Region=None, parameter_overrides: Dict[str, float]=None)¶
First loads section compartments and for each 3D compartment that does notalready exist as a geometry object in this Instantiation object, creates abox with compartment’s volume and also sets its 2D (membrane) compartment name.When multiple identical geometry objects are added to the final Model object,only one copy is left so one can merge multiple Instantiation objects that createdcompartments assuming that their volume is the same.Then loads section seed species from a BNGL file and creates release sites according to it.All elementary molecule types used in the seed species section must be already defined in subsystem.If an item in the BNGL seed species section does not have its compartment set,the argument default_region must be set and the molecules are then released into or onto thedefault_region.
- file_name: strPath to the BNGL file.
- default_release_region: Region = NoneUsed as region for releases for seed species that have no compartments specified.
- parameter_overrides: Dict[str, float] = NoneFor each key k in the parameter_overrides, if it is defined in the BNGL’s parameters section,its value is ignored and instead value parameter_overrides[k] is used.Example: 2100_gradual_bngl_load/model.py
add_viz_output (viz_output: VizOutput)¶
Adds a reference to the viz_output object to the list of visualization output specifications.
- viz_output: VizOutput
add_count (count: Count)¶
Adds a reference to the count object to the list of count specifications.
- count: Count
find_count (name: str) -> Count¶
Finds a count object by its name, returns None if no such count is present.
- name: str
load_bngl_observables (file_name: str, observables_path_or_file: str=None, parameter_overrides: Dict[str, float]=None, observables_output_format: CountOutputFormat=CountOutputFormat.AUTOMATIC_FROM_EXTENSION)¶
Loads section observables from a BNGL file and creates Count objects according to it.All elementary molecule types used in the seed species section must be defined in subsystem.
- file_name: strPath to the BNGL file.
- observables_path_or_file: str = NoneDirectory prefix or file name where observable values will be stored.If a directory such as ‘./react_data/seed_’ + str(SEED).zfill(5) + ‘/’ or an emptystring/unset is used, each observable gets its own file and the output file format for created Countobjects is CountOutputFormat.DAT.When not set, this path is used: ‘./react_data/seed_’ + str(model.config.seed).zfill(5) + ‘/’.If a file has a .gdat extension such as‘./react_data/seed_’ + str(SEED).zfill(5) + ‘/counts.gdat’, all observable are stored in thisfile and the output file format for created Count objects is CountOutputFormat.GDAT.Must not be empty when observables_output_format is explicitly set to CountOutputFormat.GDAT.
- parameter_overrides: Dict[str, float] = NoneFor each key k in the parameter_overrides, if it is defined in the BNGL’s parameters section,its value is ignored and instead value parameter_overrides[k] is used.
- observables_output_format: CountOutputFormat = CountOutputFormat.AUTOMATIC_FROM_EXTENSIONSelection of output format. Default setting uses automatic detectionbased on contents of the ‘observables_path_or_file’ attribute.Example: 2100_gradual_bngl_load/model.py
get_molecule_ids (pattern: Complex=None) -> List[int]¶
Returns a list of ids of molecules.If the arguments pattern is not set, the list of all molecule ids is returned.If the argument pattern is set, the list of all molecule ids whose species matchthe pattern is returned.
- pattern: Complex = NoneBNGL pattern to select molecules based on their species, might use compartments.
get_molecule (id: int) -> Molecule¶
Returns a information on a molecule from the simulated environment,None if the molecule does not exist.
- id: intUnique id of the molecule to be retrieved.Example: 1900_molecule_introspection/model.py
get_species_name (species_id: int) -> str¶
Returns a string representing canonical species name in the BNGL format.
- species_id: intId of the species.
get_vertex (object: GeometryObject, vertex_index: int) -> Vec3¶
Returns coordinates of a vertex.
- object: GeometryObject
- vertex_index: intThis is the index of the vertex in the geometry object’s walls (wall_list).Example: 1340_get_vertex/model.py
get_wall (object: GeometryObject, wall_index: int) -> Wall¶
Returns information about a wall belonging to a given object.
- object: GeometryObjectGeometry object whose wall to retrieve.
- wall_index: intThis is the index of the wall in the geometry object’s walls (wall_list).Example: 1330_get_wall/model.py
get_vertex_unit_normal (object: GeometryObject, vertex_index: int) -> Vec3¶
Returns sum of all wall normals that use this vertex converted to a unit vector oflength 1 um (micrometer).This represents the unit vector pointing outwards from the vertex.
- object: GeometryObjectGeometry object whose vertex to retrieve.
- vertex_index: intThis is the index of the vertex in the geometry object’s vertex_list.Example: 1320_get_vertex_unit_normal/model.py
get_wall_unit_normal (object: GeometryObject, wall_index: int) -> Vec3¶
Returns wall normal converted to a unit vector of length 1um.
- object: GeometryObjectGeometry object whose wall’s normal to retrieve.
- wall_index: intThis is the index of the vertex in the geometry object’s walls (wall_list).Example: 1310_get_wall_unit_normal/model.py
get_wall_color (object: GeometryObject, wall_index: int) -> Color¶
Returns color of a wall.
- object: GeometryObjectGeometry object whose wall’s color to retrieve.
- wall_index: intThis is the index of the vertex in the geometry object’s walls (wall_list).
set_wall_color (object: GeometryObject, wall_index: int, color: Color)¶
Sets color of a wall.
- object: GeometryObjectGeometry object whose wall’s color to retrieve.
- wall_index: intThis is the index of the vertex in the geometry object’s walls (wall_list).
- color: ColorColor to be set.