keyword stringclasses 7 values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29 values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14 values |
|---|---|---|---|---|---|---|---|
3D | mcellteam/mcell | include/dump_state.h | .h | 4,275 | 125 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef __DUMP_STATE_H__
#define __DUMP_STATE_H__
#include <iostream>
#include "mcell_structs.h"
#include "edge_util.h"
#include "grid_util.h"
#include "rng.h"
#define DUMP_EVERYTHING 0xFFFFFFFF
#ifdef _WIN64
typedef unsigned int uint;
#endif
void dump_volume(struct volume* s, const char* comment, unsigned int selected_details);
// the functions below are used to generate log that can be diffed with mcell4's log
void dump_collisions(struct collision* shead);
void dump_processing_reaction(
long long it,
struct vector3 *hitpt, double t,
struct rxn *rx, /*int path,*/
struct abstract_molecule *reacA,
struct abstract_molecule *reacB,
struct wall *w
);
void dump_rxn(rxn* rx, const char* ind, bool for_diff=false);
void dump_molecule_species(struct abstract_molecule *reac);
void dump_surface_molecule(
struct surface_molecule* amp,
const char* ind,
bool for_diff,
const char* extra_comment,
unsigned long long iteration,
double time,
bool print_position,
bool print_flags = false
);
void dump_volume_molecule(
struct volume_molecule* amp,
const char* ind,
bool for_diff,
const char* extra_comment,
unsigned long long iteration,
double time,
bool print_position,
bool print_flags = false
);
void dump_object_list(geom_object* obj, const char* name, const char* comment, const char* ind);
void dump_vector2(struct vector2 vec, const char* extra_comment);
void dump_vector3(struct vector3 vec, const char* extra_comment);
void dump_tile_neighbors_list(struct tile_neighbor *tile_nbr_head, const char* extra_comment, const char* ind);
void dump_wall(wall* w, const char* ind, bool for_diff = true);
void dump_edge(edge* e, const char* ind, bool for_diff = true);
void dump_schedule_helper(
struct schedule_helper* shp,
const char* name,
const char* comment,
const char* ind,
bool simplified_for_vm);
std::string get_species_flags_string(uint flags);
std::ostream & operator<<(std::ostream &out, const vector2 &a);
std::ostream & operator<<(std::ostream &out, const vector3 &a);
// for now keeping dumps shared among mcell3 and mcell4 in header,
// we do not want to increase the dependency of pymcell4 on mcell3
static void dump_poly_edge(int i, poly_edge* pep, bool dump_only_init = true) {
#if 0
if (!dump_only_init) {
std::cout << "next: \t\t" << pep->next << " [poly_edge*] \t\t /* Next edge in a hash table. */\n";
}
std::cout << "v1x: \t\t" << pep->v1x << " [double] \t\t /* X coord of starting point */\n";
std::cout << "v1y: \t\t" << pep->v1y << " [double] \t\t /* Y coord of starting point */\n";
std::cout << "v1z: \t\t" << pep->v1z << " [double] \t\t /* Z coord of starting point */\n";
std::cout << "v2x: \t\t" << pep->v2x << " [double] \t\t /* X coord of ending point */\n";
std::cout << "v2y: \t\t" << pep->v2y << " [double] \t\t /* Y coord of ending point */\n";
std::cout << "v2z: \t\t" << pep->v2z << " [double] \t\t /* Z coord of ending point */\n";
std::cout << "face[0]: \t\t" << pep->face[0] << " [int] \t\t /* wall indices on side of edge */\n";
if (!dump_only_init) {
std::cout << "face[1]: \t\t" << pep->face[1] << " [int] \t\t /* wall indices on side of edge */\n";
std::cout << "face[2]: \t\t" << pep->face[2] << " [int] \t\t /* wall indices on side of edge */\n";
}
std::cout << "edge[0]: \t\t" << pep->edge[0] << " [int] \t\t /* which edge of wall1/2 are we? */\n";
if (!dump_only_init) {
std::cout << "edge[1]: \t\t" << pep->edge[1] << " [int] \t\t /* which edge of wall1/2 are we? */\n";
std::cout << "edge[2]: \t\t" << pep->edge[2] << " [int] \t\t /* which edge of wall1/2 are we? */\n";
std::cout << "n: \t\t" << pep->n << " [int] \t\t /* How many walls share this edge? */\n";
}
#endif
}
#endif
| Unknown |
3D | mcellteam/mcell | include/datamodel_defines.h | .h | 21,796 | 524 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef _DATAMODEL_DEFINES_H_
#define _DATAMODEL_DEFINES_H_
// TODO: rename to data_model_...
#include <cctype>
#include <sstream>
#include <iomanip>
#include "defines.h"
#include "json/json.h"
const char* const DEFAULT_DATA_MODEL_FILENAME = "data_model.json";
const char* const DEFAULT_DATA_MODEL_VIZ_FILENAME = "data_model_viz.json";
const char* const DEFAULT_DATA_LAYOUT_FILENAME = "data_layout.json";
// ---------------------------------- datamodel constants----------------------------------
const char* const VER_DM_2017_11_18_0130 = "DM_2017_11_18_0130";
const char* const VER_DM_2017_06_23_1300 = "DM_2017_06_23_1300";
const char* const VER_DM_2018_01_11_1330 = "DM_2018_01_11_1330";
const char* const VER_DM_2018_10_16_1632 = "DM_2018_10_16_1632";
const char* const VER_DM_2014_10_24_1638 = "DM_2014_10_24_1638";
const char* const VER_DM_2015_04_13_1700 = "DM_2015_04_13_1700";
const char* const VER_DM_2015_11_08_1756 = "DM_2015_11_08_1756";
const char* const VER_DM_2016_03_15_1800 = "DM_2016_03_15_1800";
const char* const VER_DM_2017_11_30_1830 = "DM_2017_11_30_1830";
const char* const VER_DM_2020_07_12_1600 = "DM_2020_07_12_1600";
const int BLENDER_VERSION[] = {2, 79, 0};
const char* const KEY_ROOT = "root"; // not used, mainly for error reporting
// all keys should be defined as a constant string
const char* const KEY_MCELL = "mcell";
const char* const KEY_NAME = "name";
const char* const VALUE_NONE = "None";
const char* const VALUE_BLENDER = "blender";
const char* const VALUE_WORLD = "WORLD";
const char* const KEY_DATA_MODEL_VERSION = "data_model_version";
const char* const KEY_CELLBLENDER_VERSION = "cellblender_version";
const char* const VALUE_CELLBLENDER_VERSION = "0.1.54";
const char* const KEY_MODEL_LANGUAGE = "model_language";
const char* const VALUE_MCELL3 = "mcell3";
const char* const VALUE_MCELL4 = "mcell4";
const char* const KEY_USE_BNG_UNITS = "use_bng_units";
const char* const KEY_PARAMETER_SYSTEM = "parameter_system";
const char* const KEY_BLENDER_VERSION = "blender_version";
const char* const KEY_MODEL_PARAMETERS = "model_parameters";
const char* const KEY__EXTRAS = "_extras";
const char* const KEY_PAR_VALID = "par_valid";
const char* const KEY_PAR_ID_NAME = "par_id_name";
const char* const KEY_PAR_VALUE = "par_value";
const char* const KEY_PAR_DESCRIPTION = "par_description";
const char* const KEY_PAR_EXPRESSION = "par_expression";
const char* const KEY_PAR_NAME = "par_name";
const char* const KEY_PAR_UNITS = "par_units";
const char* const KEY_GEOMETRICAL_OBJECTS = "geometrical_objects";
const char* const KEY_OBJECT_LIST = "object_list";
const char* const KEY_LOCATION = "location";
const char* const KEY_ELEMENT_CONNECTIONS = "element_connections";
const char* const KEY_VERTEX_LIST = "vertex_list";
const char* const KEY_DEFINE_SURFACE_REGIONS = "define_surface_regions";
const char* const KEY_INCLUDE_ELEMENTS = "include_elements";
const char* const KEY_ELEMENT_MATERIAL_INDICES = "element_material_indices";
const char* const KEY_REACTION_LIST = "reaction_list";
const char* const KEY_DEFINE_REACTIONS = "define_reactions";
const char* const KEY_RXN_NAME = "rxn_name";
const char* const KEY_RXN_TYPE = "rxn_type";
const char* const VALUE_REVERSIBLE = "reversible";
const char* const VALUE_IRREVERSIBLE = "irreversible";
const char* const KEY_REACTANTS = "reactants";
const char* const KEY_PRODUCTS = "products";
const char* const VALUE_NULL = "NULL";
const char* const KEY_FWD_RATE= "fwd_rate";
const char* const KEY_BKWD_RATE= "bkwd_rate";
const char* const KEY_VARIABLE_RATE_VALID = "variable_rate_valid";
const char* const KEY_VARIABLE_RATE = "variable_rate";
const char* const KEY_VARIABLE_RATE_SWITCH = "variable_rate_switch";
const char* const KEY_VARIABLE_RATE_TEXT = "variable_rate_text";
const char* const KEY_MATERIAL_NAMES = "material_names";
const char* const KEY_MATERIALS = "materials";
const char* const KEY_MATERIAL_DICT = "material_dict";
const char* const KEY_VALUE_MEMBRANE = "membrane"; // used both as a key and value
const char* const KEY_DIFFUSE_COLOR = "diffuse_color";
const char* const KEY_R = "r";
const char* const KEY_G = "g";
const char* const KEY_B = "b";
const char* const KEY_A = "a";
const char* const KEY_MODEL_OBJECTS = "model_objects";
const char* const KEY_MODEL_OBJECT_LIST = "model_object_list";
const char* const KEY_PARENT_OBJECT = "parent_object";
const char* const KEY_DESCRIPTION = "description";
const char* const KEY_OBJECT_SOURCE = "object_source";
const char* const KEY_DYNAMIC_DISPLAY_SOURCE = "dynamic_display_source";
const char* const KEY_SCRIPT_NAME = "script_name";
const char* const KEY_MEMBRANE_NAME = "membrane_name";
const char* const KEY_IS_BNGL_COMPARTMENT = "is_bngl_compartment";
const char* const KEY_DYNAMIC = "dynamic";
const char* const KEY_MOL_VIZ = "mol_viz";
const char* const KEY_MANUAL_SELECT_VIZ_DIR = "manual_select_viz_dir";
const char* const KEY_FILE_START_INDEX = "file_start_index";
const char* const KEY_SEED_LIST = "seed_list";
const char* const KEY_COLOR_LIST = "color_list";
const char* const KEY_ACTIVE_SEED_INDEX = "active_seed_index";
const char* const KEY_FILE_INDEX = "file_index";
const char* const KEY_FILE_NUM = "file_num";
const char* const KEY_VIZ_ENABLE = "viz_enable";
const char* const KEY_FILE_NAME = "file_name";
const char* const KEY_COLOR_INDEX = "color_index";
const char* const KEY_RENDER_AND_SAVE = "render_and_save";
const char* const KEY_FILE_STEP_INDEX = "file_step_index";
const char* const KEY_VIZ_LIST = "viz_list";
const char* const KEY_FILE_STOP_INDEX = "file_stop_index";
const char* const KEY_FILE_DIR = "file_dir";
const char* const KEY_MOLECULE_LIST = "molecule_list";
const char* const KEY_DEFINE_MOLECULES = "define_molecules";
const char* const KEY_DISPLAY = "display";
const char* const KEY_EMIT = "emit";
const char* const KEY_COLOR = "color";
const char* const KEY_GLYPH = "glyph";
const char* const VALUE_GLYPH_SPHERE_1 = "Sphere_1";
const char* const KEY_SCALE = "scale";
const char* const KEY_BNGL_COMPONENT_LIST = "bngl_component_list";
const char* const KEY_CNAME = "cname";
const char* const KEY_CSTATES = "cstates";
const char* const KEY_IS_KEY = "is_key";
const char* const KEY_ROT_INDEX = "rot_index";
const char* const KEY_ROT_ANG = "rot_ang";
const char* const KEY_ROT_X = "rot_x";
const char* const KEY_ROT_Y = "rot_y";
const char* const KEY_ROT_Z = "rot_z";
const char* const KEY_LOC_X = "loc_x";
const char* const KEY_LOC_Y = "loc_y";
const char* const KEY_LOC_Z = "loc_z";
const char* const KEY_MOL_BNGL_LABEL = "mol_bngl_label";
const char* const KEY_MOL_NAME = "mol_name";
const char* const KEY_MOL_TYPE = "mol_type";
const char* const VALUE_MOL_TYPE_2D = "2D";
const char* const VALUE_MOL_TYPE_3D = "3D";
const char* const KEY_DIFFUSION_CONSTANT = "diffusion_constant";
const char* const KEY_EXPORT_VIZ = "export_viz";
const char* const KEY_CUSTOM_SPACE_STEP = "custom_space_step";
const char* const KEY_MAXIMUM_STEP_LENGTH = "maximum_step_length";
const char* const KEY_TARGET_ONLY = "target_only";
const char* const KEY_SPATIAL_STRUCTURE = "spatial_structure";
const char* const KEY_CUSTOM_TIME_STEP = "custom_time_step";
const char* const KEY_RELEASE_SITES = "release_sites";
const char* const KEY_RELEASE_SITE_LIST = "release_site_list";
const char* const KEY_POINTS_LIST = "points_list";
const char* const KEY_PATTERN = "pattern";
const char* const KEY_STDDEV = "stddev";
const char* const KEY_QUANTITY = "quantity";
const char* const KEY_MOLECULE = "molecule";
const char* const KEY_SHAPE = "shape";
const char* const VALUE_OBJECT = "OBJECT";
const char* const VALUE_SPHERICAL = "SPHERICAL";
const char* const VALUE_SPHERICAL_SHELL = "SPHERICAL_SHELL";
const char* const VALUE_LIST = "LIST";
const char* const KEY_RELEASE_PROBABILITY = "release_probability";
const char* const KEY_OBJECT_EXPR = "object_expr";
const char* const KEY_ORIENT = "orient";
const char* const KEY_LOCATION_X = "location_x";
const char* const KEY_LOCATION_Y = "location_y";
const char* const KEY_LOCATION_Z = "location_z";
const char* const KEY_SITE_DIAMETER = "site_diameter";
const char* const KEY_QUANTITY_TYPE = "quantity_type";
const char* const VALUE_NUMBER_TO_RELEASE = "NUMBER_TO_RELEASE";
const char* const VALUE_GAUSSIAN_RELEASE_NUMBER = "GAUSSIAN_RELEASE_NUMBER";
const char* const VALUE_DENSITY = "DENSITY";
const char* const KEY_DEFINE_RELEASE_PATTERNS = "define_release_patterns";
const char* const KEY_RELEASE_PATTERN_LIST = "release_pattern_list";
const char* const KEY_NUMBER_OF_TRAINS = "number_of_trains";
const char* const KEY_DELAY = "delay";
const char* const KEY_TRAIN_DURATION = "train_duration";
const char* const KEY_TRAIN_INTERVAL = "train_interval";
const char* const KEY_RELEASE_INTERVAL = "release_interval";
const char* const KEY_VIZ_OUTPUT = "viz_output";
const char* const KEY_EXPORT_ALL = "export_all";
const char* const KEY_ALL_ITERATIONS = "all_iterations";
const char* const KEY_START = "start";
const char* const KEY_STEP = "step";
const char* const KEY_END = "end";
const char* const KEY_REACTION_DATA_OUTPUT = "reaction_data_output";
const char* const KEY_PLOT_LAYOUT = "plot_layout";
const char* const KEY_PLOT_LEGEND = "plot_legend";
const char* const KEY_MOL_COLORS = "mol_colors";
const char* const KEY_ALWAYS_GENERATE = "always_generate";
const char* const KEY_OUTPUT_BUF_SIZE = "output_buf_size";
const char* const KEY_RXN_STEP = "rxn_step";
const char* const KEY_COMBINE_SEEDS = "combine_seeds";
const char* const KEY_REACTION_OUTPUT_LIST = "reaction_output_list";
const char* const KEY_RXN_OR_MOL = "rxn_or_mol";
const char* const VALUE_MDLSTRING = "MDLString";
const char* const VALUE_REACTION = "Reaction";
const char* const VALUE_MOLECULE = "Molecule";
const char* const VALUE_FILE = "File";
const char* const KEY_PLOTTING_ENABLED = "plotting_enabled";
const char* const KEY_MDL_FILE_PREFIX = "mdl_file_prefix"; // contains count name
const char* const KEY_OUTPUT_FILE_OVERRIDE = "output_file_override";
const char* const KEY_MOLECULE_NAME = "molecule_name";
const char* const KEY_REACTION_NAME = "reaction_name";
const char* const KEY_OBJECT_NAME = "object_name";
const char* const KEY_DATA_FILE_NAME = "data_file_name";
const char* const KEY_COUNT_LOCATION = "count_location";
const char* const VALUE_COUNT_LOCATION_WORLD = "World";
const char* const VALUE_COUNT_LOCATION_OBJECT = "Object";
const char* const VALUE_COUNT_LOCATION_REGION = "Region";
const char* const KEY_MDL_STRING = "mdl_string";
const char* const KEY_REGION_NAME = "region_name";
const char* const MARKER_SPECIES_COMMENT = "/*Species*/";
const char* const MARKER_MOLECULES_COMMENT = "/*Molecules*/";
const char* const KEY_DEFINE_SURFACE_CLASSES = "define_surface_classes";
const char* const KEY_SURFACE_CLASS_LIST = "surface_class_list";
const char* const KEY_SURFACE_CLASS_PROP_LIST = "surface_class_prop_list";
const char* const KEY_SURF_CLASS_ORIENT = "surf_class_orient";
const char* const KEY_SURF_CLASS_TYPE = "surf_class_type";
const char* const VALUE_TRANSPARENT = "TRANSPARENT";
const char* const VALUE_REFLECTIVE = "REFLECTIVE";
const char* const VALUE_ABSORPTIVE = "ABSORPTIVE";
const char* const VALUE_CLAMP_CONCENTRATION = "CLAMP_CONCENTRATION";
const char* const VALUE_CLAMP_FLUX = "CLAMP_FLUX";
const char* const KEY_AFFECTED_MOLS = "affected_mols";
const char* const VALUE_SINGLE = "SINGLE";
const char* const KEY_CLAMP_VALUE = "clamp_value";
const char* const KEY_MODIFY_SURFACE_REGIONS = "modify_surface_regions";
const char* const KEY_MODIFY_SURFACE_REGIONS_LIST = "modify_surface_regions_list";
const char* const KEY_REGION_SELECTION = "region_selection";
const char* const VALUE_ALL = "ALL";
const char* const VALUE_SEL = "SEL";
const char* const KEY_SURF_CLASS_NAME = "surf_class_name";
const char* const KEY_INITIAL_REGION_MOLECULES_LIST = "initial_region_molecules_list";
const char* const KEY_MOLECULE_NUMBER = "molecule_number";
const char* const KEY_MOLECULE_DENSITY = "molecule_density";
const char* const KEY_SCRIPTING = "scripting";
const char* const KEY_SCRIPTING_LIST = "scripting_list";
const char* const KEY_MCELL4_SCRIPTING_LIST = "mcell4_scripting_list";
const char* const KEY_INTERNAL_EXTERNAL = "internal_external";
const char* const VALUE_INTERNAL = "internal";
const char* const VALUE_EXTERNAL = "external";
const char* const KEY_INTERNAL_FILE_NAME = "internal_file_name";
const char* const KEY_EXTERNAL_FILE_NAME = "external_file_name";
const char* const KEY_SCRIPT_TEXTS = "script_texts";
const char* const KEY_DM_INTERNAL_FILE_NAME = "dm_internal_file_name";
const char* const KEY_FORCE_PROPERTY_UPDATE = "force_property_update";
const char* const KEY_DM_EXTERNAL_FILE_NAME = "dm_external_file_name";
const char* const KEY_IGNORE_CELLBLENDER_DATA = "ignore_cellblender_data";
const char* const KEY_SIMULATION_CONTROL = "simulation_control";
const char* const KEY_EXPORT_FORMAT = "export_format";
const char* const VALUE_MCELL_MDL_MODULAR = "mcell_mdl_modular";
const char* const KEY_INITIALIZATION = "initialization";
const char* const KEY_INTERACTION_RADIUS = "interaction_radius";
const char* const KEY_ACCURATE_3D_REACTIONS = "accurate_3d_reactions";
const char* const KEY_TIME_STEP = "time_step";
const char* const KEY_RADIAL_SUBDIVISIONS = "radial_subdivisions";
const char* const KEY_ITERATIONS = "iterations";
const char* const KEY_RADIAL_DIRECTIONS = "radial_directions";
const char* const KEY_CENTER_MOLECULES_ON_GRID = "center_molecules_on_grid";
const char* const KEY_COMMAND_OPTIONS = "command_options";
const char* const KEY_EXPORT_ALL_ASCII = "export_all_ascii";
const char* const KEY_MICROSCOPIC_REVERSIBILITY = "microscopic_reversibility";
const char* const KEY_TIME_STEP_MAX = "time_step_max";
const char* const KEY_VACANCY_SEARCH_DISTANCE = "vacancy_search_distance";
const char* const KEY_SPACE_STEP = "space_step";
const char* const KEY_SURFACE_GRID_DENSITY = "surface_grid_density";
const char* const VALUE_ON = "ON";
const char* const VALUE_OFF = "OFF";
const char* const VALUE_INDIVIDUAL = "INDIVIDUAL";
const char* const VALUE_IGNORED = "IGNORED";
const char* const VALUE_WARNING = "WARNING";
const char* const VALUE_ERROR = "ERROR";
const char* const KEY_WARNINGS = "warnings";
const char* const KEY_MISSED_REACTION_THRESHOLD = "missed_reaction_threshold";
const char* const KEY_LIFETIME_TOO_SHORT = "lifetime_too_short";
const char* const KEY_LIFETIME_THRESHOLD = "lifetime_threshold";
const char* const KEY_ALL_WARNINGS = "all_warnings";
const char* const KEY_MISSED_REACTIONS = "missed_reactions";
const char* const KEY_NEGATIVE_DIFFUSION_CONSTANT = "negative_diffusion_constant";
const char* const KEY_NEGATIVE_REACTION_RATE = "negative_reaction_rate";
const char* const KEY_HIGH_PROBABILITY_THRESHOLD = "high_probability_threshold";
const char* const KEY_DEGENERATE_POLYGONS = "degenerate_polygons";
const char* const KEY_USELESS_VOLUME_ORIENTATION = "useless_volume_orientation";
const char* const KEY_HIGH_REACTION_PROBABILITY = "high_reaction_probability";
const char* const KEY_MOLECULE_PLACEMENT_FAILURE = "molecule_placement_failure";
const char* const KEY_LARGE_MOLECULAR_DISPLACEMENT = "large_molecular_displacement";
const char* const KEY_MISSING_SURFACE_ORIENTATION = "missing_surface_orientation";
const char* const KEY_PARTITIONS = "partitions";
const char* const KEY_INCLUDE = "include";
const char* const KEY_Z_END = "z_end";
const char* const KEY_X_END = "x_end";
const char* const KEY_X_START = "x_start";
const char* const KEY_Z_START = "z_start";
const char* const KEY_RECURSION_FLAG = "recursion_flag";
const char* const KEY_Y_START = "y_start";
const char* const KEY_X_STEP = "x_step";
const char* const KEY_Y_END = "y_end";
const char* const KEY_Z_STEP = "z_step";
const char* const KEY_Y_STEP = "y_step";
const char* const KEY_NOTIFICATIONS = "notifications";
const char* const KEY_SPECIES_REACTIONS_REPORT = "species_reactions_report";
const char* const KEY_FILE_OUTPUT_REPORT = "file_output_report";
const char* const KEY_ALL_NOTIFICATIONS = "all_notifications";
const char* const KEY_PROBABILITY_REPORT_THRESHOLD = "probability_report_threshold";
const char* const KEY_BOX_TRIANGULATION_REPORT = "box_triangulation_report";
const char* const KEY_RELEASE_EVENT_REPORT = "release_event_report";
const char* const KEY_PROGRESS_REPORT = "progress_report";
const char* const KEY_MOLECULE_COLLISION_REPORT = "molecule_collision_report";
const char* const KEY_ITERATION_REPORT = "iteration_report";
const char* const KEY_FINAL_SUMMARY = "final_summary";
const char* const KEY_VARYING_PROBABILITY_REPORT = "varying_probability_report";
const char* const KEY_PROBABILITY_REPORT = "probability_report";
const char* const KEY_PARTITION_LOCATION_REPORT = "partition_location_report";
const char* const KEY_DIFFUSION_CONSTANT_REPORT = "diffusion_constant_report";
const char* const VALUE_BRIEF = "BRIEF";
const double DEFAULT_OBJECT_COLOR_COMPONENT = 0.8;
const double DEFAULT_OBJECT_ALPHA = 0.25;
// --------------------------------- data layout defines --------------
const char* const KEY_VERSION = "version";
const char* const KEY_MCELL4_MODE = "mcell4_mode";
const char* const KEY_DATA_LAYOUT = "data_layout";
const char* const VALUE_DIR = "/DIR";
const char* const VALUE_FILE_TYPE = "/FILE_TYPE";
// using define because of usage in another definition
#define VALUE_VIZ_DATA "viz_data"
#define VALUE_REACT_DATA "react_data"
const char* const VALUE_SEED = "/SEED";
// ---------------------------------- other --------------------------
const char* const RELEASE_PATTERN_PREFIX = "release_pattern_";
const char* const COLOR_MAT_PREFIX = "color_";
// ---------------------------------- datamodel utilities----------------------------------
// TODO: move the utility functions into a c++ file
namespace DMUtils {
static inline void add_version(Json::Value& node, const char* ver) {
node[KEY_DATA_MODEL_VERSION] = ver;
}
static inline void append_triplet(Json::Value& list, const double x, const double y, const double z) {
Json::Value list_triplet;
list_triplet.append(Json::Value(x));
list_triplet.append(Json::Value(y));
list_triplet.append(Json::Value(z));
list.append(list_triplet);
}
static inline std::string remove_obj_name_prefix(const std::string& prefix, const std::string& name) {
if (prefix == "") {
return name;
}
size_t pos = prefix.size() + 1;
assert(name.size() > pos);
assert(name.substr(0, pos) == prefix + ".");
return name.substr(pos);
}
// we do not know the prefix in this case
static inline std::string remove_obj_name_prefix(const std::string& name) {
size_t pos = name.find('.');
if (pos == std::string::npos) {
return name;
}
assert(pos + 1 < name.size());
return name.substr(pos + 1);
}
static inline std::string remove_surf_class_prefix(
const std::string& prefix, const std::string& name) {
size_t pos = name.find('+');
if (pos != std::string::npos && name.find(prefix) == 0) {
size_t pos_prefix = prefix.size() + 1;
assert(name.size() > pos_prefix);
assert(name.substr(0, pos_prefix) == prefix + "+");
return name.substr(pos_prefix);
}
// the prefix can be also at the end as suffix
else if (pos != std::string::npos && name.substr(pos + 1) == prefix) {
return name.substr(0, pos);
}
else {
return name;
}
}
static inline std::string get_object_w_region_name(
const std::string& name, const bool remove_prefix = true) {
std::string noprefix;
if (remove_prefix) {
noprefix = remove_obj_name_prefix(name);
}
else {
noprefix = name;
}
size_t pos = noprefix.find(',');
assert(pos != std::string::npos);
assert(pos + 1 < name.size());
std::string obj = noprefix.substr(0, pos);
std::string reg = noprefix.substr(pos + 1);
return obj + "[" + reg + "]";
}
static inline std::string get_region_name(const std::string& name) {
size_t pos = name.find(',');
assert(pos != std::string::npos);
assert(pos + 1 < name.size());
std::string reg_selection = name.substr(pos + 1);
return reg_selection;
}
static inline std::string get_surface_region_name(const std::string& name) {
size_t pos = name.find(',');
// TODO: these checks should be enabled also for release build
assert(pos != std::string::npos);
assert(pos + 1 < name.size());
return name.substr(pos + 1);
}
static inline std::string to_id(const std::string& name) {
if (name == "") {
return "";
}
std::string res;
for (char c: name) {
if (isalnum(c) || c == '_') {
res += c;
}
}
return res;
}
static inline std::string orientation_to_str(const BNG::orientation_t o) {
switch (o) {
case BNG::ORIENTATION_DOWN: return ",";
case BNG::ORIENTATION_UP: return "'";
case BNG::ORIENTATION_NONE: return ";"; // this character is used by cellblender for volume mols is release sites
default:
assert(false);
return "ERROR";
}
}
static inline std::string color_to_mat_name(const uint color) {
std::stringstream ss;
ss << std::setfill('0') << std::setw(8) << std::hex << (color);
return COLOR_MAT_PREFIX + ss.str();
}
#define CONVERSION_UNSUPPORTED(msg) \
do { errs() << msg << " This is not supported yet.\n"; exit(1); } while (0)
#define CONVERSION_CHECK(cond, msg) \
do { if (!(cond)) { errs() << "Check failed: " << #cond << ": " << msg << " This is not supported yet.\n"; exit(1); } } while (0)
} // namespace DMUtil
#endif // _DATAMODEL_DEFINES_H_
| Unknown |
3D | mcellteam/mcell | include/debug_config.h | .h | 7,553 | 248 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
// diverse debug macros
#ifndef __DEBUG_CONFIG_H__
#define __DEBUG_CONFIG_H__
// TODO: make the dumping system integrated and build it all for debug builds,
// enabled by cmdline arguments
// for mcell3 - crossing memory partitions causes reordering in diffusion and it is not possible to
// compare results anymore
#include <iostream>
// use gperftools to print a snapshot of heap, can be displayed with
// pprof mcell.so mem<N>.dump -gv
// MCell must be built with -DENABLE_GPERFTOOLS=ON otherwise
// linking fails with undefined symbol MallocExtension::instance()
#ifdef WITHGPERFTOOLS
//#define PROFILE_MEMORY
#endif
// when enabled, mcell3 produces identical result to the mcell master branch
#define MCELL3_IDENTICAL
#define MCELL4_IDENTICAL
//#define MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP
//#define MCELL3_SORTED_VIZ_OUTPUT
// define when comparin mcell4 and pymcell4 outputs
//#define PYMCELL4_TESTING
// bug in mcellr - exact disk
// most probably mcell3r ever had support for reactive surfaces,
// but keeping this as a macro to maintain compatibility
// if needed
#define FIX_EXTERNAL_SPECIES_WO_RXS_IN_EXACT_DISK
// number placements are in reverse order, but density placements are in correct order,
// enabling this macro unifies it
#define MCELL3_REVERSE_INITIAL_SURF_MOL_PLACEMENT_BY_NUM
// in MCell3 the newly created particles that have long time steps gradually increase
// their timestep to the full value
// we cannot have individual timesteps for each molecule in MCell4 because there would be no way to
// parallelize it
// enabling this macro disables logic in safe_diffusion_step and set_inertness_and_maxtime
//#define MCELL3_MOLECULE_MOVES_WITH_MAXIMUM_TIMESTEP
//#define MCELL3_NO_COMPARMTENT_IN_PRINTOUTS
#ifndef MCELL3_IDENTICAL
// ---- MCell4 macros to match MCell3R ----
#ifndef MCELL4_IDENTICAL
// MCell3R always creates new products when there is the same species
// on the reactants and products side (unlike in normal MCell)
// this switch is for validation of MCell4 BNG against MCell3R
// One can detect this automatically or with an option, but both seemed as ugly solution
// testsuite for mcell4 won't pass
#define MCELL4_DO_NOT_REUSE_REACTANT
// MCell3R seems to sort reaction products by name
//#define MCELL4_SORT_RXN_PRODUCTS_BY_NAME
//#define MCELL4_SORT_RXN_PRODUCTS_BY_NAME_REV
#define MCELL4_SORT_RXN_PRODUCTS_BY_LENGTH_DESC
// tentative sorting of reactions in a rxn class to match MCell3R
#define MCELL4_REVERSED_RXNS_IN_RXN_CLASS
// do not call random generator when probability of an unimol rxn is 0
// required for compatibility with MCell3R that ignores such reactions,
// however MCell3 call rng even if the prob is 0
// testsuite for mcell4 won't pass
#define MCELL4_NO_RNG_FOR_UNIMOL_RXN_P_0
// when a volume product is created in a surface reaction, it is bumped from the surface,
// when is this macro enabled, it is bumped only by EPS same as in MCell3, not 16*EPS
#define MCELL4_VOL_PROD_BUMP_FROM_SURFACE_ONLY_ONE_EPS
// sort molecules in schedule helper according to ID before a new timestep begins
// testsuite for mcell4 won't pass
#define MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
#define MCELL3_UNIMOL_RX_ABSORB_NO_RNG
// do not reuse molecule IDs
#define MCELL3_DO_NOT_REUSE_MOL_ID_UNIMOL_RXN
#endif
// ^^^^ MCell4 macros to match MCell3R ^^^^
// enable several things that make comparison with mcell4 easier
#define MCELL3_ONLY_ONE_MEMPART
#define MCELL3_SORTED_VIZ_OUTPUT
#define MCELL3_SORTED_WALLS_FOR_COLLISION
#ifndef MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
// sort molecules when run_timestep is started, replaced by better MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID that
// however changes ordering for mcell4
#define MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP
#endif
//#define MCELL3_4_SAFE_DIFF_STEP_RETURNS_CONSTANT
//#define MCELL3_NEXT_BARRIER_IS_THE_NEXT_TIMESTEP // do not diffuse more than until the end of the timestep
// messes up original ordering when all releases are planned for 0, not sure why yet
// use only really when needed
//#define MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
//#define MCELL3_ROUND_TSTEPS
//#define MCELL3_ALWAYS_DIFFUSE // non-diffusable molecules are scheduled differently when there is a unimol reaction and ??
#define ASSERT_FOR_MCELL4(...) assert(__VA_ARGS__)
#else
#define ASSERT_FOR_MCELL4(...) do { } while(0)
#endif
#define DUMP4_PRECISION_DEFAULT 5
#ifdef PYMCELL4_TESTING
// needed for easier diff between mcell4 and pymcell4
#define SORT_MCELL4_SPECIES_BY_NAME
// testsuite for mcell4 won't pass
// #define ORDER_RXNS_IN_RXN_CLASS_BY_NAME
#define DUMP4_PRECISION 17
#else
#define DUMP4_PRECISION DUMP4_PRECISION_DEFAULT
#endif
//#define DEBUG_EXTRA_CHECKS
//#define DUMP_ALWAYS
#define DUMP_NEVER
#if (!defined(NDEBUG) || defined(DUMP_ALWAYS)) && !defined(DUMP_NEVER)
/*
#define MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
#define MCELL3_SORTED_VIZ_OUTPUT
#define MCELL3_ONLY_ONE_MEMPART
#define MCELL3_4_SAFE_DIFF_STEP_RETURNS_CONSTANT
#define MCELL3_SORTED_WALLS_FOR_COLLISION
#define MCELL3_RELEASE_ACCORDING_TO_EVENT_TIME
#define MCELL3_UNIMOL_RX_ABSORB_NO_RNG
*/
//#define DUMP_LOCAL_SCHEDULE_HELPER
#define TRACK_MOL 1 // true
#define TRACKED_MOL_ID 61254
#define FROM_ITERATION 100000
#define TO_ITERATION 1000000
#define DUMP_NONDIFFUSING_VMS
#if 1
#define DEBUG_DIFFUSION
#define DEBUG_COLLISIONS
//#define NODEBUG_WALL_COLLISIONS
#endif
#define DEBUG_RXNS
//#define DEBUG_COMPARTMENTS
//#define DEBUG_RNG_CALLS // cannot be conditioned by iterations
//#define DEBUG_WALL_COLLISIONS
//#define DEBUG_DYNAMIC_GEOMETRY
//#define DEBUG_DYNAMIC_GEOMETRY_MCELL4_ONLY
//#define DEBUG_DYNAMIC_GEOMETRY_COLLISION_DETECTIONS
//#define DEBUG_CLOSEST_INTERIOR_POINT
//#define DEBUG_POLY_EDGE_INITIALIZATION
//#define DEBUG_EDGE_INITIALIZATION
//#define DEBUG_SCHEDULER_ACTION
//#define DEBUG_SCHEDULER
//#define DEBUG_DEFRAGMENTATION
//#define DEBUG_EXACT_DISK
//#define DEBUG_RELEASES // cannot be conditioned by iterations
// does not generate the same dump as mcell3
//#define DEBUG_SUBPARTITIONS
//#define DEBUG_COUNTED_VOLUMES
//#define DEBUG_TRANSPARENT_SURFACES
//#define DEBUG_TIMING
//#define DEBUG_DIFFUSION_EXTRA
//#define DEBUG_COLLISIONS_WALL_EXTRA
//#define DEBUG_COUNTED_VOLUMES
//#define DEBUG_REACTION_PROBABILITIES // cannot be conditioned by iterations
//#define DEBUG_GRIDS
#define DUMP_CONDITION3(code) do { if ((int)world->current_iterations >= (int)FROM_ITERATION && (int)world->current_iterations <= (int)TO_ITERATION) { code; } } while (0)
#define DUMP_CONDITION4(id, code) do { \
if (\
((int)world->get_current_iteration() >= (int)FROM_ITERATION && (int)world->get_current_iteration() <= (int)TO_ITERATION) || \
(TRACK_MOL && id == TRACKED_MOL_ID)) { \
code; } } while (0)
#define DUMP_CONDITION4P(code) do { if ((int)p.stats.get_current_iteration() >= (int)FROM_ITERATION && (int)p.stats.get_current_iteration() <= (int)TO_ITERATION) { code; } } while (0)
#ifdef DEBUG_SCHEDULER
#define DUMP_LOCAL_SCHEDULE_HELPER
#endif
#endif
#endif // __DEBUG_CONFIG_H__
| Unknown |
3D | mcellteam/mcell | src4/wall_utils.h | .h | 822 | 39 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_WALL_UTILS_H_
#define SRC4_WALL_UTILS_H_
namespace MCell {
class Partition;
class Wall;
struct Vec3;
namespace WallUtils {
// only the needed functions for now
static int wall_in_box(
const Partition& p,
const Wall& w,
const Vec3& llf, const Vec3& urb
);
} // namespace WallUtil
} // namespace MCell
#endif // SRC4_WALL_UTILS_H_
| Unknown |
3D | mcellteam/mcell | src4/wall_overlap.h | .h | 913 | 31 | /******************************************************************************
*
* Copyright (C) 2006-2017,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_WALL_OVERLAP_H_
#define SRC4_WALL_OVERLAP_H_
#include "defines.h"
namespace MCell {
class Wall;
namespace WallOverlap {
// rand_vec is a value of three random values used when sorting walls for overlap detection
// (TODO: not completely sure why a random value is needed there)
bool check_for_overlapped_walls(Partition& p, const Vec3& rand_vec);
} // namespace WallOverlap
} // namespace MCell
#endif // SRC4_WALL_OVERLAP_H_
| Unknown |
3D | mcellteam/mcell | src4/diffuse_react_event.h | .h | 10,821 | 357 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_DIFFUSE_REACT_EVENT_H_
#define SRC4_DIFFUSE_REACT_EVENT_H_
#include <vector>
#include <deque>
#include "../libs/boost/container/small_vector.hpp"
#include "base_event.h"
#include "partition.h"
#include "collision_structs.h"
namespace MCell {
class World;
class Partition;
class Molecule;
// we are executing diffusion every iteration, do not change this constant
const double DIFFUSE_REACT_EVENT_PERIODICITY = 1.0;
// this is an arbitrary value but let's say that we do now want to
// simulate more than 100 iterations at once, this is used in scheduler
// to find the next barrier
const double DIFFUSION_TIME_UPPER_LIMIT = 100.0;
enum class RayTraceState {
UNDEFINED,
HIT_SUBPARTITION,
RAY_TRACE_HIT_WALL,
FINISHED
};
enum class WallRxnResult {
INVALID,
TRANSPARENT,
REFLECT,
DESTROYED
};
class TileNeighborVector: public std::deque<WallTileIndexPair> {
public:
void dump(const std::string extra_comment, const std::string ind) {
std::cout << ind << extra_comment << "\n";
for (uint i = 0; i < size(); i++) {
std::cout << ind << i << ": " << at(i).tile_index << "\n";
}
}
};
/**
* Used as a pair molecule id, remaining timestep for molecules newly created in diffusion.
* Using name action instead of event because events are handled by scheduler and are ordered by time.
* These actions are simply processes in a queue (FIFO) manner.
*
* Used in diffuse_react _event_t and in partition_t.
*/
class DiffuseAction {
public:
// position where this mol was created is
// used to avoid rebinding for surf+vol->surf+vol reactions
DiffuseAction(
const molecule_id_t id_,
const WallTileIndexPair& where_created_this_iteration_)
:
id(id_),
where_created_this_iteration(where_created_this_iteration_) {
}
// position where the molecule was created may be unset when it was not a result of surface reaction
DiffuseAction(const molecule_id_t id_)
: id(id_) {
}
// defined because of usage in calendar_t
const DiffuseAction& operator->() const { // TODO: remove
return *this;
}
molecule_id_t id;
// used to avoid rebinding for surf+vol->surf+vol reactions
// TODO: can be removed and replaced with Molecule::previous_wall_index?
WallTileIndexPair where_created_this_iteration;
};
/**
* Diffuse all molecules with a given time step.
* When a molecule is diffused, it is checked for collisions and reactions
* are evaluated. Molecules newly created in reactions and diffused with their
* remaining time.
*/
class DiffuseReactEvent : public BaseEvent {
public:
DiffuseReactEvent(World* world_) :
BaseEvent(EVENT_TYPE_INDEX_DIFFUSE_REACT),
world(world_), time_up_to_next_barrier(FLT_INVALID) {
// repeat this event each iteration
periodicity_interval = DIFFUSE_REACT_EVENT_PERIODICITY;
}
void step() override;
void dump(const std::string ind = "") const override;
bool update_event_time_for_next_scheduled_time() override {
assert(time_up_to_next_barrier != FLT_INVALID);
// the next time to schedule
if (time_up_to_next_barrier < periodicity_interval) {
event_time = event_time + time_up_to_next_barrier;
}
else {
event_time = event_time + periodicity_interval;
}
return true;
}
bool may_be_blocked_by_barrier_and_needs_set_time_step() const override {
// DiffuseReactEvent must execute only up to a barrier such as CountEvent
return true;
}
double get_max_time_up_to_next_barrier() const override {
return DIFFUSION_TIME_UPPER_LIMIT;
}
void set_barrier_time_for_next_execution(const double time_up_to_next_barrier_) override {
// scheduler says to this event for how long it can execute
// either the maximum time step (periodicity_interval) or time up to the
// first barrier
release_assert(time_up_to_next_barrier_ > 0 && "Diffusion must advance even if a little bit");
assert(cmp_eq(time_up_to_next_barrier_, round_f(time_up_to_next_barrier_)) &&
"Time up to the next barrier is expected to be a whole number");
time_up_to_next_barrier = time_up_to_next_barrier_;
}
void add_diffuse_action(const DiffuseAction& action) {
new_diffuse_actions.push_back(action);
}
bool before_this_iterations_end(const double time) const {
// must be lt to make sure that we don't simulate molecules with max_time close to 0
return cmp_lt(time, event_time + periodicity_interval, EPS);
}
// used also directly from MCell API
// returns true if molecule survived
bool outcome_unimolecular(
Partition& p,
Molecule& vm,
const double scheduled_time,
BNG::RxnClass* rxn_class,
const BNG::rxn_class_pathway_index_t pathway_index,
MoleculeIdsVector* optional_product_ids = nullptr
);
// returns true if molecule survived
bool cross_transparent_wall(
Partition& p,
const Collision& collision,
Molecule& vm, // moves vm to the reflection point
Vec3& remaining_displacement,
double& t_steps,
double& elapsed_molecule_time,
wall_index_t& last_hit_wall_index
);
World* world;
// this event diffuses all molecules that have this diffusion time_step
double time_up_to_next_barrier;
private:
// auxiliary array used to store result from Partition::get_molecules_ready_for_diffusion
// using the same array every iteration in order not to reallocate it every iteration
MoleculeIdsVector molecules_ready_array;
// internal event's schedule of molecules newly created in reactions that must be diffused
std::vector<DiffuseAction> new_diffuse_actions;
double get_max_time(Partition& p, Molecule& m);
void diffuse_molecules(Partition& p, const MoleculeIdsVector& indices);
void diffuse_single_molecule(
Partition& p,
const molecule_id_t vm_id,
WallTileIndexPair where_created_this_iteration
);
// ---------------------------------- volume molecules ----------------------------------
void diffuse_vol_molecule(
Partition& p,
Molecule& vm,
double& max_time,
const double diffusion_start_time,
WallTileIndexPair& where_created_this_iteration
);
bool collide_and_react_with_vol_mol(
Partition& p,
Collision& collision,
Vec3& displacement,
const double t_steps,
const double r_rate_factor,
const double elapsed_molecule_time
);
int collide_and_react_with_surf_mol(
Partition& p,
const Collision& collision,
const double r_rate_factor,
WallTileIndexPair& where_created_this_iteration,
wall_index_t& last_hit_wall_index,
Vec3& remaining_displacement,
double& t_steps,
double& elapsed_molecule_time
);
WallRxnResult collide_and_react_with_walls(
Partition& p,
Collision& collision,
const double r_rate_factor,
const double elapsed_molecule_time,
const double t_steps
);
// ---------------------------------- surface molecules ----------------------------------
void diffuse_surf_molecule(
Partition& p,
Molecule& sm,
double& max_time,
const double diffusion_start_time
);
wall_index_t ray_trace_surf(
Partition& p,
const BNG::Species& species,
const molecule_id_t sm_id,
Vec2& remaining_displacement,
Vec2& new_pos,
BNG::RxnClass*& absorb_now_rxn_class // set to non-null is molecule has to be absorbed
);
bool react_2D_all_neighbors(
Partition& p,
Molecule& sm,
const double time, // same argument as t passed in mcell3 (come up with a better name)
const double diffusion_start_time // diffusion_start_time + elapsed_molecule_time should be the time when reaction occurred
);
bool react_2D_intermembrane(
Partition& p, Molecule& sm,
const double t_steps, const double diffusion_start_time
);
// ---------------------------------- reactions ----------------------------------
int find_surf_product_positions(
Partition& p,
const Collision& collision,
const BNG::RxnRule* rxn,
const Molecule* reacA, const bool keep_reacA,
const Molecule* reacB, const bool keep_reacB,
const Molecule* surf_reac,
const BNG::RxnProductsVector& actual_products,
GridPosVector& assigned_surf_product_positions,
uint& num_surface_products,
bool& surf_pos_reacA_is_used
);
int outcome_bimolecular(
Partition& p,
const Collision& collision,
const int path,
const double remaining_time_step
);
int outcome_intersect(
Partition& p,
BNG::RxnClass* rxn_class,
const BNG::rxn_class_pathway_index_t pathway_index,
Collision& collision,
const double time
);
void handle_rxn_callback(
Partition& p,
const Collision& collision,
const double time,
const BNG::RxnRule* rxn,
const Molecule* reac1,
const Molecule* reac2,
const MoleculeIdsVector& product_ids,
bool& cancel_reaction
);
orientation_t determine_orientation_depending_on_surf_comp(
const species_id_t prod_species_id,
const Molecule* surf_reac
);
int outcome_products_random(
Partition& p,
const Collision& collision,
const double remaining_time_step,
const BNG::rxn_class_pathway_index_t pathway_index,
bool& keep_reacA,
bool& keep_reacB,
MoleculeIdsVector* optional_product_ids = nullptr
);
void pick_unimol_rxn_class_and_set_rxn_time(
Partition& p,
const double remaining_time_step,
Molecule& vm
);
bool react_unimol_single_molecule(
Partition& p,
const molecule_id_t vm_id
);
};
RayTraceState ray_trace_vol(
Partition& p,
rng_state& rng,
const molecule_id_t vm_id, // molecule that we are diffusing, we are changing its pos and possibly also subvolume
const bool can_vol_react,
const wall_index_t previous_reflected_wall, // is WALL_INDEX_INVALID when our molecule did not replect from anything this iddfusion step yet
Vec3& remaining_displacement, // in/out - recomputed if there was a reflection
CollisionsVector& molecule_collisions // possible reactions in this part of way marching, ordered by time
);
void sort_collisions_by_time(CollisionsVector& molecule_collisions);
} // namespace mcell
#endif // SRC4_DIFFUSE_REACT_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/memory_limit_checker.h | .h | 1,329 | 59 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MEMORY_LIMIT_CHECKER_H_
#define SRC4_MEMORY_LIMIT_CHECKER_H_
#include "defines.h"
#include "libs/cpptime/cpptime.h"
namespace MCell {
class World;
class MemoryLimitChecker {
public:
MemoryLimitChecker() :
world(nullptr),
limit_gb(-1),
exit_when_over_limit(false),
over_limit(false),
timer(nullptr), created_timer_id(0) {
}
~MemoryLimitChecker();
// does nothing when limit_in_gb_ <= 0
void start_timed_check(
World* world_, const int limit_gb_, const bool exit_when_over_limit_ = true);
void stop_timed_check();
bool is_over_memory_limit() const {
return over_limit;
}
private:
// set in start_timed_check
World* world;
int limit_gb; // -1 to ignore
bool exit_when_over_limit;
bool over_limit; // safe to read asynchronously
CppTime::Timer* timer;
CppTime::timer_id created_timer_id;
};
} /* namespace MCell */
#endif /* SRC4_MEMORY_LIMIT_CHECKER_H_ */
| Unknown |
3D | mcellteam/mcell | src4/partition.h | .h | 43,641 | 1,211 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_PARTITION_H_
#define SRC4_PARTITION_H_
#include <set>
#include "bng/rxn_container.h"
#include "defines.h"
#include "dyn_vertex_structs.h"
#include "molecule.h"
#include "scheduler.h"
#include "geometry.h"
#include "simulation_stats.h"
#include "simulation_config.h"
#include "libmcell/api/shared_structs.h"
#include "rng.h"
namespace Json {
class Value;
}
namespace MCell {
typedef std::map<counted_volume_index_t, uint> CountInGeomObjectMap;
typedef std::map<wall_index_t, uint> CountOnWallMap;
typedef uint_set<wall_index_t> WallsInSubpart;
// class used to hold potential reactants of given species in a single subpart
// performance critical, therefore we are using a vector for now,
// we will probably need to change it in the future by deriving it from
// std::map<species_id_t, uint_set<molecule_id_t> >,
class SubpartReactantsSet {
public:
SubpartReactantsSet(const uint num_subparts) {
sets_per_subpart.resize(num_subparts, nullptr);
}
~SubpartReactantsSet() {
for (MoleculeIdsSet* s: sets_per_subpart) {
// check for nullptr is really not needed, mainly to show that
// some items are not allocated
if (s != nullptr) {
delete s;
}
}
}
// subpart must exist
void erase_existing(const subpart_index_t subpart_index, const molecule_id_t id) {
assert(subpart_index < sets_per_subpart.size());
assert(sets_per_subpart[subpart_index] != nullptr);
sets_per_subpart[subpart_index]->erase_existing(id);
}
void erase(const subpart_index_t subpart_index, const molecule_id_t id) {
assert(subpart_index < sets_per_subpart.size());
if (sets_per_subpart[subpart_index] == nullptr) {
return;
}
sets_per_subpart[subpart_index]->erase(id);
}
// key is created if it does not exist
void insert_unique(const subpart_index_t subpart_index, const molecule_id_t id) {
assert(subpart_index < sets_per_subpart.size());
allocate_set_if_needed(subpart_index);
sets_per_subpart[subpart_index]->insert_unique(id);
}
void insert(const subpart_index_t subpart_index, const molecule_id_t id) {
assert(subpart_index < sets_per_subpart.size());
allocate_set_if_needed(subpart_index);
sets_per_subpart[subpart_index]->insert(id);
}
bool contains(const subpart_index_t subpart_index, const molecule_id_t id) const {
assert(subpart_index < sets_per_subpart.size());
if (sets_per_subpart[subpart_index] == nullptr) {
return false;
}
return sets_per_subpart[subpart_index]->count(id) != 0;
}
const MoleculeIdsSet& get_contained_set(const subpart_index_t subpart_index) const {
// when calling this method, this container may be empty, i.e. initialized with 0 subparts
if (subpart_index >= sets_per_subpart.size() || sets_per_subpart[subpart_index] == nullptr) {
return empty_set;
}
else {
return *sets_per_subpart[subpart_index];
}
}
void clear_set(const subpart_index_t subpart_index) {
assert(subpart_index < sets_per_subpart.size());
if (sets_per_subpart[subpart_index] == nullptr) {
return;
}
delete sets_per_subpart[subpart_index];
sets_per_subpart[subpart_index] = nullptr;
}
private:
void allocate_set_if_needed(const subpart_index_t subpart_index) {
assert(subpart_index < sets_per_subpart.size());
if (sets_per_subpart[subpart_index] == nullptr) {
sets_per_subpart[subpart_index] = new MoleculeIdsSet();
}
}
// vector is indexed by subpart_index_t
std::vector<MoleculeIdsSet*> sets_per_subpart;
MoleculeIdsSet empty_set;
};
// container that holds SubpartReactantsSet for each species
class ReactantClassSubpartReactantsSet {
public:
ReactantClassSubpartReactantsSet(const uint num_subparts_) :
empty_subpart_reactants_set(0),
num_subparts(num_subparts_) {
}
~ReactantClassSubpartReactantsSet() {
for (auto& subpart_sets: subparts_reactant_sets_per_reactant_class) {
if (subpart_sets != nullptr) {
delete subpart_sets;
}
}
}
void remove_reactant_sets_for_reactant_class(const BNG::reactant_class_id_t id) {
if (id >= subparts_reactant_sets_per_reactant_class.size()) {
return;
}
if (subparts_reactant_sets_per_reactant_class[id] != nullptr) {
delete subparts_reactant_sets_per_reactant_class[id];
subparts_reactant_sets_per_reactant_class[id] = nullptr;
}
}
SubpartReactantsSet& get_subparts_reactants_for_reactant_class(const BNG::reactant_class_id_t id) {
if (id >= subparts_reactant_sets_per_reactant_class.size()) {
subparts_reactant_sets_per_reactant_class.resize(id + 1, nullptr);
}
if (subparts_reactant_sets_per_reactant_class[id] == nullptr) {
subparts_reactant_sets_per_reactant_class[id] = new SubpartReactantsSet(num_subparts);
}
return *subparts_reactant_sets_per_reactant_class[id];
}
const SubpartReactantsSet& get_subparts_reactants_for_reactant_class(const BNG::reactant_class_id_t id) const {
if (id >= subparts_reactant_sets_per_reactant_class.size() ||
subparts_reactant_sets_per_reactant_class[id] == nullptr) {
return empty_subpart_reactants_set;
}
else {
return *subparts_reactant_sets_per_reactant_class[id];
}
}
private:
// indexed by reactant_class_id, grows dynamically as number of species grows
std::vector<SubpartReactantsSet*> subparts_reactant_sets_per_reactant_class;
SubpartReactantsSet empty_subpart_reactants_set;
// used when constructing SubpartReactantsSet
uint num_subparts;
};
struct Waypoint {
Vec3 pos;
counted_volume_index_t counted_volume_index;
};
/**
* Partition class contains all molecules and other data contained in
* one simulation block.
*/
class Partition {
public:
Partition(
const partition_id_t id_,
const Vec3& origin_corner_,
const SimulationConfig& config_,
BNG::BNGEngine& bng_engine_,
SimulationStats& stats_
);
~Partition();
Molecule& get_m(const molecule_id_t id) {
assert(id != MOLECULE_ID_INVALID);
assert(id < molecule_id_to_index_mapping.size());
// code works with molecule ids, but they need to be converted to indices to the volume_molecules vector
// because we need to defragment the contents
molecule_index_t vm_vec_index = molecule_id_to_index_mapping[id];
assert(vm_vec_index != MOLECULE_INDEX_INVALID);
return molecules[vm_vec_index];
}
const Molecule& get_m(const molecule_id_t id) const {
assert(id != MOLECULE_ID_INVALID);
assert(id < molecule_id_to_index_mapping.size());
// code works with molecule ids, but they need to be converted to indices to the volume_molecules vector
// because we need to defragment the contents
molecule_index_t vm_vec_index = molecule_id_to_index_mapping[id];
assert(vm_vec_index != MOLECULE_INDEX_INVALID);
return molecules[vm_vec_index];
}
void get_molecules_ready_for_diffusion(MoleculeIdsVector& ready_vector) const {
// select all molecules that are scheduled for this iteration and are not defunct
ready_vector.clear();
double time_it_end = stats.get_current_iteration() + 1;
for (molecule_id_t id: schedulable_molecule_ids) {
const Molecule& m = get_m(id);
assert(!m.has_flag(MOLECULE_FLAG_NO_NEED_TO_SCHEDULE));
// new products may have been scheduled for the previous iteration
if (!m.is_defunct() &&
cmp_lt(m.diffusion_time, time_it_end, EPS)) {
ready_vector.push_back(m.id);
}
}
}
bool in_this_partition(const Vec3& pos) const {
return glm::all(glm::greaterThanEqual(pos, origin_corner))
&& glm::all(glm::lessThan(pos, opposite_corner));
}
bool is_subpart_index_in_range(const int index) const {
return index >= 0 && index < (int)config.num_subparts_per_partition_edge;
}
void get_subpart_3d_indices(const Vec3& pos, IVec3& res) const {
assert(in_this_partition(pos) &&
"Requested position is outside of a partition, usually a molecule diffused there. Please enlarge the partition size.");
Vec3 relative_position = pos - origin_corner;
res = relative_position * config.subpart_edge_length_rcp;
}
subpart_index_t get_subpart_index_from_3d_indices_allow_outside(const IVec3& indices) const {
// does nto check whether we are outside the partition
// example: dim: 5x5x5, (1, 2, 3) -> 1 + 2*5 + 3*5*5 = 86
return
indices.x +
indices.y * config.num_subparts_per_partition_edge +
indices.z * config.num_subparts_per_partition_edge_squared;
}
subpart_index_t get_subpart_index_from_3d_indices(const IVec3& indices) const {
// example: dim: 5x5x5, (1, 2, 3) -> 1 + 2*5 + 3*5*5 = 86
assert(indices.x < (int)config.num_subparts_per_partition_edge);
assert(indices.y < (int)config.num_subparts_per_partition_edge);
assert(indices.z < (int)config.num_subparts_per_partition_edge);
// this recomputation can be slow when done often, but we need subpart indices to be continuous
return get_subpart_index_from_3d_indices_allow_outside(indices);
}
subpart_index_t get_subpart_index_from_3d_indices(const int x, const int y, const int z) const {
return get_subpart_index_from_3d_indices(IVec3(x, y, z));
}
void get_subpart_3d_indices_from_index(const subpart_index_t index, IVec3& indices) const {
uint32_t dim = config.num_subparts_per_partition_edge;
// example: dim: 5x5x5, 86 -> (86%5, (86/5)%5, (86/(5*5))%5) = (1, 2, 3)
indices.x = index % dim;
indices.y = (index / dim) % dim;
indices.z = (index / config.num_subparts_per_partition_edge_squared) % dim;
}
subpart_index_t get_subpart_index(const Vec3& pos) const {
IVec3 indices;
get_subpart_3d_indices(pos, indices);
return get_subpart_index_from_3d_indices(indices);
}
void get_subpart_llf_point(const subpart_index_t subpart_index, Vec3& llf) const {
IVec3 indices;
get_subpart_3d_indices_from_index(subpart_index, indices);
llf = origin_corner + Vec3(indices) * Vec3(config.subpart_edge_length);
}
void get_subpart_urb_point_from_llf(const Vec3& llf, Vec3& urb) const {
urb = llf + Vec3(config.subpart_edge_length);
}
// - called when a volume molecule is added and it is detected that this is a new species,
// - ignore the current molecule because it will be added a little later,
// not ignoring the molecule would cause an assert in uint_set::insert_unique called from
// SubpartReactantsSet::insert_unique in case that there are reactions of type A+A
void update_reactants_maps_for_new_species(
const species_id_t new_species_id, const molecule_id_t current_molecule_id
) {
// can the new species initiate a reaction?
BNG::Species& initiator_reactant_species = get_species(new_species_id);
if (initiator_reactant_species.is_target_only()) {
// nothing to do
return;
}
assert(initiator_reactant_species.is_vol());
const BNG::ReactantClassIdSet& reacting_classes =
get_all_rxns().get_reacting_classes(initiator_reactant_species);
SubpartReactantsSet& reactant_sets_per_subpart =
volume_molecule_reactants_per_reactant_class.get_subparts_reactants_for_reactant_class(
initiator_reactant_species.get_reactant_class_id());
// let's go through all molecules and update whether they can react with our new species
for (const Molecule& m: molecules) {
if (!m.is_vol() || m.is_defunct() || m.id == current_molecule_id) {
continue;
}
assert(m.v.reactant_subpart_index != SUBPART_INDEX_INVALID);
const BNG::Species& reactant_species = get_species(m.species_id);
if (reactant_species.has_valid_reactant_class_id() &&
reacting_classes.count(reactant_species.get_reactant_class_id()) != 0) {
reactant_sets_per_subpart.insert(m.v.reactant_subpart_index, m.id);
}
}
}
// - the reactant_subpart_index is index where the molecule was originally created,
// it might have moved to subpart_index in the meantime
// - might invalidate Species references
void change_vol_reactants_map_from_orig_to_current(Molecule& vm, bool adding, bool removing) {
assert(!(adding && vm.is_defunct()));
assert(vm.is_vol() && "This function is applicable only to volume mols and ignored for surface mols");
assert(vm.v.subpart_index != SUBPART_INDEX_INVALID);
assert(vm.v.reactant_subpart_index != SUBPART_INDEX_INVALID);
assert(vm.v.subpart_index == get_subpart_index(vm.v.pos) && "Position and subpart must match all the time");
BNG::Species& vm_species = get_species(vm.species_id);
if (!vm_species.has_bimol_vol_rxn()) {
return;
}
const BNG::ReactantClassIdSet& reacting_classes = get_all_rxns().get_reacting_classes(vm_species);
// we need to set/clear flag that says that second_reactant_info.first can react with reactant_species_id
for (const BNG::reactant_class_id_t reacting_class_id: reacting_classes) {
// can the second reactant initiate a reaction with me?
const BNG::ReactantClass& initiator_reactant_class = get_all_rxns().get_reactant_class(reacting_class_id);
if (initiator_reactant_class.target_only) {
// nothing to do
continue;
}
SubpartReactantsSet& second_reactant_sets_per_subpart =
volume_molecule_reactants_per_reactant_class.get_subparts_reactants_for_reactant_class(reacting_class_id);
if (removing) {
second_reactant_sets_per_subpart.erase_existing(vm.v.reactant_subpart_index, vm.id);
}
if (adding) {
second_reactant_sets_per_subpart.insert_unique(vm.v.subpart_index, vm.id);
}
}
// update the previous (reactant) to the current subpart index
vm.v.reactant_subpart_index = vm.v.subpart_index;
#ifdef DEBUG_EXTRA_CHECKS
// check that we don't have any defunct mols
if (!adding && removing) {
for (auto species_vec: volume_molecule_reactants_per_subpart) {
for (auto subpart_reactants: species_vec) {
for (molecule_id_t id: subpart_reactants) {
assert(!get_m(id).is_defunct());
}
}
}
}
#endif
}
void update_molecule_reactants_map(Molecule& vm) {
assert(vm.v.subpart_index < config.num_subparts);
assert(vm.v.reactant_subpart_index < config.num_subparts);
if (vm.v.subpart_index == vm.v.reactant_subpart_index) {
return; // nothing to do
}
#ifdef DEBUG_SUBPARTITIONS
std::cout << "Molecule " << vm.id << " changed subpartition from "
<< vm.v.reactant_subpart_index << " to " << vm.v.subpart_index << ".\n";
#endif
change_vol_reactants_map_from_orig_to_current(vm, true, true);
}
molecule_id_t get_next_molecule_id_no_increment() {
return next_molecule_id;
}
private:
// internal methods that sets molecule's id and adds it to all relevant structures,
// do not use species-id here because it may change
Molecule& add_molecule(const Molecule& m_copy, const bool is_vol, const double release_delay_time) {
#ifndef NDEBUG
const BNG::Species& species = get_species(m_copy.species_id);
assert((is_vol && species.is_vol()) || (!is_vol && species.is_surf()));
#endif
if (m_copy.id == MOLECULE_ID_INVALID) {
// assign new ID, in theory, molecule IDs should be assigned by World, but this
// is a common operation and some decentralized solution is needed
molecule_id_t molecule_id = next_molecule_id;
next_molecule_id++;
// We always have to increase the size of the mapping array - its size is
// large enough to hold ids for all molecules that were ever created,
// we will need to reuse ids or compress it later
molecule_index_t next_molecule_index = molecules.size(); // get the index of the molecule we are going to store
molecule_id_to_index_mapping.push_back(next_molecule_index);
assert(
molecule_id_to_index_mapping.size() == next_molecule_id
&& "Mapping array must have value for every molecule index"
);
// This is the only place where we insert molecules into volume_molecules,
// although this array size can be decreased in defragmentation
molecules.push_back(m_copy);
Molecule& new_m = molecules.back();
new_m.id = molecule_id;
// set to diffuse this or the next iteration,
// for releases - it will be diffused this iteration
// for new reaction products - it will be diffused next iteration because the DiffuseaAndReactEvent handles
// the current iteration
new_m.diffusion_time = stats.get_current_iteration() + release_delay_time;
return new_m;
}
else {
// this is a checkpointed molecule
// update the next molecule id counter
if (m_copy.id >= next_molecule_id) {
next_molecule_id = m_copy.id + 1;
}
// set its index in the molecule_id_to_index_mapping array
// its id must be at the position
uint32_t next_molecule_array_index = molecules.size(); // get the index of the molecule we are going to store
if (m_copy.id >= molecule_id_to_index_mapping.size()) {
// insert invalid indices up to the index specified by id
molecule_id_to_index_mapping.insert(
molecule_id_to_index_mapping.end(),
m_copy.id + 1 - molecule_id_to_index_mapping.size(),
MOLECULE_INDEX_INVALID
);
}
molecule_id_to_index_mapping[m_copy.id] = next_molecule_array_index;
// and append it to the molecules array
molecules.push_back(m_copy);
Molecule& new_m = molecules.back();
return new_m;
}
}
void update_species_for_new_molecule_and_add_to_schedulable_list(Molecule& m) {
// make sure that the rxn for this species flags are up-to-date
BNG::Species& sp = get_species(m.species_id);
if (!sp.are_rxn_and_custom_flags_uptodate()) {
sp.update_rxn_and_custom_flags(get_all_species(), get_all_rxns());
}
if (!sp.was_instantiated()) {
// update rxn classes for this new species, may create new species and
// invalidate Species reference
get_all_rxns().get_bimol_rxns_for_reactant(sp.id);
}
// we must get a new reference
get_species(m.species_id).inc_num_instantiations();
// also set a flag used for optimization
m.set_no_need_to_schedule_flag(bng_engine.get_all_species());
if (!m.has_flag(MOLECULE_FLAG_NO_NEED_TO_SCHEDULE)) {
schedulable_molecule_ids.push_back(m.id);
}
}
void update_compartment(Molecule& new_m, const BNG::compartment_id_t target_compartment_id) {
const BNG::Species& species = get_species(new_m.species_id);
// set compartment/define new species if needed, surface species may have only one surface compartment
BNG::compartment_id_t species_compartment_id = species.get_primary_compartment_id();
assert(!BNG::is_in_out_compartment_id(species_compartment_id));
// change only if it was not set
if (species_compartment_id != target_compartment_id) {
// desired compartment was not set or is set incorrectly, override
release_assert(target_compartment_id != BNG::COMPARTMENT_ID_NONE && "Not 100% sure whether this can occur");
new_m.species_id = get_all_species().get_species_id_with_compartment(new_m.species_id, target_compartment_id);
}
}
void update_volume_compartment(Molecule& new_vm) {
const BNG::Species& species = get_species(new_vm.species_id);
BNG::compartment_id_t target_compartment_id = get_compartment_id_for_counted_volume(new_vm.v.counted_volume_index);
assert(target_compartment_id == BNG::COMPARTMENT_ID_NONE ||
bng_engine.get_data().get_compartment(target_compartment_id).is_3d);
update_compartment(new_vm, target_compartment_id);
}
void update_surface_compartment(Molecule& new_sm) {
const Wall& w = get_wall(new_sm.s.wall_index);
const GeometryObject& o = get_geometry_object(w.object_index);
if (o.surf_compartment_id != BNG::COMPARTMENT_ID_NONE) {
BNG::compartment_id_t target_compartment_id = o.surf_compartment_id;
assert(!bng_engine.get_data().get_compartment(target_compartment_id).is_3d);
update_compartment(new_sm, target_compartment_id);
}
}
public:
// any molecule flags are set by caller after the molecule is created by this method
// molecule releases should use update_compartment = true,
// when a molecule is created by a reaction, the compartment is usually known and update_compartment may be false for efficiency
Molecule& add_volume_molecule(const Molecule& vm_copy, const double release_delay_time = 0) {
assert(vm_copy.is_vol());
// check that the molecule belongs to this partition
if (!in_this_partition(vm_copy.v.pos)) {
const BNG::Species& s = get_all_species().get(vm_copy.species_id);
errs() << "cannot create molecule of species '" << s.name << "' outside partition at location " << vm_copy.v.pos << ".\n";
exit(1);
}
// add a new molecule
Molecule& new_vm = add_molecule(vm_copy, true, release_delay_time);
// set subpart indices for vol-vol rxn handling
new_vm.v.subpart_index = get_subpart_index(new_vm.v.pos);
new_vm.v.reactant_subpart_index = new_vm.v.subpart_index;
// compute counted volume id for a new molecule, might be used to determine compartment
counted_volume_index_t counted_volume_index = new_vm.v.counted_volume_index;
if (new_vm.v.counted_volume_index == COUNTED_VOLUME_INDEX_INVALID) {
new_vm.v.counted_volume_index = compute_counted_volume_using_waypoints(new_vm.v.pos);
}
update_volume_compartment(new_vm);
// make sure that the rxn for this species flags are up-to-date and
// increment number of instantiations of this species
update_species_for_new_molecule_and_add_to_schedulable_list(new_vm);
// TODO: use Species::is_instantiated instead of the known_vol_species
if (known_vol_species.count(new_vm.species_id) == 0) {
// we must update reactant maps if new species were added,
// uses reactant_subpart_index of existing molecules
update_reactants_maps_for_new_species(new_vm.species_id, new_vm.id);
known_vol_species.insert(new_vm.species_id);
}
// and add this molecule to a map that tells which species can react with it
// might invalidate species references
change_vol_reactants_map_from_orig_to_current(new_vm, true, false);
return new_vm;
}
Molecule& add_surface_molecule(const Molecule& sm_copy, const double release_delay_time = 0) {
assert(sm_copy.is_surf() && sm_copy.s.wall_index != WALL_INDEX_INVALID);
Molecule& new_sm = add_molecule(sm_copy, false, release_delay_time);
// set compartment if needed
update_surface_compartment(new_sm);
update_species_for_new_molecule_and_add_to_schedulable_list(new_sm);
return new_sm;
}
void set_molecule_as_defunct(Molecule& m) {
// set that this molecule does not exist anymore
m.set_is_defunct();
BNG::Species& sp = get_species(m.species_id);
sp.dec_num_instantiations();
if (m.is_vol()) {
change_vol_reactants_map_from_orig_to_current(m, false, true);
}
// remove from grid if it was not already removed
if (m.is_surf() && m.s.grid_tile_index != TILE_INDEX_INVALID) {
Grid& g = get_wall(m.s.wall_index).grid;
g.reset_molecule_tile(m.s.grid_tile_index);
}
}
// ---------------------------------- molecule getters ----------------------------------
const Vec3& get_origin_corner() const {
return origin_corner;
}
const Vec3& get_opposite_corner() const {
return opposite_corner;
}
const MoleculeIdsSet& get_volume_molecule_reactants(subpart_index_t subpart_index, species_id_t species_id) const {
assert(subpart_index < config.num_subparts);
const BNG::Species& species = get_species(species_id);
return volume_molecule_reactants_per_reactant_class.
get_subparts_reactants_for_reactant_class(species.get_reactant_class_id()).get_contained_set(subpart_index);
}
const std::vector<Molecule>& get_molecules() const {
return molecules;
}
std::vector<Molecule>& get_molecules() {
return molecules;
}
std::vector<molecule_index_t>& get_molecule_id_to_index_mapping() {
return molecule_id_to_index_mapping;
}
const std::vector<molecule_index_t>& get_molecule_id_to_index_mapping() const {
return molecule_id_to_index_mapping;
}
std::vector<molecule_index_t>& get_schedulable_molecule_ids() {
return schedulable_molecule_ids;
}
// ---------------------------------- geometry ----------------------------------
vertex_index_t add_geometry_vertex(const Vec3 pos) {
vertex_index_t index = geometry_vertices.size();
geometry_vertices.push_back(pos);
return index;
}
vertex_index_t add_or_find_geometry_vertex(const Vec3 pos) {
// using exact comparison
auto it = std::find(geometry_vertices.begin(), geometry_vertices.end(), pos);
if (it == geometry_vertices.end()) {
return add_geometry_vertex(pos);
}
else {
return it - geometry_vertices.begin();
}
}
uint get_geometry_vertex_count() const {
return geometry_vertices.size();
}
const Vec3& get_geometry_vertex(vertex_index_t i) const {
assert(i < geometry_vertices.size());
return geometry_vertices[i];
}
Vec3& get_geometry_vertex(vertex_index_t i) {
assert(i < geometry_vertices.size());
return geometry_vertices[i];
}
const Vec3& get_wall_vertex(const Wall& w, uint vertex_in_wall_index) const {
assert(vertex_in_wall_index < VERTICES_IN_TRIANGLE);
vertex_index_t i = w.vertex_indices[vertex_in_wall_index];
assert(i < geometry_vertices.size());
return get_geometry_vertex(i);
}
region_index_t add_region_and_set_its_index(Region& reg) {
assert(reg.id != REGION_ID_INVALID);
region_index_t index = regions.size();
reg.index = index;
regions.push_back(reg);
return index;
}
// returns reference to the new wall, only sets id and index
Wall& add_uninitialized_wall(const wall_id_t id) {
wall_index_t index = walls.size();
walls.push_back(Wall(create_wall_shared_data(index)));
Wall& new_wall = walls.back();
new_wall.id = id;
new_wall.index = index;
return new_wall;
}
// when a wall is added with add_uninitialized_wall,
// its type and vertices are not know yet, we must include the walls
// into subpartitions and also for other purposes
void finalize_walls();
// returns reference to the new object, only sets id
GeometryObject& add_uninitialized_geometry_object(const geometry_object_id_t id) {
geometry_object_index_t index = geometry_objects.size();
geometry_objects.push_back(GeometryObject());
GeometryObject& new_obj = geometry_objects.back();
new_obj.id = id;
new_obj.index = index;
return new_obj;
}
GeometryObject& get_geometry_object(const geometry_object_index_t index) {
assert(index < geometry_objects.size());
return geometry_objects[index];
}
const GeometryObject& get_geometry_object(const geometry_object_index_t index) const {
assert(index < geometry_objects.size());
return geometry_objects[index];
}
GeometryObject& get_geometry_object_by_id(const geometry_object_id_t id) {
GeometryObject& res = get_geometry_object((geometry_object_index_t)id);
assert(res.id == res.index && "With a single partition, geom obj id must be the same as index");
return res;
}
const GeometryObject& get_geometry_object_by_id(const geometry_object_id_t id) const {
const GeometryObject& res = get_geometry_object((geometry_object_index_t)id);
assert(res.id == res.index && "With a single partition, geom obj id must be the same as index");
return res;
}
const GeometryObject* find_geometry_object(const std::string& name) const {
for (auto& go: geometry_objects) {
if (go.name == name) {
return &go;
}
}
return nullptr;
}
const GeometryObjectVector& get_geometry_objects() const {
return geometry_objects;
}
GeometryObjectVector& get_geometry_objects() {
return geometry_objects;
}
Region& get_region(const region_index_t index) {
assert(index < regions.size());
return regions[index];
}
const Region& get_region(const region_index_t index) const {
assert(index < regions.size());
return regions[index];
}
const std::vector<Region>& get_regions() const {
return regions;
}
const Region& get_region_by_id(const region_id_t id) const {
assert(id != REGION_ID_INVALID);
const Region& res = get_region((region_index_t)id);
assert(res.id == res.index && "With a single partition, region id == index");
return res;
}
Region& get_region_by_id(const region_id_t id) {
assert(id != REGION_ID_INVALID);
Region& res = get_region((region_index_t)id);
assert(res.id == res.index && "With a single partition, region id == index");
return res;
}
const GeometryObject* find_geometry_object_by_name(const std::string& name) const {
for (const GeometryObject& o: geometry_objects) {
if (o.name == name) {
return &o;
}
}
return nullptr;
}
const Region* find_region_by_name(const std::string& name) const {
for (const Region& r: regions) {
if (r.name == name) {
return &r;
}
}
return nullptr;
}
Region* find_region_by_name(const std::string& name) {
for (Region& r: regions) {
if (r.name == name) {
return &r;
}
}
return nullptr;
}
uint get_wall_count() const {
return walls.size();
}
const std::vector<Wall>& get_walls() const {
return walls;
}
std::vector<Wall>& get_walls() {
return walls;
}
const Wall& get_wall(const wall_index_t i) const {
assert(i < walls.size());
const Wall& res = walls[i];
assert(res.index == i && "Index of a wall must correspond to its position");
return res;
}
Wall& get_wall(const wall_index_t i) {
assert(i < walls.size());
Wall& res = walls[i];
assert(res.index == i && "Index of a wall must correspond to its position");
return res;
}
Wall* get_wall_if_exists(const wall_index_t i) {
if (i == WALL_INDEX_INVALID) {
return nullptr;
}
assert(i < walls.size());
Wall& res = walls[i];
assert(res.index == i && "Index of a wall must correspond to its position");
return &res;
}
const WallCollisionRejectionData& get_wall_collision_rejection_data(const wall_index_t i) const {
assert(i < wall_collision_rejection_data.size());
assert(wall_collision_rejection_data.size() == walls.size());
const WallCollisionRejectionData& res = wall_collision_rejection_data[i];
assert(res.has_identical_data_as_wall(walls[i]));
return res;
}
void update_wall_collision_rejection_data(const Wall& w) {
assert(w.index < wall_collision_rejection_data.size());
assert(wall_collision_rejection_data.size() == walls.size());
wall_collision_rejection_data[w.index] = w;
}
// maybe we will need to filter out, e.g. just reflective surfaces
const WallsInSubpart& get_subpart_wall_indices(const subpart_index_t subpart_index) const {
return walls_per_subpart[subpart_index];
}
// returns nullptr if either the wall does not exist or the wall's grid was not initialized
const Grid* get_wall_grid_if_exists(const wall_index_t wall_index) const {
if (wall_index == WALL_INDEX_INVALID) {
return nullptr;
}
const Wall& w = get_wall(wall_index);
if (!w.has_initialized_grid()) {
return nullptr;
}
return &w.grid;
}
const std::vector<wall_index_t>& get_walls_using_vertex(const vertex_index_t vertex_index) const {
assert(vertex_index != VERTEX_INDEX_INVALID);
assert(vertex_index < walls_using_vertex_mapping.size());
return walls_using_vertex_mapping[vertex_index];
}
BNG::compartment_id_t get_compartment_id_for_counted_volume(
const counted_volume_index_t counted_volume_index);
// ---------------------------------- dynamic vertices ----------------------------------
// may change the displacements in vertex_moves in some cases, do not use it afterwards
// returns a list of new vertex moves, the caller is responsible for deleting items
// in vertex_moves_due_to_paired_molecules
void apply_vertex_moves(
const bool randomize_order,
std::vector<VertexMoveInfo>& ordered_vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules);
void move_waypoint_because_positioned_on_wall(
const IVec3& waypoint_index, const bool reinitialize = true
);
WallSharedData* create_wall_shared_data() {
WallSharedData* res = new WallSharedData;
wall_shared_data.insert(res);
return res;
}
WallSharedData* create_wall_shared_data(const wall_index_t wi) {
WallSharedData* res = new WallSharedData;
res->shared_among_walls.push_back(wi);
wall_shared_data.insert(res);
return res;
}
void delete_wall_shared_data(WallSharedData* ptr) {
assert(wall_shared_data.count(ptr) != 0);
delete ptr;
wall_shared_data.erase(ptr);
}
private:
void clamp_vertex_moves_to_wall_wall_collisions(
std::vector<VertexMoveInfo*>& vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls);
void apply_vertex_moves_per_object(
const bool move_paired_walls,
std::vector<VertexMoveInfo*>& vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules);
void move_walls_with_paired_molecules(
const MoleculeIdsVector& paired_molecules,
const WallsWithTheirMovesMap& walls_with_their_moves,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules);
void update_walls_per_subpart(
const WallsWithTheirMovesMap& walls_with_their_moves, const bool insert
);
// automatically enlarges walls_using_vertex array
void add_wall_using_vertex_mapping(vertex_index_t vertex_index, wall_index_t wall_index) {
if (vertex_index >= walls_using_vertex_mapping.size()) {
walls_using_vertex_mapping.resize(vertex_index + 1);
}
walls_using_vertex_mapping[vertex_index].push_back(wall_index);
}
void initialize_waypoint(
const IVec3& waypoint_index,
const bool use_previous_waypoint,
const IVec3& previous_waypoint_index,
const bool keep_pos = false
);
public:
// ---------------------------------- other ----------------------------------
BNG::SpeciesContainer& get_all_species() { return bng_engine.get_all_species(); }
const BNG::SpeciesContainer& get_all_species() const { return bng_engine.get_all_species(); }
// helper methods to get directly a Species object
BNG::Species& get_species(const species_id_t id) { return bng_engine.get_all_species().get(id); }
const BNG::Species& get_species(const species_id_t id) const { return bng_engine.get_all_species().get(id); }
BNG::RxnContainer& get_all_rxns() { return bng_engine.get_all_rxns(); }
const BNG::RxnContainer& get_all_rxns() const { return bng_engine.get_all_rxns(); }
// ---------------------------------- counting ----------------------------------
// returns counted volume index for this position,
counted_volume_index_t compute_counted_volume_from_scratch(const Vec3& pos);
counted_volume_index_t compute_counted_volume_using_waypoints(const Vec3& pos);
void initialize_all_waypoints();
bool is_valid_waypoint_index(const IVec3& index3d) const {
return
index3d.x >= 0 &&
index3d.x < (int)waypoints.size() &&
index3d.y >= 0 &&
index3d.y < (int)waypoints[index3d.x].size() &&
index3d.z >= 0 &&
index3d.z < (int)waypoints[index3d.x][index3d.y].size();
}
Waypoint& get_waypoint(const IVec3& index3d) {
assert(is_valid_waypoint_index(index3d));
return waypoints[index3d.x][index3d.y][index3d.z];
}
const Waypoint& get_waypoint(const IVec3& index3d) const {
assert(is_valid_waypoint_index(index3d));
return waypoints[index3d.x][index3d.y][index3d.z];
}
counted_volume_index_t find_or_add_counted_volume(const CountedVolume& cv);
const CountedVolume& get_counted_volume(const counted_volume_index_t counted_volume_index) const {
assert(counted_volumes_vector.size() == counted_volumes_set.size());
assert(counted_volume_index < counted_volumes_vector.size());
assert(counted_volumes_vector[counted_volume_index].index == counted_volume_index);
return counted_volumes_vector[counted_volume_index];
}
void inc_rxn_in_volume_occured_count(
const BNG::rxn_rule_id_t rxn_id, const counted_volume_index_t counted_volume_index) {
assert(rxn_id != BNG::RXN_RULE_ID_INVALID);
// counted_volume_index may be invalid when we are counting reactions in the whole world
assert(counted_volume_index != COUNTED_VOLUME_INDEX_INVALID ||
!get_all_rxns().get(rxn_id)->is_counted_in_volume_regions()
);
auto& map_for_rxn = rxn_counts_per_counted_volume[rxn_id];
auto it_counted_volume = map_for_rxn.find(counted_volume_index);
if (it_counted_volume == map_for_rxn.end()) {
map_for_rxn[counted_volume_index] = 1;
}
else {
it_counted_volume->second++;
}
}
const CountInGeomObjectMap& get_rxn_in_volume_count_map(const BNG::rxn_rule_id_t rxn_rule_id) {
// creates a new map if it was not created before
return rxn_counts_per_counted_volume[rxn_rule_id];
}
void inc_rxn_on_surface_occured_count(const BNG::rxn_rule_id_t rxn_id, const wall_index_t wall_index) {
assert(rxn_id != BNG::RXN_RULE_ID_INVALID);
assert(wall_index != WALL_INDEX_INVALID);
auto& map_for_rxn = rxn_counts_per_wall_volume[rxn_id];
auto it_wall = map_for_rxn.find(wall_index);
if (it_wall == map_for_rxn.end()) {
map_for_rxn[wall_index] = 1;
}
else {
it_wall->second++;
}
}
const CountInGeomObjectMap& get_rxn_on_surface_count_map(const BNG::rxn_rule_id_t rxn_rule_id) {
// creates a new map if it was not created before
return rxn_counts_per_wall_volume[rxn_rule_id];
}
void remove_from_known_vol_species(const species_id_t species_id);
void remove_reactant_class_usage(const BNG::reactant_class_id_t reactant_class_id);
void shuffle_schedulable_molecule_ids();
// ------------ used directly by Pymcell4 API ------------
bool does_molecule_exist(const molecule_id_t id) {
if (id == MOLECULE_ID_INVALID) {
return false;
}
if (id >= molecule_id_to_index_mapping.size()) {
return false;
}
molecule_index_t index = molecule_id_to_index_mapping[id];
if (index == MOLECULE_INDEX_INVALID) {
return false;
}
return !get_m(id).is_defunct();
}
// the methods pair_molecules and unpair_molecules return a non-empty string
// if there was an error while adding/removing molecule pair
std::string pair_molecules(const molecule_id_t id1, const molecule_id_t id2);
std::string unpair_molecules(const molecule_id_t id1, const molecule_id_t id2);
// returns MOLECULE_ID_INVALID when the molecule is not paired
molecule_id_t get_paired_molecule(const molecule_id_t id) const;
std::map<molecule_id_t, molecule_id_t> get_paired_molecules() const {
return paired_molecules;
}
// --- diverse exports and dumps ---
void print_periodic_stats() const;
void dump(const bool with_geometry = false);
void to_data_model(Json::Value& mcell, std::set<rgba_t>& used_colors) const;
private:
// left, bottom, closest (lowest z) point of the partition
Vec3 origin_corner;
Vec3 opposite_corner;
// ---------------------------------- molecules ----------------------------------
// vector containing all molecules in this partition (volume and surface)
std::vector<Molecule> molecules;
// contains mapping of molecule ids to indices to the molecules array
std::vector<molecule_index_t> molecule_id_to_index_mapping;
// contains ids of molecules that need to be scheduled for diffusion or unimol rxn
// execution
std::vector<molecule_id_t> schedulable_molecule_ids;
// id of the next molecule to be created
// TODO_LATER: move to World
molecule_id_t next_molecule_id;
// indexed with species_id
ReactantClassSubpartReactantsSet volume_molecule_reactants_per_reactant_class;
// set that remembers which species we already saw, used to update
// volume_molecule_reactants_per_subpart when needed
std::set<species_id_t> known_vol_species;
// ---------------------------------- geometry objects ----------------------------------
std::vector<Vec3> geometry_vertices;
std::vector<GeometryObject> geometry_objects;
std::vector<Wall> walls;
// some wall data must be shared when walls are overlapping
// container for shared wall data, owned by partition
std::set<WallSharedData*> wall_shared_data;
// this is a copy of normal and distance from origin for fast wall collision rejection,
// stored in separate array to optimize cache performance in collide_wall
std::vector<WallCollisionRejectionData> wall_collision_rejection_data;
std::vector<Region> regions;
// indexed by vertex_index_t
std::vector< std::vector<wall_index_t>> walls_using_vertex_mapping;
// indexed by subpartition index, contains a container wall indices (wall_index_t)
std::vector< WallsInSubpart > walls_per_subpart;
// ---------------------------------- counting ------------------------------------------
// - key is rxn rule id and its values are maps that contain current reaction counts for each
// counted volume or wall
// - counts are 0 when resumed from a checkpoint because there is not easy way how to reconstruct
// these data from the last observables counts and it was much easier to store the previous counts
// in the MolOrRxnCountTerm object
std::map< BNG::rxn_rule_id_t, CountInGeomObjectMap > rxn_counts_per_counted_volume;
std::map< BNG::rxn_rule_id_t, CountOnWallMap > rxn_counts_per_wall_volume;
// indexed by counted_volume_index_t
std::vector<CountedVolume> counted_volumes_vector;
// set for fast search
std::set<CountedVolume> counted_volumes_set;
std::map<counted_volume_index_t, BNG::compartment_id_t> counted_volume_index_to_compartment_id_cache;
// indexed by [x][y][z]
std::vector< std::vector< std::vector< Waypoint > > > waypoints;
// bidirectional map -> each pair is added twice
std::map<molecule_id_t, molecule_id_t> paired_molecules;
// ---------------------------------- shared simulation configuration -------------------
public:
partition_id_t id;
// auxiliary random generator state
mutable rng_state aux_rng;
// all these reference an object owned by a single World instance
// enclose into something?
const SimulationConfig& config;
BNG::BNGEngine& bng_engine;
SimulationStats& stats;
};
typedef std::vector<Partition> PartitionVector;
} // namespace mcell
#endif // SRC4_PARTITION_H_
| Unknown |
3D | mcellteam/mcell | src4/base_event.cpp | .cpp | 967 | 32 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include "base_event.h"
using namespace std;
namespace MCell {
void BaseEvent::dump(const std::string ind) const {
cout << ind << "event_time: \t\t" << event_time << " [double] \t\t\n";
cout << ind << "periodicity_interval: \t\t" << periodicity_interval << " [double] \t\t\n";
cout << ind << "type_index: \t\t" << type_index << " [event_type_index_t] \t\t\n";
}
void BaseEvent::to_data_model(Json::Value& mcell_node) const {
// does nothing by default
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/region_utils.h | .h | 2,869 | 85 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_REGION_UTIL_H_
#define SRC4_REGION_UTIL_H_
#include "defines.h"
namespace MCell {
class Partition;
class Molecule;
namespace RegionUtils {
/* ALL_INSIDE: flag that indicates that all reactants lie inside their
* respective restrictive regions
* ALL_OUTSIDE: flag that indicates that all reactants lie outside
* their respective restrictive regions
* SURF1_IN_SURF2_OUT: flag that indicates that reactant "sm_1" lies
* inside and reactant "sm_2" lies outside of their
* respective restrictive regions
* SURF1_OUT_SURF2_IN: flag that indicates that reactant "sm_1" lies outside
* and reactant "sm_2" lies inside of their
* respective restrictive regions
* SURF1_IN: flag that indicates that only reactant "sm_1" has
* restrictive regions on the object and it lies
* inside its restrictive region.
* SURF1_OUT: flag that indicates that only reactant "sm_1" has
* restrictive regions on the object and it lies
* outside its restrictive region.
* SURF2_IN: flag that indicates that only reactant "sm_2" has
* restrictive regions on the object and it lies
* inside its restrictive region.
* SURF2_OUT: flag that indicates that only reactant "sm_2" has
* restrictive regions on the object and it lies
* outside its restrictive region. */
enum surf_mol_region_relationship_flag_t {
ALL_INSIDE = 0x01,
ALL_OUTSIDE = 0x02,
SURF1_IN_SURF2_OUT = 0x04,
SURF1_OUT_SURF2_IN = 0x08,
SURF1_IN = 0x10,
SURF1_OUT = 0x20,
SURF2_IN = 0x40,
SURF2_OUT = 0x80
};
// returns flags composed of surf_mol_region_relationship_flag_t
uint determine_molecule_region_topology(
Partition& p,
const Molecule* reacA,
const Molecule* reacB,
const bool is_unimol,
RegionIndicesSet& rlp_wall_1,
RegionIndicesSet& rlp_wall_2,
RegionIndicesSet& rlp_obj_1,
RegionIndicesSet& rlp_obj_2);
bool product_tile_can_be_reached(
const Partition& p,
const wall_index_t wall_index,
const bool is_unimol,
const uint sm_bitmask,
const RegionIndicesSet& rlp_wall_1,
const RegionIndicesSet& rlp_wall_2,
const RegionIndicesSet& rlp_obj_1,
const RegionIndicesSet& rlp_obj_2);
} // namespace RegionUtil
} // namespace MCell
#endif // SRC4_REGION_UTIL_H_
| Unknown |
3D | mcellteam/mcell | src4/wall_overlap.cpp | .cpp | 12,445 | 399 | /******************************************************************************
*
* Copyright (C) 2006-2017,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* The triangle overlap code in this file is based on the triangle/triangle
* intersection test routine by by Tomas Moller, 1997.
*
* See article "A Fast Triangle-Triangle Intersection Test",
* Journal of Graphics Tools, 2(2), 1997
*
* In contrast to Moller's general triangle-triangle intersection routine
* our code only tests for area overlap of coplanar triangles.
* In particular it will treat triangles which share an edge or vertex as
* non-overlapping. Only triangles with a bona-fide area overlap will be
* flagged.
*
* The code returns 1 if the provided triangles have an area overlap and 0
* otherwise.
*/
#include "geometry.h"
#include "partition.h"
using namespace std;
namespace MCell {
namespace WallOverlap {
#include "wall_overlap.h"
/******************************************************************
are_walls_coplanar:
In: first wall
second wall
accuracy of the comparison
Out: 1 if the walls are coplanar
0 if walls are not coplanar
Note: see "Real-time rendering" 2nd Ed., by Tomas Akenine-Moller and
Eric Haines, pp. 590-591
******************************************************************/
static bool are_coplanar(const Partition& p, const Wall& w1, const Wall& w2, const pos_t eps) {
/* find the plane equation of the second wall in the form (n*x + d2 = 0) */
pos_t d2, d1_0, d1_1, d1_2;
const Vec3 w2_vert0 = p.get_wall_vertex(w2, 0);
const Vec3 w1_vert0 = p.get_wall_vertex(w1, 0);
const Vec3 w1_vert1 = p.get_wall_vertex(w1, 1);
const Vec3 w1_vert2 = p.get_wall_vertex(w1, 2);
d2 = -dot(w2.normal, w2_vert0);
/* check whether all vertices of the first wall satisfy
plane equation of the second wall */
d1_0 = dot(w2.normal, w1_vert0) + d2;
d1_1 = dot(w2.normal, w1_vert1) + d2;
d1_2 = dot(w2.normal, w1_vert2) + d2;
if ((!distinguishable_f(d1_0, 0, eps)) && (!distinguishable_f(d1_1, 0, eps)) &&
(!distinguishable_f(d1_2, 0, eps))) {
return true;
}
return false;
}
/*******************************************************************
are_walls_coincident:
In: first wall
second wall
accuracy of the comparison
Out: 0 if the walls are not coincident
1 if the walls are coincident
*******************************************************************/
static bool are_coincident(const Partition& p, const Wall& w1, const Wall& w2, const pos_t eps) {
int count = 0;
for (uint w1_vert = 0; w1_vert < VERTICES_IN_TRIANGLE; w1_vert++) {
for (uint w2_vert = 0; w2_vert < VERTICES_IN_TRIANGLE; w2_vert++) {
if (!distinguishable_vec3(
p.get_wall_vertex(w1, w1_vert), p.get_wall_vertex(w2, w2_vert), eps)) {
count++;
}
}
}
if (count >= 3)
return 1;
return 0;
}
/* this edge to edge test is based on Franlin Antonio's gem:
* "Faster Line Segment Intersection", in Graphics Gems III,
* pp. 199-202 */
static bool edge_edge_test(
const Vec3& v0, const Vec3& u0, const Vec3& u1,
uint i0, uint i1,
pos_t Ax, pos_t Ay) {
pos_t Bx = u0[i0] - u1[i0];
pos_t By = u0[i1] - u1[i1];
pos_t Cx = v0[i0] - u0[i0];
pos_t Cy = v0[i1] - u0[i1];
pos_t f = Ay * Bx - Ax * By;
pos_t d = By * Cx - Bx * Cy;
if ((f > 0 && d >= 0 && d <= f) || (f < 0 && d <= 0 && d >= f)) {
pos_t e = Ax * Cy - Ay * Cx;
// ignore edge or vertex overlaps
bool dz = !distinguishable_f(d, 0.0, POS_EPS);
bool ez = !distinguishable_f(e, 0.0, POS_EPS);
bool df = !distinguishable_f(d, f, POS_EPS);
bool ef = !distinguishable_f(e, f, POS_EPS);
if ((dz && ez) || (dz && ef) || (df && ez) || (df && ef)) {
return false;
}
if (f > 0) {
if (e >= 0 && e <= f) {
return true;
}
}
else {
if (e <= 0 && e >= f) {
return true;
}
}
}
return false;
}
/* edge_against_tri_edges tests if edge v0v1 intersects with any edge of
* triangle u0u1u2 */
static inline bool edge_against_tri_edges(
const Vec3& v0, const Vec3& v1, const Vec3& u0,
const Vec3& u1, const Vec3& u2, uint i0,
uint i1) {
pos_t Ax = v1[i0] - v0[i0];
pos_t Ay = v1[i1] - v0[i1];
/* test edge u0,u1 against v0,v1 */
if (edge_edge_test(v0, u0, u1, i0, i1, Ax, Ay)) {
return true;
}
/* test edge u1,u2 against v0,v1 */
if (edge_edge_test(v0, u1, u2, i0, i1, Ax, Ay)) {
return true;
};
/* test edge u2,u1 against v0,v1 */
if (edge_edge_test(v0, u2, u0, i0, i1, Ax, Ay)) {
return true;
}
return false;
}
/* point_in_tri tests if point v0 is contained in triangle u0u1u2 */
static bool point_in_tri(const Vec3& v0, const Vec3& u0, const Vec3& u1, const Vec3& u2,
uint i0, uint i1) {
/* is T1 completly inside T2? */
/* check if v0 is inside tri(u0,u1,u2) */
pos_t a = u1[i1] - u0[i1];
pos_t b = -(u1[i0] - u0[i0]);
pos_t c = -a * u0[i0] - b * u0[i1];
pos_t d0 = a * v0[i0] + b * v0[i1] + c;
a = u2[i1] - u1[i1];
b = -(u2[i0] - u1[i0]);
c = -a * u1[i0] - b * u1[i1];
pos_t d1 = a * v0[i0] + b * v0[i1] + c;
a = u0[i1] - u2[i1];
b = -(u0[i0] - u2[i0]);
c = -a * u2[i0] - b * u2[i1];
pos_t d2 = a * v0[i0] + b * v0[i1] + c;
if (d0 * d1 > 0.0) {
if (d0 * d2 > 0.0) return true;
}
return false;
}
/* coplanar_tri_tri checks if triangles v0v1v2 and u0u1u2 have area overlap. */
static bool coplanar_tri_tri(
const Vec3& n,
const Vec3& v0, const Vec3& v1, const Vec3& v2,
const Vec3& u0, const Vec3& u1, const Vec3& u2) {
uint i0, i1;
/* first project onto an axis-aligned plane, that maximizes the area */
/* of the triangles, compute indices: i0,i1. */
Vec3 a = abs3(n);
if (a.x > a.y) {
if (a.x > a.z) {
i0 = 1; /* a.x is greatest */
i1 = 2;
} else {
i0 = 0; /* a.z is greatest */
i1 = 1;
}
} else /* a.x<=a.y */
{
if (a.z > a.y) {
i0 = 0; /* a.z is greatest */
i1 = 1;
} else {
i0 = 0; /* a.y is greatest */
i1 = 2;
}
}
/* test all edges of triangle 1 against the edges of triangle 2 */
if (edge_against_tri_edges(v0, v1, u0, u1, u2, i0, i1) ||
edge_against_tri_edges(v1, v2, u0, u1, u2, i0, i1) ||
edge_against_tri_edges(v2, v0, u0, u1, u2, i0, i1)) {
return true;
}
/* finally, test if tri1 is totally contained in tri2 or vice versa */
if (point_in_tri(v0, u0, u1, u2, i0, i1) ||
point_in_tri(u0, v0, v1, v2, i0, i1)) {
return true;
}
return false;
}
/* coplanar_tri_operlap tests if w1 and w2 overlap and returns 1 if yes
* and 0 otherwise.
*
* NOTE 1: w1 and w2 are assumed to be coplanar.
* NOTE 2: this function will only return 1 if w1 and w2 have a bona
* fide area overlap. If w1 and w2 share an edge or vertex
* this will *not* be treated as an overlap.
*/
static bool coplanar_walls_overlap(const Partition& p, const Wall& w1, const Wall& w2) {
assert(are_coplanar(p, w1, w2, POS_EPS));
const Vec3& v0 = p.get_wall_vertex(w1, 0);
const Vec3& v1 = p.get_wall_vertex(w1, 1);
const Vec3& v2 = p.get_wall_vertex(w1, 2);
const Vec3& u0 = p.get_wall_vertex(w2, 0);
const Vec3& u1 = p.get_wall_vertex(w2, 1);
const Vec3& u2 = p.get_wall_vertex(w2, 2);
/* plane equation 1: N1.X+d1=0 */
return coplanar_tri_tri(w1.normal, v0, v1, v2, u0, u1, u2);
}
static uint get_num_same_vertex_coords(const Partition& p, const Wall& w1, const Wall& w2) {
// assuming no vertices for one wall are identical
uint num_same = 0;
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
const Vec3& v1 = p.get_wall_vertex(w1, i);
for (uint k = 0; k < VERTICES_IN_TRIANGLE; k++) {
const Vec3& v2 = p.get_wall_vertex(w2, k);
if (v1 == v2) {
num_same++;
}
}
}
return num_same;
}
static void merge_walls(Partition& p, Wall& w1, Wall& w2) {
release_assert(w1.wall_shared_data != w2.wall_shared_data
&& "Cannot merge already merged walls");
// which one is primary?
GeometryObject& o1 = p.get_geometry_object(w1.object_index);
GeometryObject& o2 = p.get_geometry_object(w2.object_index);
if (!o1.is_fully_transparent && !o2.is_fully_transparent) {
errs() << "Cannot allow overlapped wall because neither object '" << o1.name << "' nor '" <<
o2.name << "' is fully transparent (does not have a transparent surface class for all molecules). " <<
"Error for: wall side " << w1.side << " from '" << o1.name << "' and wall side " << w2.side << " from '" << o2.name << ".\n";
exit(1);
}
WallSharedData* shared_data = p.create_wall_shared_data();
// merge in the right order so that the primary wall is listed as the first one
// if both are fully transparent, order does not matter
if (o1.is_fully_transparent) {
shared_data->merge_initial_wall_data(w2.wall_shared_data);
shared_data->merge_initial_wall_data(w1.wall_shared_data);
// mark o1 as being overlapped
o1.has_overlapped_walls = true;
}
else {
shared_data->merge_initial_wall_data(w1.wall_shared_data);
shared_data->merge_initial_wall_data(w2.wall_shared_data);
// mark o2 as being overlapped
o2.has_overlapped_walls = true;
}
p.delete_wall_shared_data(w1.wall_shared_data);
p.delete_wall_shared_data(w2.wall_shared_data);
w1.wall_shared_data = shared_data;
w2.wall_shared_data = shared_data;
}
bool check_for_overlapped_walls(Partition& p, const Vec3& rand_vec) {
typedef pair<wall_index_t, double> WallDprodPair;
vector<WallDprodPair> wall_indices_w_dprod;
for (const Wall& w: p.get_walls()) {
double d_prod = dot(rand_vec, w.normal);
/* we want to place walls with opposite normals into
neighboring positions in the sorted list */
if (d_prod < 0) {
d_prod = -d_prod;
}
wall_indices_w_dprod.push_back(make_pair(w.index, d_prod));
}
// sort according to dprod
sort(wall_indices_w_dprod.begin(), wall_indices_w_dprod.end(),
[](const WallDprodPair& a, const WallDprodPair& b) -> bool {
return a.second < b.second;
}
);
for (size_t i = 0; i < wall_indices_w_dprod.size(); i++) {
WallDprodPair& wd = wall_indices_w_dprod[i];
Wall& w1 = p.get_wall(wd.first);
size_t next_index = i + 1;
while (next_index < wall_indices_w_dprod.size() &&
(!distinguishable_f(wd.second, wall_indices_w_dprod[next_index].second, EPS))) {
/* there may be several walls with the same (or mirror) oriented normals */
Wall& w2 = p.get_wall(wall_indices_w_dprod[next_index].first);
if (WallOverlap::are_coplanar(p, w1, w2, MESH_DISTINCTIVE_EPS) &&
(WallOverlap::are_coincident(p, w1, w2, MESH_DISTINCTIVE_EPS) ||
WallOverlap::coplanar_walls_overlap(p, w1, w2))
) {
// check for a shared wall
uint num_same = get_num_same_vertex_coords(p, w1, w2);
if (num_same == 2) {
// ok, allowed
}
else if (num_same == 3) {
const string& obj1_name = p.get_geometry_object(w1.object_id).name;
const string& obj2_name = p.get_geometry_object(w2.object_id).name;
if (p.config.wall_overlap_report) {
notifys() << "wall overlap: wall side " << w1.side << " from '" << obj1_name <<
"' overlaps wall side " << w2.side << " from '" << obj2_name <<
"'.\n";
}
merge_walls(p, w1, w2);
}
else {
const string& obj1_name = p.get_geometry_object(w1.object_id).name;
const string& obj2_name = p.get_geometry_object(w2.object_id).name;
errs() << "walls are overlapped: wall side " << w1.side << " from '" << obj1_name <<
"' overlaps wall side " << w2.side << " from '" << obj2_name <<
"', the only overlapping walls that are allowed are those that have the same vertex coordinates.\n";
return false;
}
}
next_index++;
}
}
return true;
}
} // namespace WallOverlap
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/wall.cpp | .cpp | 13,128 | 458 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include "bng/bng.h"
#include "rng.h" // MCell 3
#include "isaac64.h"
#include "mcell_structs_shared.h"
#include "logging.h"
#include "wall_util.h"
#include "partition.h"
#include "geometry.h"
#include "release_event.h"
#include "datamodel_defines.h"
#include "geometry_utils.h"
#include "geometry_utils.inl" // uses get_wall_bounding_box, maybe not include this file
#include "collision_utils.inl"
#include "dump_state.h"
using namespace std;
namespace MCell {
// may be also used for reinitialization
void Grid::initialize(const Partition& p, const Wall& w) {
if (is_initialized()) {
// keep the same number of items
#ifndef NDEBUG
small_vector<molecule_id_t> molecule_ids;
get_contained_molecules(molecule_ids);
assert(molecule_ids.size() == num_occupied);
#endif
}
else {
num_occupied = 0;
}
num_tiles_along_axis = (int)ceil_p(sqrt_p(w.area));
if (num_tiles_along_axis < 1) {
num_tiles_along_axis = 1;
}
num_tiles = num_tiles_along_axis * num_tiles_along_axis;
molecules_per_tile.resize(num_tiles, MOLECULE_ID_INVALID);
strip_width_rcp = 1 / (w.uv_vert2.v / ((pos_t)num_tiles_along_axis));
vert2_slope = w.uv_vert2.u / w.uv_vert2.v;
fullslope = w.uv_vert1_u / w.uv_vert2.v;
binding_factor = ((pos_t)num_tiles) / w.area;
const Vec3& vert0_tmp = p.get_wall_vertex(w, 0);
vert0.u = dot(vert0_tmp, w.unit_u);
vert0.v = dot(vert0_tmp, w.unit_v);
assert(w.index != WALL_INDEX_INVALID);
wall_index = w.index;
}
// populates array molecules with ids of molecules belonging to this grid
void Grid::get_contained_molecules(
small_vector<molecule_id_t>& molecule_ids
) const {
// might be optimized by retaining a vector/set that gets invalidated if anything changes
molecule_ids.clear();
for (molecule_id_t id: molecules_per_tile) {
if (id != MOLECULE_ID_INVALID) {
molecule_ids.push_back(id);
}
}
}
void Grid::dump() const {
// dumping just occupied locations and base info for now
cout << "Grid: num_tiles: " << num_tiles << ", num_occupied: " << num_occupied << "\n";
for (uint i = 0; i < molecules_per_tile.size(); i++) {
molecule_id_t id = molecules_per_tile[i];
if (id != MOLECULE_ID_INVALID) {
cout << "[" << i << "]" << id << "\n";
}
}
}
static std::string get_wall_details(const Partition& p, const Wall& w) {
stringstream ss;
ss << "Wall side " << w.side << " has vertex coordinates " <<
p.get_wall_vertex(w, 0) * Vec3(p.config.length_unit) << ", " <<
p.get_wall_vertex(w, 1) * Vec3(p.config.length_unit) << ", "<<
p.get_wall_vertex(w, 2) * Vec3(p.config.length_unit) <<
" and area " << w.area * pow(p.config.length_unit, 2) << " (in um and um^2).";
return ss.str();
}
static void report_malformed_geom_object_and_exit(const Partition& p, const Wall& wf, const Wall& wb) {
const GeometryObject& o = p.get_geometry_object(wb.object_index);
errs() << "Detected malformed geometry object '" << o.name << "'. " <<
"A possible cause is that two vertices of the same object share the same location or a wall became very thin (like a line).\n" <<
"Error detected for walls with side indices " << wf.side << " and " << wb.side << ".\n" <<
get_wall_details(p, wf) << "\n" <<
get_wall_details(p, wb) << "\n" <<
"Terminating because this issue would lead to simulation errors.\n";
exit(1);
}
/***************************************************************************
init_edge_transform
In: e: pointer to an edge
edgenum: integer telling which edge (0-2) of the "forward" face we are
Out: No return value. Coordinate transform in edge struct is set.
Note: Don't call this on a non-shared edge.
***************************************************************************/
void Edge::reinit_edge_constants(const Partition& p) {
assert(is_shared_edge());
if (!is_initialized()) {
return;
}
Wall wf = p.get_wall(forward_index);
Wall wb = p.get_wall(backward_index);
#ifdef DEBUG_EDGE_INITIALIZATION
std::cout << "Edge initialization, edgenum: " << edge_num_used_for_init << "\n";
wf.dump(p, "", true);
wb.dump(p, "", true);
#endif
// edge_num_used_for_init is set in surface_net when object is initialized
edge_index_t i = edge_num_used_for_init;
assert(i < VERTICES_IN_TRIANGLE);
edge_index_t j = i + 1;
if (j == VERTICES_IN_TRIANGLE) {
j = 0;
}
const Vec3& wf_vert_0 = p.get_geometry_vertex(wf.vertex_indices[0]);
const Vec3& wf_vert_i = p.get_geometry_vertex(wf.vertex_indices[i]);
const Vec3& wf_vert_j = p.get_geometry_vertex(wf.vertex_indices[j]);
const Vec3& wb_vert_0 = p.get_geometry_vertex(wb.vertex_indices[0]);
/* Intermediate basis from the perspective of the forward frame */
Vec3 diff_i_0 = wf_vert_i - wf_vert_0;
Vec2 O_f;
O_f.u = dot(diff_i_0, wf.unit_u); // should be called after wall init
O_f.v = dot(diff_i_0, wf.unit_v); /* Origin */
Vec3 diff_j_0 = wf_vert_j - wf_vert_0;
Vec2 temp_ff;
temp_ff.u = dot(diff_j_0, wf.unit_u) - O_f.u;
temp_ff.v = dot(diff_j_0, wf.unit_v) - O_f.v; /* Far side of e */
if (cmp_eq(len2_squared(temp_ff), (pos_t)0, POS_EPS)) {
report_malformed_geom_object_and_exit(p, wf, wb);
}
pos_t d_f = 1 / len2(temp_ff);
Vec2 ehat_f, fhat_f;
ehat_f = temp_ff * d_f; /* ehat along edge */
fhat_f.u = -ehat_f.v;
fhat_f.v = ehat_f.u; /* fhat 90 degrees CCW */
/* Intermediate basis from the perspective of the backward frame */
Vec3 diff_i_b0 = wf_vert_i - wb_vert_0;
Vec2 O_b;
O_b.u = dot(diff_i_b0, wb.unit_u);
O_b.v = dot(diff_i_b0, wb.unit_v); /* Origin */
Vec3 diff_j_b0 = wf_vert_j - wb_vert_0;
Vec2 temp_fb;
temp_fb.u = dot(diff_j_b0, wb.unit_u) - O_b.u;
temp_fb.v = dot(diff_j_b0, wb.unit_v) - O_b.v; /* Far side of e */
if (cmp_eq(len2_squared(temp_fb), (pos_t)0, POS_EPS)) {
report_malformed_geom_object_and_exit(p, wf, wb);
}
pos_t d_b = 1 / len2(temp_fb);
Vec2 ehat_b, fhat_b;
ehat_b = temp_fb * d_b; /* ehat along edge */
fhat_b.u = -ehat_b.v;
fhat_b.v = ehat_b.u; /* fhat 90 degrees CCW */
/* Calculate transformation matrix */
pos_t mtx[2][2];
mtx[0][0] = ehat_f.u * ehat_b.u + fhat_f.u * fhat_b.u;
mtx[0][1] = ehat_f.v * ehat_b.u + fhat_f.v * fhat_b.u;
mtx[1][0] = ehat_f.u * ehat_b.v + fhat_f.u * fhat_b.v;
mtx[1][1] = ehat_f.v * ehat_b.v + fhat_f.v * fhat_b.v;
/* Calculate translation vector */
Vec2 q;
q = O_b;
q.u -= mtx[0][0] * O_f.u + mtx[0][1] * O_f.v;
q.v -= mtx[1][0] * O_f.u + mtx[1][1] * O_f.v;
/* Store the results */
cos_theta = mtx[0][0];
sin_theta = mtx[0][1];
translate = q;
#ifdef DEBUG_EDGE_INITIALIZATION
dump();
#endif
}
void Edge::debug_check_values_are_uptodate(const Partition& p) {
if (!is_initialized()) {
return;
}
#ifndef NDEBUG
Vec2 orig_translate = translate;
#endif
pos_t orig_cos_theta = cos_theta;
pos_t orig_sin_theta = sin_theta;
#ifdef DEBUG_EDGE_INITIALIZATION
dump();
#endif
reinit_edge_constants(p);
#ifdef DEBUG_EDGE_INITIALIZATION
dump();
#endif
assert(cmp_eq(orig_translate, translate));
assert(cmp_eq(orig_cos_theta, cos_theta));
assert(cmp_eq(orig_sin_theta, sin_theta));
}
void Edge::dump(const std::string ind) const {
Vec2 translate_rounded;
translate_rounded.x = (translate.x < POS_EPS) ? 0 : translate.x;
translate_rounded.y = (translate.y < POS_EPS) ? 0 : translate.y;
cout << ind <<
"Edge: "
"forward_index: " << forward_index <<
", backward_index: " << backward_index <<
", translate: " << translate_rounded <<
", cos_theta: " << ((cos_theta < POS_EPS) ? 0 : cos_theta) <<
", sin_theta: " << ((sin_theta < POS_EPS) ? 0 : sin_theta) <<
", edge_num_used_for_init: " << edge_num_used_for_init << "\n";
}
void WallSharedData::merge_initial_wall_data(const WallSharedData* wsd) {
shared_among_walls.insert(
shared_among_walls.end(), wsd->shared_among_walls.begin(), wsd->shared_among_walls.end());
}
void Wall::initialize_wall_constants(const Partition& p) {
const Vec3* v0;
const Vec3* v1;
const Vec3* v2;
if (exists_in_partition()) {
v0 = &p.get_geometry_vertex(vertex_indices[0]);
v1 = &p.get_geometry_vertex(vertex_indices[1]);
v2 = &p.get_geometry_vertex(vertex_indices[2]);
}
else {
WallWithVertices* wall_w_vertices = static_cast<WallWithVertices*>(this);
assert(wall_w_vertices != nullptr);
v0 = &wall_w_vertices->vertices[0];
v1 = &wall_w_vertices->vertices[1];
v2 = &wall_w_vertices->vertices[2];
}
Vec3 vA, vB, vX;
vA = *v1 - *v0;
vB = *v2 - *v0;
vX = cross(vA, vB);
area = 0.5 * len3(vX);
if (!distinguishable_f(area, 0, EPS)) {
/* this is a degenerate polygon.
* perform initialization and quit. */
normal = Vec3(0);
unit_u = Vec3(0);
unit_v = Vec3(0);
uv_vert1_u = 0;
uv_vert2 = Vec2(0);
distance_to_origin = 0;
return;
}
Vec3 f1 = *v1 - *v0;
pos_t f1_len_squared = len3_squared(f1);
assert(f1_len_squared != 0);
pos_t inv_f1_len = 1 / sqrt_p(f1_len_squared);
unit_u = f1 * Vec3(inv_f1_len);
Vec3 f2 = *v2 - *v0;
normal = cross(unit_u, f2);
pos_t norm_len_squared = len3_squared(normal);
assert(norm_len_squared != 0);
pos_t inv_norm_len = 1 / sqrt_p(norm_len_squared);
normal = normal * Vec3(inv_norm_len);
unit_v = cross(normal, unit_u);
distance_to_origin = dot(*v0, normal);
uv_vert1_u = dot(f1, unit_u);
uv_vert2.u = dot(f2, unit_u);
uv_vert2.v = dot(f2, unit_v);
wall_constants_initialized = true;
}
void Wall::initialize_edge_constants(const Partition& p) {
// edges, uses info set by init_tri_wall
for (uint edge_index = 0; edge_index < EDGES_IN_TRIANGLE; edge_index++) {
if (edges[edge_index].is_shared_edge()) {
edges[edge_index].reinit_edge_constants(p);
}
}
}
void Wall::dump(const Partition& p, const std::string ind, const bool for_diff) const {
if (for_diff) {
cout << "wall[side: " << side << "]: ";
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
vertex_index_t vertex_index = vertex_indices[i];
Vec3 pos = p.get_geometry_vertex(vertex_index);
cout << pos;
if (i != VERTICES_IN_TRIANGLE - 1) {
cout << ", ";
}
}
cout << "\n";
}
else {
cout << ind <<
"id: " << id << ", index: " << index << ", side: " << side <<
", object_id: " << object_id << ", object_index: " << object_index << "\n";
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
vertex_index_t vertex_index = vertex_indices[i];
Vec3 pos = p.get_geometry_vertex(vertex_index);
cout << ind << "vertex_index: " << vertex_index << ":" << pos << "\n";
}
cout << ind << "edges:\n";
for (uint i = 0; i < EDGES_IN_TRIANGLE; i++) {
cout << ind << i << ":\n";
edges[i].dump(ind + " ");
}
cout << ind;
for (uint i = 0; i < EDGES_IN_TRIANGLE; i++) {
cout << "nb_walls[" << i << "]: " << nb_walls[i] << ", ";
}
cout << "\n";
cout << ind << "regions: ";
for (region_index_t i: regions) {
cout << i << ", ";
}
cout << "\n";
cout << ind
<< "uv_vert1_u: " << uv_vert1_u
<< ", uv_vert2: " << uv_vert2
<< ", area: " << area
<< ", normal: " << normal << "\n";
cout << ind
<< "unit_u: " << unit_u
<< ", unit_v: " << unit_v
<< ", distance_to_origin: " << distance_to_origin
<< "\n";
}
}
/***************************************************************************
create_region_bbox:
In: a region
Out: LLF and URB corners of a bounding box around the region
***************************************************************************/
void Region::compute_bounding_box(const Partition& p, Vec3& llf, Vec3& urb) {
bool found_first_wall = false;
for (auto it: walls_and_edges) {
const Wall& w = p.get_wall(it.first);
const Vec3* verts[VERTICES_IN_TRIANGLE];
verts[0] = &p.get_wall_vertex(w, 0);
verts[1] = &p.get_wall_vertex(w, 1);
verts[2] = &p.get_wall_vertex(w, 2);
if (!found_first_wall) {
llf = *verts[0];
urb = *verts[0];
found_first_wall = true;
}
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
const Vec3* v = verts[i];
if (llf.x > v->x) {
llf.x = v->x;
}
else if (urb.x < v->x) {
urb.x = v->x;
}
if (llf.y > v->y) {
llf.y = v->y;
}
else if (urb.y < v->y) {
urb.y = v->y;
}
if (llf.z > v->z) {
llf.z = v->z;
}
else if (urb.z < v->z) {
urb.z = v->z;
}
}
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/defines.h | .h | 24,014 | 835 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_DEFINES_H_
#define SRC4_DEFINES_H_
#include <stdint.h>
#include <vector>
#include <set>
#include <string>
#include <cassert>
#include <climits>
#include <cmath>
#include <iostream>
#include <map>
#include <unordered_map>
#include "mcell_structs_shared.h"
#include "debug_config.h"
// warning: do not use floating point types from directly,
// we need to be able to control the precision
#include "../libs/glm/glm.hpp"
#define GLM_ENABLE_EXPERIMENTAL
#include "../libs/glm/gtx/component_wise.hpp"
#include "bng/shared_defines.h" // may define INDEXER_WA
#if defined(NDEBUG) && defined(INDEXER_WA)
#warning "INDEXER_WA is enabled and this will lead to lower performance"
#endif
#ifndef INDEXER_WA
#include <boost/container/small_vector.hpp>
#include <boost/container/flat_set.hpp>
#endif
// this file must not depend on any other from mcell4 otherwise there
// might be some nasty cyclic include dependencies
/**
* Usage of IDs and indexes:
*
* ID - world-unique identifier of an object
* Index -partition-unique identifier of an object
*
* Why use indices instead of pointers:
* - Having a value that is independent on actual position in memory can be beneficial,
* this way, we can migrate the data to a different piece of memory and the index will be still valid
*
* - Do we really need to move data? - Yes
* - Growing arrays get reallocated
* - Defragmentation of molecule arrays
*
* Use only IDs?
* - This would mean that for every access, we need to use indirection, might be cheap, but also might
* block some superscalar executions...
* - Also, every type of object would have its own mapping array for all the possible IDs
* in each partition
*
* What about cases when a wall changes its partition?
* - If I hold just its index, I cannot know that it has moved.
*
* Go back to single partition? Do not think about multicore execution for now?
* - Single partition system won't need to use indices, just IDs
* - However, ids do not allow for defragmentation without fixing up all existing references
*
* Keep the implementation it as it is for now? - Yes
* - molecules use ids, everything else uses indices
* - refactor once we will have a good reason to do it - e.g. initially we might now want to allow walls to cross partitions
*
* Another approach:
* - Id + index for everything that can change?
* - Id for everything that does not change?
*
*/
namespace MCell {
// import shared declarations from BNG into our own namespace
using BNGCommon::f_to_str;
using BNGCommon::EPS;
using BNGCommon::SQRT_EPS;
using BNGCommon::DBL_GIGANTIC;
using BNGCommon::pos_t;
using BNGCommon::POS_EPS;
using BNGCommon::POS_SQRT_EPS;
using BNGCommon::POS_GIGANTIC;
using BNGCommon::stime_t;
using BNGCommon::STIME_EPS;
using BNGCommon::STIME_SQRT_EPS;
using BNGCommon::STIME_GIGANTIC;
using BNGCommon::fabs_f;
using BNGCommon::cmp_eq;
using BNGCommon::distinguishable_p;
using BNGCommon::distinguishable_f;
using BNGCommon::sqrt_f;
using BNGCommon::pow_f;
using BNGCommon::floor_f;
using BNGCommon::round_f;
// also import commonly used declarations from BNG into our own namespace
using BNG::species_id_t;
using BNG::SPECIES_ID_INVALID;
using BNG::orientation_t;
using BNG::ORIENTATION_DOWN;
using BNG::ORIENTATION_NONE;
using BNG::ORIENTATION_UP;
using BNG::ORIENTATION_NOT_SET;
using BNG::ORIENTATION_DEPENDS_ON_SURF_COMP;
const double MIN_WALL_GAP = 1e-4; // 1 angstrom when length unit is 1um
// ---------------------------------- optimization macros ----------------------------------
#if defined(likely) || defined(unlikely)
#error "Macros 'likely' or 'unlikely' are already defined"
#endif
#ifndef _MSC_VER
#define likely(x) __builtin_expect((x),1)
#define unlikely(x) __builtin_expect((x),0)
#else
#define likely(x) (x)
#define unlikely(x) (x)
#endif
// ---------------------------------- float types ----------------------------------
const double SCHEDULER_COMPARISON_EPS = 1e-10;
const size_t SCHEDULER_MAX_BUCKETS_TO_FUTURE = 100000000;
const double MESH_DISTINCTIVE_EPS = EPS;
// ---------------------------------- configurable constants----------------------------------
const uint SORT_MOLS_BY_SUBPART_PERIODICITY = 20;
const uint DEFRAGMENTATION_PERIODICITY = 100;
const pos_t PARTITION_EDGE_LENGTH_DEFAULT_UM = 10; // large for now because we have just one partition
const pos_t PARTITION_EDGE_EXTRA_MARGIN_UM = 0.01;
const uint SUBPARTITIONS_PER_PARTITION_DIMENSION_DEFAULT = 1;
const uint MAX_SUBPARTS_PER_PARTITION = 300;
// with low sampling rate, the buffers take long to flush and
// the user may want to see the results earlier, so the buffers are
// periodically flushed, not only when they are full
// this time is checked with output frequency (when the iterations report is printed)
const double COUNT_BUFFER_FLUSH_SECONDS = 60;
// ideally we would need this event to be scheduled right away but this may
// require too much memory (related to maximal distance of simulation barrier)
const uint64_t ITERATIONS_BEFORE_RUN_N_ITERATIONS_END_EVENT = 10000;
const uint64_t DEFAULT_MOL_ORDER_SHUFFLE_PERIODICITY = 10000;
// ---------------------------------- fixed constants and specific typedefs -------------------
const pos_t POS_INVALID = FLT_MAX; // cannot be NAN because we cannot do any comparison with NANs
const pos_t LENGTH_INVALID = FLT_MAX;
const double TIME_INVALID = -256;
const double TIME_FOREVER = 1e20; // based on MCell3
const double TIME_SIMULATION_START = 0;
const pos_t POS_SQRT2 = 1.41421356238;
const pos_t POS_RXN_RADIUS_MULTIPLIER = 1.3; // TEMPORARY - we should figure out why some collisions with subparts are missed..., but maybe it won't have big perf impact...
const uint INT_INVALID = INT32_MAX;
// molecule id is a unique identifier of a molecule,
// no 2 molecules may have the same ID in the course of a simulation (at least for now)
typedef uint molecule_id_t;
const molecule_id_t MOLECULE_ID_INVALID = ID_INVALID;
typedef std::vector<molecule_id_t> MoleculeIdsVector;
typedef uint_set<molecule_id_t> MoleculeIdsSet;
// molecule index is index into partition's molecules array, indices and ids are
// identical until the first defragmentation that shuffles molecules in the molecules array
typedef uint molecule_index_t;
const molecule_index_t MOLECULE_INDEX_INVALID = INDEX_INVALID;
// for now, this is the partition that contains point 0,0,0 in its center
typedef uint partition_id_t;
const partition_id_t PARTITION_ID_INITIAL = 0;
const partition_id_t PARTITION_ID_INVALID = INDEX_INVALID;
typedef uint subpart_index_t;
const subpart_index_t SUBPART_INDEX_INVALID = INDEX_INVALID;
// time step is used in partition to make sets of molecules that can be diffused with
// different periodicity
const uint TIME_STEP_INDEX_INVALID = INDEX_INVALID;
const char* const NAME_INVALID = "name_invalid";
const char* const NAME_NOT_SET = "name_not_set";
const uint64_t BUCKET_INDEX_INVALID = UINT64_MAX;
const uint VERTICES_IN_TRIANGLE = 3;
const uint EDGES_IN_TRIANGLE = VERTICES_IN_TRIANGLE; // same of course as above, but different name to specify what we are counting
typedef uint vertex_index_t; // index in partition's vertices
const vertex_index_t VERTEX_INDEX_INVALID = INDEX_INVALID;
typedef uint wall_index_t; // index in partition's walls
const wall_index_t WALL_INDEX_INVALID = INDEX_INVALID;
typedef uint tile_index_t; // index of a tile in a grid
const tile_index_t TILE_INDEX_INVALID = INDEX_INVALID;
typedef uint edge_index_t; // index of an edge in a wall, must be in range 0..2
const edge_index_t EDGE_INDEX_0 = 0;
const edge_index_t EDGE_INDEX_1 = 1;
const edge_index_t EDGE_INDEX_2 = 2;
const edge_index_t EDGE_INDEX_WITHIN_WALL = 3; // used in find_edge_point
const edge_index_t EDGE_INDEX_CANNOT_TELL = 4;
const edge_index_t EDGE_INDEX_INVALID = INDEX_INVALID;
typedef uint count_buffer_id_t; // index of a tile in a grid
const count_buffer_id_t COUNT_BUFFER_ID_INVALID = INDEX_INVALID;
// index of CountSpeciesInfo in count_species_info_vec
typedef uint count_species_info_index_t;
const count_species_info_index_t NotSeenYet = INDEX_INVALID;
const count_species_info_index_t NotToBeCounted = INDEX_INVALID2;
typedef uint rgba_t; // color represented by rgba
const rgba_t DEFAULT_COLOR = 0xFFFFFF3F; // 1, 1, 1, 0.25
/* contains information about the neighbors of the tile */
class WallTileIndexPair {
public:
WallTileIndexPair()
: wall_index(WALL_INDEX_INVALID), tile_index(TILE_INDEX_INVALID)
{
}
WallTileIndexPair(const wall_index_t wall_index_, const tile_index_t tile_index_)
: wall_index(wall_index_), tile_index(tile_index_)
{
}
bool operator== (const WallTileIndexPair& other) const {
return wall_index == other.wall_index && tile_index == other.tile_index;
}
wall_index_t wall_index; /* surface grid the tile is on */
tile_index_t tile_index; /* index on that tile */
};
typedef uint wall_id_t; // world-unique wall id
const wall_id_t WALL_ID_INVALID = ID_INVALID;
const wall_id_t WALL_ID_NOT_IN_PARTITION = ID_INVALID2;
typedef uint region_id_t; // world-unique region id
const region_id_t REGION_ID_INVALID = ID_INVALID;
typedef uint region_index_t; // index in partition's regions
const region_index_t REGION_INDEX_INVALID = INDEX_INVALID;
typedef uint_set<region_index_t> RegionIndicesSet;
typedef uint geometry_object_index_t;
const geometry_object_index_t GEOMETRY_OBJECT_INDEX_INVALID = INDEX_INVALID;
typedef uint geometry_object_id_t; // world-unique unique geometry object id
const geometry_object_id_t GEOMETRY_OBJECT_ID_INVALID = ID_INVALID;
// each partition has a list of volumes that are counted
// each counted volume is identified by a set of geometry objects it is in
// completely
typedef uint counted_volume_index_t;
// volume outside of all objects, i.e. WORLD-all objects,
// this is a special counted volume that has no geometry objects
const counted_volume_index_t COUNTED_VOLUME_INDEX_OUTSIDE_ALL = 0;
// special value that tells that the specific index must be computed
// based on the specific position
const counted_volume_index_t COUNTED_VOLUME_INDEX_INTERSECTS = INDEX_INVALID2;
const counted_volume_index_t COUNTED_VOLUME_INDEX_INVALID = INDEX_INVALID;
typedef std::pair<partition_id_t, wall_index_t> PartitionWallIndexPair;
typedef std::pair<partition_id_t, region_index_t> PartitionRegionIndexPair;
typedef std::pair<partition_id_t, vertex_index_t> PartitionVertexIndexPair;
typedef std::pair<pos_t, PartitionWallIndexPair> CummAreaPWallIndexPair;
typedef std::map<geometry_object_id_t, uint_set<geometry_object_id_t>> CountedVolumesMap;
const int BASE_CONTAINER_ALLOC = 16;
#ifndef INDEXER_WA
typedef boost::container::small_vector<subpart_index_t, BASE_CONTAINER_ALLOC> SubpartIndicesVector;
typedef boost::container::small_vector<wall_index_t, BASE_CONTAINER_ALLOC> WallIndicesVector;
// WARNING: std::set_intersection and possibly other algorithms do not work correctly with dense_hash_set
typedef uint_dense_hash_set<subpart_index_t> SubpartIndicesSet; // boost-based uint_set is worse on average
#else
typedef std::vector<subpart_index_t> SubpartIndicesVector;
typedef std::vector<wall_index_t> WallIndicesVector;
typedef std::set<subpart_index_t> SubpartIndicesSet;
#endif
template<typename T>
class insertion_ordered_set {
public:
void insert_ordered(const T& value) {
if (s.count(value) == 0) {
s.insert(value);
v.push_back(value);
}
}
const T& operator [] (const size_t i) const {
assert(i < size());
return v[i];
}
size_t size() const {
assert(v.size() == s.size());
return v.size();
}
const std::vector<T>& get_as_vector() const {
return v;
}
private:
std::vector<T> v;
std::set<T> s;
};
// ---------------------------------- vector types ----------------------------------
#if POS_T_BYTES == 8
typedef glm::dvec3 glm_vec3_t;
typedef glm::dvec2 glm_vec2_t;
typedef glm::dmat4x4 mat4x4;
#else
typedef glm::fvec3 glm_vec3_t;
typedef glm::fvec2 glm_vec2_t;
typedef glm::fmat4x4 mat4x4;
#endif
typedef glm::ivec3 glm_ivec3_t;
typedef glm::uvec3 UVec3;
typedef glm::bvec3 BVec3;
struct IVec3: public glm_ivec3_t {
IVec3() = default;
IVec3(const glm_vec3_t& a) { x = a.x; y = a.y; z = a.z; }
IVec3(const IVec3& a) : glm_ivec3_t(a.x, a.y, a.z) { }
IVec3(const int x_, const int y_, const int z_) { x = x_; y = y_; z = z_; }
IVec3(const int xyz) { x = xyz; y = xyz; z = xyz; }
IVec3(const std::vector<int>& xyz) { assert(xyz.size() == 3); x = xyz[0]; y = xyz[1]; z = xyz[2]; }
IVec3(const vector3& v3) { x = v3.x; y = v3.y; z = v3.z; }
IVec3& operator=(const IVec3& other) = default;
// arbitrary ordering in order to use IVec3 as keys in sets and maps
bool operator < (const IVec3& other) const {
if (x < other.x) {
return true;
}
else if (x == other.x) {
if (y < other.y) {
return true;
}
else if (y == other.y) {
if (z < other.z) {
return true;
}
else {
return false;
}
}
else {
return false;
}
}
else {
return false;
}
}
};
struct Vec3: public glm_vec3_t {
Vec3() = default;
Vec3(const glm_vec3_t& a) { x = a.x; y = a.y; z = a.z; }
Vec3(const Vec3& a) : glm_vec3_t(a.x, a.y, a.z) { }
Vec3(const IVec3& a) : glm_vec3_t(a.x, a.y, a.z) { }
Vec3(const vector3& a) { x = a.x; y = a.y; z = a.z; }
Vec3(const pos_t x_, const pos_t y_, const pos_t z_) { x = x_; y = y_; z = z_; }
Vec3(const pos_t xyz) { x = xyz; y = xyz; z = xyz; }
Vec3(const std::vector<double>& xyz) { assert(xyz.size() == 3); x = xyz[0]; y = xyz[1]; z = xyz[2]; }
#if POS_T_BYTES == 4
Vec3(const std::vector<pos_t>& xyz) { assert(xyz.size() == 3); x = xyz[0]; y = xyz[1]; z = xyz[2]; }
#endif
Vec3& operator=(const Vec3& other) = default;
std::vector<double> to_vec() const {
std::vector<double> res(3);
res[0] = x;
res[1] = y;
res[2] = z;
return res;
}
bool is_valid() const { return !(x == POS_INVALID || y == POS_INVALID || z == POS_INVALID); }
std::string to_string() const;
void dump(const std::string extra_comment, const std::string ind) const;
};
// usually are .u and .v used to access contained values
struct Vec2: public glm_vec2_t {
Vec2() = default;
Vec2(const glm_vec2_t& a) { x = a.x; y = a.y; }
Vec2(const Vec2& a) : glm_vec2_t(a.x, a.y) { }
Vec2(const vector2& a) { x = a.u; y = a.v; }
Vec2(const pos_t x_, const pos_t y_) { x = x_; y = y_; }
Vec2(const pos_t xy) { x = xy; y = xy; }
Vec2(const std::vector<double>& xy) { assert(xy.size() == 2); x = xy[0]; y = xy[1]; }
#if POS_T_BYTES == 4
Vec2(const std::vector<pos_t>& xy) { assert(xy.size() == 2); x = xy[0]; y = xy[1]; }
#endif
Vec2& operator=(const Vec2& other) = default;
std::vector<double> to_vec() const {
std::vector<double> res(2);
res[0] = x;
res[1] = y;
return res;
}
bool is_valid() const { return !(x == POS_INVALID || y == POS_INVALID); }
std::string to_string() const;
void dump(const std::string extra_comment, const std::string ind) const;
};
static inline std::ostream & operator<<(std::ostream &out, const Vec3& a) {
out << "(" << a.x << ", " << a.y << ", " << a.z << ")";
return out;
}
static inline std::ostream & operator<<(std::ostream &out, const Vec2& a) {
out << "(" << a.u << ", " << a.v << ")";
return out;
}
// ---------------------------------- auxiliary functions ----------------------------------
static inline double log_f(const double x) {
assert(x != 0);
return log(x);
}
static inline pos_t log_p(const pos_t x) {
assert(x != 0);
#if POS_T_BYTES == 4
return logf(x);
#else
return log(x);
#endif
}
static inline double exp_f(const double x) {
return exp(x);
}
static inline double ceil_f(const double x) {
return ceil(x);
}
static inline double ceil_p(const pos_t x) {
#if POS_T_BYTES == 8
return ceil(x);
#else
return ceilf(x);
#endif
}
static inline pos_t fabs_p(const pos_t x) {
if (x < 0) {
return -x;
}
else {
return x;
}
}
static inline double floor_to_multiple_f(const double val, double multiple) {
assert(val >= 0);
assert(multiple > 0);
return (double)((long long)((val + EPS)/ multiple)) * multiple;
}
static inline pos_t floor_to_multiple_p(const pos_t val, pos_t multiple) {
assert(val >= 0);
assert(multiple > 0);
return (pos_t)((long long)((val + EPS)/ multiple)) * multiple;
}
static inline double floor_to_multiple_allow_negative_p(const double val, pos_t multiple) {
if (val >= 0) {
return (double)((long long)((val + EPS)/ multiple)) * multiple;
}
else {
// we need to floor towards the lower negative value, the code above would
// ceil the value for negative inputs
return (double)((long long)((val + EPS - multiple)/ multiple)) * multiple;
}
}
static inline Vec3 floor_to_multiple_allow_negative_p(const Vec3& val, const pos_t multiple) {
Vec3 res;
res.x = floor_to_multiple_allow_negative_p(val.x, multiple);
res.y = floor_to_multiple_allow_negative_p(val.y, multiple);
res.z = floor_to_multiple_allow_negative_p(val.z, multiple);
return res;
}
static inline double ceil_to_multiple_p(const double val, const pos_t multiple) {
assert(val >= 0);
double res = floor_to_multiple_p(val, multiple);
if (!cmp_eq(val, res)) {
res += multiple;
}
return res;
}
static inline Vec3 ceil_to_multiple_p(const Vec3& val, const pos_t multiple) {
Vec3 res;
res.x = ceil_to_multiple_p(val.x, multiple);
res.y = ceil_to_multiple_p(val.y, multiple);
res.z = ceil_to_multiple_p(val.z, multiple);
return res;
}
static inline bool cmp_eq(const Vec3& a, const Vec3& b, const pos_t eps) {
return cmp_eq(a.x, b.x, eps) && cmp_eq(a.y, b.y, eps) && cmp_eq(a.z, b.z, eps);
}
static inline bool cmp_eq(const Vec3& a, const Vec3& b) {
return cmp_eq(a, b, EPS);
}
static inline bool cmp_eq(const Vec2& a, const Vec2& b, const pos_t eps) {
return cmp_eq(a.x, b.x, eps) && cmp_eq(a.y, b.y, eps);
}
static inline bool cmp_eq(const Vec2& a, const Vec2& b) {
return cmp_eq(a, b, EPS);
}
static inline bool cmp_lt(const double a, const double b, const double eps) {
return a < b && !cmp_eq(a, b, eps);
}
static inline bool cmp_le(const double a, const double b, const double eps) {
return a < b || cmp_eq(a, b, eps);
}
static inline bool cmp_gt(const double a, const double b, const double eps) {
return a > b && !cmp_eq(a, b, eps);
}
static inline bool cmp_ge(const double a, const double b, const double eps) {
return a > b || cmp_eq(a, b, eps);
}
static inline pos_t sqrt_p(const pos_t x) {
#if POS_T_BYTES == 4
return sqrtf(x);
#else
return sqrt(x);
#endif
}
static inline uint powu(const uint a, const uint n) {
uint res = a;
for (uint i = 1; i < n; i++) {
res *= a;
}
return res;
}
static inline pos_t max3(const Vec3& v) {
return glm::compMax((glm_vec3_t)v);
}
static inline pos_t min3(const Vec3& v) {
return glm::compMin((glm_vec3_t)v);
}
static inline pos_t min3_p(const pos_t x, const pos_t y, const pos_t z) {
return (z < y) ? ((z < x) ? z : x) : ((y < x) ? y : x);
}
static inline int max3_i(const IVec3& v) {
return glm::compMax((glm_ivec3_t)v);
}
static inline int min3_i(const IVec3& v) {
return glm::compMin((glm_ivec3_t)v);
}
static inline Vec3 abs3(const Vec3& v) {
return glm::abs((glm_vec3_t)v);
}
static inline Vec3 floor3(const Vec3& v) {
return glm::floor((glm_vec3_t)v);
}
static inline Vec3 round3(const Vec3& v) {
return glm::round((glm_vec3_t)v);
}
/* abs_max_2vec picks out the largest (absolute) value found among two vectors
* (useful for properly handling floating-point rounding error). */
static inline pos_t abs_max_2vec(const Vec3& v1, const Vec3& v2) {
glm_vec3_t v1abs = abs3(v1);
glm_vec3_t v2abs = abs3(v2);
Vec3 vmax = glm::max(v1abs, v2abs);
return MCell::max3(vmax);
}
static inline pos_t determinant2(const Vec2& v1, const Vec2& v2) {
return v1.u * v2.v - v1.v * v2.u;
}
static inline pos_t dot2(const Vec2& v1, const Vec2& v2) {
return glm::dot((glm_vec2_t)v1, (glm_vec2_t)v2);
}
static inline pos_t len2_squared(const Vec2& v1) {
return v1.u * v1.u + v1.v * v1.v;
}
static inline pos_t len2(const Vec2& v1) {
return sqrt_p(len2_squared(v1));
}
static inline pos_t dot(const Vec3& v1, const Vec3& v2) {
return glm::dot((glm_vec3_t)v1, (glm_vec3_t)v2);
}
static inline pos_t len3_squared(const Vec3& v1) {
return v1.x * v1.x + v1.y * v1.y + v1.z * v1.z;
}
static inline pos_t len3(const Vec3& v1) {
return sqrt_p(len3_squared(v1));
}
static inline pos_t distance3_squared(const Vec3& v1, const Vec3& v2) {
return len3_squared(v1 - v2);
}
static inline pos_t distance3(const Vec3& v1, const Vec3& v2) {
return sqrt_p( len3_squared(v1 - v2) );
}
static inline uint get_largest_abs_dim_index(const Vec3& v) {
Vec3 a = glm::abs(glm_vec3_t(v));
if (a.x > a.y) {
if (a.x > a.z) {
return 0; // x
}
else {
return 2; // z
}
}
else {
if (a.y > a.z) {
return 1; // y
}
else {
return 2; // z
}
}
}
/***************************************************************************
point_in_box:
In: pt - we want to find out if this point is in the box
llf - lower left front corner of the box
urb - upper right back corner of the box
Out: Returns true if point is in box, 0 otherwise
***************************************************************************/
static inline bool point_in_box(const Vec3& pt, const Vec3& llf, const Vec3& urb) {
return
pt.x >= llf.x && pt.x <= urb.x &&
pt.y >= llf.y && pt.y <= urb.y &&
pt.z >= llf.z && pt.z <= urb.z;
}
/**
* Performs vector cross product.
* Computes the cross product of two vector3's v1 and v2 storing the result
* in vector3 v3.
*/
static inline Vec3 cross(const Vec3& v1, const Vec3& v2) {
return glm::cross((glm_vec3_t)v1, (glm_vec3_t)v2);
}
static inline int distinguishable_vec2(const Vec2& a, const Vec2& b, const pos_t eps) {
pos_t c, cc, d;
/* Find largest coordinate */
c = fabs_p(a.u);
d = fabs_p(a.v);
if (d > c)
c = d;
d = fabs_p(b.u);
if (d > c)
c = d;
d = fabs_p(b.v);
if (d > c)
c = d;
/* Find largest difference */
cc = fabs_p(a.u - b.u);
d = fabs_p(a.v - b.v);
if (d > cc)
cc = d;
/* Make sure fractional difference is at least eps and absolute difference is
* at least (eps*eps) */
if (c < eps)
c = eps;
return (c * eps < cc);
}
static inline bool distinguishable_vec3(const Vec3& a, const Vec3& b, const pos_t eps) {
pos_t c, cc, d;
/* Find largest coordinate */
c = fabs_p(a.x);
d = fabs_p(a.y);
if (d > c)
c = d;
d = fabs_p(a.z);
if (d > c)
c = d;
d = fabs_p(b.x);
if (d > c)
c = d;
d = fabs_p(b.y);
if (d > c)
c = d;
d = fabs_p(b.z);
if (d > c)
c = d;
/* Find largest difference */
cc = fabs_p(a.x - b.x);
d = fabs_p(a.y - b.y);
if (d > cc)
cc = d;
d = fabs_p(a.z - b.z);
if (d > cc)
cc = d;
/* Make sure fractional difference is at least eps and absolute difference is
* at least (eps*eps) */
if (c < eps)
c = eps;
return (c * eps < cc);
}
static inline void guard_zero_div(Vec3& val) {
if (val.x == 0) {
val.x = FLT_MIN;
}
if (val.y == 0) {
val.y = FLT_MIN;
}
if (val.z == 0) {
val.z = FLT_MIN;
}
}
// some utilities
uint64_t get_mem_usage();
} // namespace mcell
#endif // SRC4_DEFINES_H_
| Unknown |
3D | mcellteam/mcell | src4/rxn_class_cleanup_event.h | .h | 879 | 37 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_RXN_CLASS_CLEANUP_EVENT_H_
#define SRC4_RXN_CLASS_CLEANUP_EVENT_H_
#include "base_event.h"
namespace MCell {
class World;
class RxnClassCleanupEvent: public BaseEvent {
public:
RxnClassCleanupEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_RXN_CLASS_CLEANUP),
world(world_) {
}
void step() override;
void dump(const std::string indent) const override;
private:
World* world;
};
} /* namespace MCell */
#endif /* SRC4_RXN_CLASS_CLEANUP_EVENT_H_ */
| Unknown |
3D | mcellteam/mcell | src4/sort_mols_by_subpart_event.h | .h | 1,079 | 40 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_SORT_MOLS_BY_SUBPART_EVENT_H_
#define SRC4_SORT_MOLS_BY_SUBPART_EVENT_H_
#include "base_event.h"
namespace MCell {
/**
* When a reaction occurs, a hole is created in the parition's molecules array,
* defragmentation "squeezes" this array so that there are no defuct molecules anymore;
* updates all related data
*/
class SortMolsBySubpartEvent: public BaseEvent {
public:
SortMolsBySubpartEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_SORT_MOLS_BY_SUBPART),
world(world_) {
}
void step() override;
void dump(const std::string indent) const override;
private:
World* world;
};
} // namespace mcell
#endif // SRC4_SORT_MOLS_BY_SUBPART_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/count_buffer.cpp | .cpp | 4,112 | 178 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "count_buffer.h"
#include <iomanip>
#include <sstream>
#include "logging.h"
#include "util.h"
#include "bng/filesystem_utils.h"
using namespace std;
const uint GDAT_COLUMN_WIDTH = 14;
namespace MCell {
void CountValue::write_as_dat(std::ostream& out) const {
out << time << " " << value << "\n";
}
static void write_gdat_value(std::ostream& outs, double d) {
// there is no way to set number of digits in an exponent
// so we must do it manually
// split exponent and base as string - we do not want to do
// any numerical computation here
stringstream ss;
ss << scientific << setprecision(GDAT_COLUMN_WIDTH - 6) << d;
string s = ss.str();
size_t pos = s.find('e');
assert(pos != string::npos);
string base = s.substr(0, pos);
int exponent = stoi(s.substr(pos + 1));
string sign;
if (exponent >= 0) {
sign = "+";
}
else {
// setfill/setw does not add '0' for negative values
sign = "-";
exponent = -exponent;
}
outs << base << "e" << sign << setfill('0') << setw(2) << exponent;
}
void CountBuffer::flush() {
if (!fout.is_open()) {
open(true);
}
if (output_format == CountOutputFormat::DAT) {
// there is a single column
assert(data.size() == 1);
for (const auto& value: data[0]) {
assert(value.column_index == 0);
value.write_as_dat(fout);
}
}
else {
assert(data.size() >= 1);
// output row
// expecting that each column has the same depth
size_t num_rows = data[0].size();
for (size_t row = 0; row < num_rows; row++) {
// simply use time from the first column
double time = data[0][row].time;
fout << " ";
write_gdat_value(fout, time);
// output each column
for (size_t col = 0; col < data.size(); col++) {
assert(row < data[col].size());
const auto& value = data[col][row];
release_assert(cmp_eq(value.time, time, SQRT_EPS) && "Mismatch in gdat column times");
fout << " ";
write_gdat_value(fout, value.value);
}
fout << "\n";
}
}
fout.flush(); // flush the data so the user can see them
for (auto& column: data) {
column.clear();
}
}
void CountBuffer::write_gdat_header() {
assert(fout.is_open());
assert(output_format == CountOutputFormat::GDAT);
fout << "#";
string time = "time";
time.insert(time.begin(), GDAT_COLUMN_WIDTH - time.size(), ' ');
fout << time;
for (const string& name: column_names) {
string col = name;
if (GDAT_COLUMN_WIDTH > col.size()) {
col.insert(col.begin(), GDAT_COLUMN_WIDTH - col.size() + 2, ' ');
}
else {
col = " " + col;
}
fout << col;
}
fout << "\n";
}
bool CountBuffer::open(bool error_is_fatal) {
FSUtils::make_dir_for_file_w_multiple_attempts(filename);
if (!open_for_append) {
// create an empty file so that we know that nothing was stored
fout.open(filename);
}
else {
// appending is used when restoring a checkpoint
// opens a new file if the file does not exist
fout.open(filename, std::ofstream::out | std::ofstream::app);
}
// write header
if (output_format == CountOutputFormat::GDAT && !open_for_append) {
write_gdat_header();
}
if (!fout.is_open()) {
mcell_warn("Could not open file %s for writing.", filename.c_str());
if (error_is_fatal) {
mcell_error("Terminating due to error.");
}
return false;
}
return true;
}
void CountBuffer::flush_and_close() {
flush();
if (fout.is_open()) {
fout.close();
}
else {
bool ok = open(false);
if (ok) {
fout.close();
}
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/rxn_class_cleanup_event.cpp | .cpp | 1,590 | 58 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include "rxn_class_cleanup_event.h"
#include "world.h"
using namespace std;
namespace MCell {
void RxnClassCleanupEvent::dump(const string ind) const {
cout << ind << "Rxn class cleanup event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
void RxnClassCleanupEvent::step() {
// for all species
for (BNG::Species* sp: world->get_all_species().get_species_vector()) {
release_assert(sp != nullptr);
if (sp->get_num_instantiations() == 0 && sp->was_instantiated()) {
// there are no instances, we can efficiently remove all rxn classes for this species
// remove rxn classes
world->get_all_rxns().remove_unimol_rxn_class(sp->id);
world->get_all_rxns().remove_bimol_rxn_classes(sp->id);
// clear flag telling that this species was instantiated
sp->set_was_instantiated(false);
// and also tell partitions that this species is not known anymore
// TODO: can this may be done through the was_instantiated flag?
if (sp->is_vol()) {
for (Partition& p: world->get_partitions()) {
p.remove_from_known_vol_species(sp->id);
}
}
}
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/defragmentation_event.cpp | .cpp | 3,891 | 117 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <algorithm>
#include "defragmentation_event.h"
#include "world.h"
#include "partition.h"
using namespace std;
namespace MCell {
void DefragmentationEvent::dump(const string ind) const {
cout << ind << "Defragmentation event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
void DefragmentationEvent::step() {
for (Partition& p: world->get_partitions()) {
vector<Molecule>& molecules = p.get_molecules();
if (molecules.empty()) {
// simply skip if there are no volume molecules
continue;
}
// first cleanup schedulable_molecule_ids by removing all mols that are defunct
// must be done before the following cleanup
auto& schedulable_mol_ids = p.get_schedulable_molecule_ids();
auto it_new_end = remove_if(schedulable_mol_ids.begin(), schedulable_mol_ids.end(),
[&p](const molecule_id_t id) -> bool { return p.get_m(id).is_defunct(); });
schedulable_mol_ids.erase(it_new_end, schedulable_mol_ids.end());
// remove defunct molecules in the molecules array
vector<molecule_index_t>& molecule_id_to_index_mapping = p.get_molecule_id_to_index_mapping();
#ifdef DEBUG_DEFRAGMENTATION
cout << "Defragmentation before sort:\n";
Molecule::dump_array(molecules);
#endif
size_t removed = 0;
typedef vector<Molecule>::iterator vmit_t;
vmit_t it_end = molecules.end();
// find first defunct molecule
vmit_t it_first_defunct = find_if(molecules.begin(), it_end, [](const Molecule & m) -> bool { return m.is_defunct(); });
vmit_t it_copy_destination = it_first_defunct;
while (it_first_defunct != it_end) {
// then find the next one that is not defunct (might be it_end)
vmit_t it_next_funct = find_if(it_first_defunct, it_end, [](const Molecule & m) -> bool { return !m.is_defunct(); });
// then again, find following defunct molecule
vmit_t it_second_defunct = find_if(it_next_funct, it_end, [](const Molecule & m) -> bool { return m.is_defunct(); });
// items between it_first_defunct and it_next_funct will be removed
// for debug mode, we will set their ids in volume_molecules_id_to_index_mapping as invalid
#ifndef NDEBUG
for (vmit_t it_update_mapping = it_first_defunct; it_update_mapping != it_next_funct; it_update_mapping++) {
const Molecule& vm = *it_update_mapping;
assert(vm.is_defunct());
molecule_id_to_index_mapping[vm.id] = MOLECULE_INDEX_INVALID;
}
#endif
// move data: from, to, into position
std::copy(it_next_funct, it_second_defunct, it_copy_destination);
removed += it_next_funct - it_first_defunct;
// and also move destination pointer
it_copy_destination += it_second_defunct - it_next_funct;
it_first_defunct = it_second_defunct;
}
// remove everything after it_copy_destination
if (removed != 0) {
molecules.resize(molecules.size() - removed);
}
#ifdef DEBUG_DEFRAGMENTATION
cout << "Defragmentation after defunct removal:\n";
Molecule::dump_array(molecules);
#endif
// update mapping
size_t new_count = molecules.size();
for (size_t i = 0; i < new_count; i++) {
const Molecule& vm = molecules[i];
if (vm.is_defunct()) {
break;
}
// correct index because the molecule could have been moved
molecule_id_to_index_mapping[vm.id] = i;
}
}
}
} /* namespace mcell */
| C++ |
3D | mcellteam/mcell | src4/region_expr.h | .h | 2,355 | 96 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_REGION_EXPR_H_
#define SRC4_REGION_EXPR_H_
#include "defines.h"
namespace MCell {
class World;
class Region;
enum class RegionExprOperator {
INVALID,
UNION,
INTERSECT,
DIFFERENCE,
LEAF_SURFACE_REGION,
LEAF_GEOMETRY_OBJECT
};
class RegionExprNode {
public:
RegionExprNode()
: op(RegionExprOperator::INVALID),
region_id(REGION_INDEX_INVALID),
geometry_object_id(GEOMETRY_OBJECT_ID_INVALID),
left(nullptr), right(nullptr) {
}
~RegionExprNode() {
// children are contained in RegionExpr::all_region_expr_nodes,
// and are deleted when ReleaseEvent is destroyed
}
bool has_binary_op() const {
return
op == RegionExprOperator::UNION ||
op == RegionExprOperator::INTERSECT ||
op == RegionExprOperator::DIFFERENCE;
}
RegionExprOperator op;
region_id_t region_id;
geometry_object_id_t geometry_object_id;
RegionExprNode* left;
RegionExprNode* right;
void dump(const World* world = nullptr) const; // does not print any newlines
std::string to_string(const World* world = nullptr, const bool for_datamodel = false) const;
};
// constructor and container for all region expr nodes
class RegionExpr {
public:
RegionExpr() :
root(nullptr) {
}
RegionExpr(const RegionExpr& other) {
*this = other;
}
RegionExpr& operator=(const RegionExpr& other);
~RegionExpr();
RegionExprNode* create_new_expr_node_leaf_surface_region(const region_id_t id);
RegionExprNode* create_new_expr_node_leaf_geometry_object(const geometry_object_id_t id);
RegionExprNode* create_new_region_expr_node_op(const RegionExprOperator op, RegionExprNode* left, RegionExprNode* right);
// used when release_shape is ReleaseShape::Region
RegionExprNode* root;
private:
std::vector<RegionExprNode*> all_region_expr_nodes;
};
} /* namespace MCell */
#endif /* SRC4_REGION_EXPR_H_ */
| Unknown |
3D | mcellteam/mcell | src4/defragmentation_event.h | .h | 1,123 | 41 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_DEFRAGMENTATION_EVENT_H_
#define SRC4_DEFRAGMENTATION_EVENT_H_
#include "base_event.h"
namespace MCell {
/**
* When a reaction occurs, a hole is created in the parition's molecules array,
* defragmentation "squeezes" this array so that there are no defuct molecules anymore;
* updates all related data
*/
class DefragmentationEvent: public BaseEvent {
public:
DefragmentationEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_DEFRAGMENTATION),
world(world_) {
}
void step() override;
void dump(const std::string indent) const override;
private:
World* world;
};
} // namespace mcell
#endif // SRC4_DEFRAGMENTATION_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/bng_data_to_datamodel_converter.cpp | .cpp | 14,160 | 426 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <exception>
#include <string>
#include "bng_data_to_datamodel_converter.h"
#include "datamodel_defines.h"
#include "bng/bng.h"
#include "viz_output_event.h"
#include "scheduler.h"
#include "world.h"
using namespace std;
using namespace DMUtils;
using namespace BNG;
using Json::Value;
namespace MCell {
typedef std::invalid_argument ConversionError;
#define CHECK(stmt) \
do { \
try { \
(stmt); \
} \
catch (exception& e) { \
cerr << e.what() << "\n"; \
cerr << "Exception caught in '" << __FUNCTION__ << "' after conversion error.\n"; \
conversion_failed = true; \
} \
} while (0)
#define CHECK_PROPERTY(cond) \
do { \
if(!(cond)) { \
throw ConversionError("Expected '" + #cond + "' is false. (" + __FUNCTION__ + " - " + __FILE__ + ":" + to_string(__LINE__) + ")"); \
} \
} while (0)
#define CHECK_PROPERTY_W_NAME(cond, name) \
do { \
if(!(cond)) { \
throw ConversionError(string("Conversion of ") + name + ": Expected '" + #cond + "' is false. (" + __FUNCTION__ + " - " + __FILE__ + ":" + to_string(__LINE__) + ")"); \
} \
} while (0)
BngDataToDatamodelConverter::BngDataToDatamodelConverter() {
reset();
// list from https://www.rapidtables.com/web/color/RGB_Color.html
colors.push_back(Vec3(1, 0, 0));
colors.push_back(Vec3(0, 1, 0));
colors.push_back(Vec3(0, 0, 1));
colors.push_back(Vec3(1, 1, 0));
colors.push_back(Vec3(0, 1, 1));
colors.push_back(Vec3(1, 0, 1));
// ...
}
void BngDataToDatamodelConverter::reset() {
world = nullptr;
bng_engine = nullptr;
next_color_index = 0;
rxn_counter = 0;
conversion_failed = false;
processed_surface_classes.clear();
}
void BngDataToDatamodelConverter::to_data_model(
const World* world_, Value& mcell_node, const bool only_for_viz) {
reset();
world = world_;
bng_engine = &(world->bng_engine);
// similarly as in pymcell converter, maximum effort is given to conversion and
// if some parts won't go through, we are trying to generate
CHECK(convert_molecules(mcell_node));
// compartments are converted in GeometryObject into the KEY_MODEL_OBJECTS section
if (!only_for_viz) {
CHECK(convert_rxns(mcell_node));
}
return;
}
Vec3 BngDataToDatamodelConverter::get_next_color() {
Vec3 res = colors[next_color_index];
next_color_index++;
if (next_color_index == colors.size()) {
next_color_index = 0;
}
return res;
}
void BngDataToDatamodelConverter::convert_molecules(Value& mcell_node) {
Value& define_molecules = mcell_node[KEY_DEFINE_MOLECULES];
add_version(define_molecules, VER_DM_2014_10_24_1638);
Value& molecule_list = define_molecules[KEY_MOLECULE_LIST];
molecule_list = Value(Json::arrayValue); // empty array
// we are converting molecule types because that's the information we need in
// the datamodel, we do not care about species
for (const ElemMolType& mt: bng_engine->get_data().get_elem_mol_types()) {
// - ALL_* species are ignored
// - reactive surfaces are converted as surface classes
// -
if (is_species_superclass(mt.name) || mt.is_reactive_surface()) {
continue;
}
Value molecule_node;
CHECK(convert_single_mol_type(mt, molecule_node));
molecule_list.append(molecule_node);
}
}
void BngDataToDatamodelConverter::convert_single_mol_type(const BNG::ElemMolType& mt, Value& molecule_node) {
add_version(molecule_node, VER_DM_2018_10_16_1632);
Value& display = molecule_node[KEY_DISPLAY];
display[KEY_EMIT] = 0.0;
Value& color_value = display[KEY_COLOR];
if (mt.color_set) {
color_value.append(mt.color_r);
color_value.append(mt.color_g);
color_value.append(mt.color_b);
}
else {
// automatic color
Vec3 c = get_next_color();
color_value.append(c.r);
color_value.append(c.g);
color_value.append(c.b);
}
display[KEY_GLYPH] = VALUE_GLYPH_SPHERE_1;
display[KEY_SCALE] = mt.scale;
molecule_node[KEY_BNGL_COMPONENT_LIST] = Value(Json::arrayValue); // empty array
molecule_node[KEY_MOL_BNGL_LABEL] = "";
molecule_node[KEY_DESCRIPTION] = "";
molecule_node[KEY_MOL_TYPE] = mt.is_vol() ? VALUE_MOL_TYPE_3D : VALUE_MOL_TYPE_2D;
const VizOutputEvent* viz =
dynamic_cast<const VizOutputEvent*>(world->scheduler.find_next_event_with_type_index(EVENT_TYPE_INDEX_VIZ_OUTPUT));
if (viz == nullptr || viz->should_visualize_all_species()) {
// no visualization/or enabled globally
molecule_node[KEY_EXPORT_VIZ] = false;
}
else {
// simple species based on this molecule type set to be visualized?
// the simple species have always the same name
species_id_t species_id = bng_engine->get_all_species().find_by_name(mt.name);
molecule_node[KEY_EXPORT_VIZ] = viz->species_ids_to_visualize.count(species_id) == 1;
}
if (mt.custom_space_step != 0) {
molecule_node[KEY_CUSTOM_SPACE_STEP] = f_to_str(mt.custom_space_step);
}
else {
molecule_node[KEY_CUSTOM_SPACE_STEP] = "";
}
if (mt.custom_time_step != 0) {
molecule_node[KEY_CUSTOM_TIME_STEP] = f_to_str(mt.custom_time_step);
}
else {
molecule_node[KEY_CUSTOM_TIME_STEP] = "";
}
molecule_node[KEY_MAXIMUM_STEP_LENGTH] = "";
molecule_node[KEY_TARGET_ONLY] = mt.cant_initiate();
molecule_node[KEY_DIFFUSION_CONSTANT] = f_to_str(mt.D);
molecule_node[KEY_SPATIAL_STRUCTURE] = "None";
molecule_node[KEY_MOL_NAME] = mt.name;
if (!mt.component_type_ids.empty()) {
// generate info on components
Value& bngl_component_list = molecule_node[KEY_BNGL_COMPONENT_LIST];
bngl_component_list = Value(Json::arrayValue);
for (component_type_id_t ct_id: mt.component_type_ids) {
Value bngl_component;
const ComponentType& ct = bng_engine->get_data().get_component_type(ct_id);
bngl_component[KEY_CNAME] = ct.name;
Value& cstates = bngl_component[KEY_CSTATES];
cstates = Value(Json::arrayValue);
for (state_id_t s_id: ct.allowed_state_ids) {
const string& state_name = bng_engine->get_data().get_state_name(s_id);
cstates.append(state_name);
}
// additional empty data required by cellblender
bngl_component[KEY_IS_KEY] = false;
bngl_component[KEY_ROT_INDEX] = 0;
bngl_component[KEY_ROT_ANG] = "0";
bngl_component[KEY_ROT_X] = "0";
bngl_component[KEY_ROT_Y] = "0";
bngl_component[KEY_ROT_Z] = "0";
bngl_component[KEY_LOC_X] = "0";
bngl_component[KEY_LOC_Y] = "0";
bngl_component[KEY_LOC_Z] = "0";
bngl_component_list.append(bngl_component);
}
}
}
void BngDataToDatamodelConverter::convert_single_rxn_rule(const BNG::RxnRule& r, Value& rxn_node) {
assert(r.type == RxnType::Standard);
add_version(rxn_node, VER_DM_2018_01_11_1330);
// name is put into rnx_name and name is the string of the reaction
rxn_node[KEY_RXN_NAME] = r.name;
rxn_node[KEY_DESCRIPTION] = "";
// LATER: maybe find an opposite reaction and generate it as reversible
rxn_node[KEY_RXN_TYPE] = VALUE_IRREVERSIBLE;
string reactants = r.reactants_to_str();
rxn_node[KEY_REACTANTS] = reactants;
string products = r.products_to_str();
if (products == "") {
products = VALUE_NULL;
}
rxn_node[KEY_PRODUCTS] = products;
// generated directly by data_model_to_mdl converter,
// reversible rxns were cloned
rxn_node[KEY_NAME] = reactants + " -> " + products;
if (r.base_variable_rates.empty()) {
rxn_node[KEY_FWD_RATE] = f_to_str(r.base_rate_constant);
rxn_node[KEY_BKWD_RATE] = "";
CHECK_PROPERTY_W_NAME(r.base_variable_rates.empty(), r.name);
rxn_node[KEY_VARIABLE_RATE_VALID] = false;
rxn_node[KEY_VARIABLE_RATE_SWITCH] = false;
rxn_node[KEY_VARIABLE_RATE] = "";
rxn_node[KEY_VARIABLE_RATE_TEXT] = "";
}
else {
rxn_node[KEY_FWD_RATE] = "0";
rxn_node[KEY_BKWD_RATE] = "";
rxn_node[KEY_VARIABLE_RATE_VALID] = true;
rxn_node[KEY_VARIABLE_RATE_SWITCH] = true;
rxn_node[KEY_VARIABLE_RATE] = "var_rate_" + DMUtils::to_id(r.name) + "_" + to_string(rxn_counter);
rxn_counter++;
stringstream text;
// initial value for time 0
text << 0.0 << "\t" << r.base_rate_constant << "\n";
for (const RxnRateInfo& ri: r.base_variable_rates) {
text << ri.time * world->config.time_unit << "\t" << ri.rate_constant << "\n";
}
rxn_node[KEY_VARIABLE_RATE_TEXT] = text.str();
}
}
string BngDataToDatamodelConverter::get_surface_class_name(const BNG::RxnRule& r) {
assert(r.is_bimol() && r.is_reactive_surface_rxn());
uint idx = (r.reactants[0].is_reactive_surface()) ? 0 : 1;
assert(r.reactants[idx].is_simple());
// the name of the surface class is the name of the species/elem mol type
return
bng_engine->get_data().get_elem_mol_type(r.reactants[idx].get_simple_species_mol_type_id()).name;
}
void BngDataToDatamodelConverter::convert_single_surface_class(const BNG::RxnRule& base_rxn, Value& surface_class) {
surface_class[KEY_DESCRIPTION] = "";
add_version(surface_class, VER_DM_2018_01_11_1330);
string name = get_surface_class_name(base_rxn);
assert(processed_surface_classes.count(name) == 0 && "This surface class was already processed");
processed_surface_classes.insert(name);
surface_class[KEY_NAME] = name;
Value& surface_class_prop_list = surface_class[KEY_SURFACE_CLASS_PROP_LIST];
surface_class_prop_list = Value(Json::arrayValue);
// find all rxn rules with the same name
vector<const RxnRule*> rxns_belonging_to_surf_class;
for (const RxnRule* rxn_rule: bng_engine->get_all_rxns().get_rxn_rules_vector()) {
if (rxn_rule->is_reactive_surface_rxn() && get_surface_class_name(*rxn_rule) == name) {
rxns_belonging_to_surf_class.push_back(rxn_rule);
}
}
// and convert them all as properties of this surface class
for (const RxnRule* rxn_rule: rxns_belonging_to_surf_class) {
Value sc_property;
add_version(sc_property, VER_DM_2015_11_08_1756);
CONVERSION_CHECK(rxn_rule->reactants[0].is_simple(), "Surface class reactant must be simple for now.");
bool has_type = true;
switch (rxn_rule->type) {
case RxnType::Transparent:
sc_property[KEY_SURF_CLASS_TYPE] = VALUE_TRANSPARENT;
break;
case RxnType::Reflect:
sc_property[KEY_SURF_CLASS_TYPE] = VALUE_REFLECTIVE;
break;
case RxnType::AbsorbRegionBorder:
sc_property[KEY_SURF_CLASS_TYPE] = VALUE_ABSORPTIVE;
break;
case RxnType::Standard:
if (rxn_rule->is_absorptive_region_rxn()) {
sc_property[KEY_SURF_CLASS_TYPE] = VALUE_ABSORPTIVE;
}
else {
// do not generate any property if type is nto set
continue;
}
break;
default:
CONVERSION_UNSUPPORTED("Unexpected reaction type");
}
const string& reactant_name = bng_engine->get_data().get_elem_mol_type(rxn_rule->reactants[0].get_simple_species_mol_type_id()).name;
if (is_species_superclass(reactant_name)) {
sc_property[KEY_AFFECTED_MOLS] = reactant_name;
sc_property[KEY_MOLECULE] = "";
}
else {
sc_property[KEY_AFFECTED_MOLS] = VALUE_SINGLE;
sc_property[KEY_MOLECULE] = reactant_name;
}
sc_property[KEY_SURF_CLASS_ORIENT] = DMUtils::orientation_to_str(rxn_rule->reactants[0].get_orientation());
sc_property[KEY_CLAMP_VALUE] = "0";
sc_property[KEY_NAME] = ""; // name is ignored by the datamodel to mdl converter anyway
surface_class_prop_list.append(sc_property);
}
}
void BngDataToDatamodelConverter::convert_rxns(Value& mcell_node) {
// --- define_reactions --- (this section is always present)
Value& define_reactions = mcell_node[KEY_DEFINE_REACTIONS];
add_version(define_reactions, VER_DM_2014_10_24_1638);
Value& reaction_list = define_reactions[KEY_REACTION_LIST];
reaction_list = Value(Json::arrayValue);
// --- define_surface_classes --- (only when needed)
Value& define_surface_classes = mcell_node[KEY_DEFINE_SURFACE_CLASSES];
add_version(define_surface_classes, VER_DM_2014_10_24_1638);
Value& surface_class_list = define_surface_classes[KEY_SURFACE_CLASS_LIST];
if (!surface_class_list.isArray()) {
// do not overwrite if it was already set
surface_class_list = Value(Json::arrayValue);
}
for (const RxnRule* rxn_rule: bng_engine->get_all_rxns().get_rxn_rules_vector()) {
if (rxn_rule->has_flag(RXN_FLAG_CREATED_FOR_CONCENTRATION_CLAMP) ||
rxn_rule->has_flag(RXN_FLAG_CREATED_FOR_FLUX_CLAMP) ) {
// concentration clamp info is generated from ConcentrationClampReleaseEvent
continue;
}
if (rxn_rule->type == RxnType::Standard) {
// this might be a special case of absorptive reaction
if (!rxn_rule->is_absorptive_region_rxn()) {
Value rxn_node;
CHECK(convert_single_rxn_rule(*rxn_rule, rxn_node));
reaction_list.append(rxn_node);
}
// also register the surface class
if (rxn_rule->is_reactive_surface_rxn() &&
processed_surface_classes.count(get_surface_class_name(*rxn_rule)) == 0) {
Value surface_class;
CHECK(convert_single_surface_class(*rxn_rule, surface_class));
surface_class_list.append(surface_class);
}
}
else if (rxn_rule->type == RxnType::Transparent ||
rxn_rule->type == RxnType::Reflect ||
rxn_rule->type == RxnType::AbsorbRegionBorder) {
// this rxn rule defines a surface class
if (processed_surface_classes.count(get_surface_class_name(*rxn_rule)) == 0) {
Value surface_class;
CHECK(convert_single_surface_class(*rxn_rule, surface_class));
surface_class_list.append(surface_class);
}
}
else {
CONVERSION_UNSUPPORTED("Invalid reaction type");
}
}
}
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/vtk_utils.cpp | .cpp | 21,189 | 671 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <vtkSmartPointer.h>
#include <vtkTriangle.h>
#include <vtkCleanPolyData.h>
#include <vtkTriangleFilter.h>
#include <vtkCollisionDetectionFilter.h>
#include <vtkSelectEnclosedPoints.h>
#include <vtkTransform.h>
#include <vtkPointData.h>
#include <vtkFeatureEdges.h>
#include <vtkMassProperties.h>
#include <vtkPolyDataNormals.h>
#include <vtkPolyDataMapper.h>
#include <vtkProperty.h>
#include <vtkRenderWindow.h>
#include <vtkRenderer.h>
#include <vtkOBJExporter.h>
#include "logging.h"
#include "world.h"
#include "partition.h"
#include "geometry.h"
#include "vtk_utils.h"
using namespace std;
namespace MCell {
namespace VtkUtils {
enum class ContainmentResult {
Error,
Disjoint,
Identical,
Intersect,
Obj1InObj2,
Obj2InObj1
};
GeometryObject& GeomObjectInfo::get_geometry_object_noconst(World* world) const {
assert(world != nullptr);
assert(for_counted_objects);
Partition& p = world->get_partition(partition_id);
return p.get_geometry_object(geometry_object_id);
}
const GeometryObject& GeomObjectInfo::get_geometry_object(const World* world) const {
assert(world != nullptr);
assert(for_counted_objects);
const Partition& p = world->get_partition(partition_id);
return p.get_geometry_object(geometry_object_id);
}
static vtkSmartPointer<vtkPolyData> convert_geometry_object_to_polydata(
const World* world, const GeometryObject& obj, const bool convert_units = false) {
const Partition& p = world->get_partition(PARTITION_ID_INITIAL);
// we need to convert each geometry object into VTK's polydata representation
// example: https://vtk.org/Wiki/VTK/Examples/Cxx/PolyData/TriangleArea
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> triangles = vtkSmartPointer<vtkCellArray>::New();
// first collect vertices
uint_set<vertex_index_t> vertex_indices;
for (wall_index_t wi: obj.wall_indices) {
const Wall& w = p.get_wall(wi);
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
vertex_indices.insert(w.vertex_indices[i]);
}
}
// store vertices and create mapping
// mcell vertex index -> vtk vertex index
map<vertex_index_t, uint> vertex_mapping;
uint curr_vtk_index = 0;
for (vertex_index_t vi: vertex_indices) {
Vec3 pt = p.get_geometry_vertex(vi);
if (convert_units) {
pt = pt * Vec3(world->config.length_unit);
}
points->InsertNextPoint(pt.x, pt.y, pt.z);
vertex_mapping[vi] = curr_vtk_index;
curr_vtk_index++;
}
// store triangles
for (wall_index_t wi: obj.wall_indices) {
const Wall& w = p.get_wall(wi);
vtkSmartPointer<vtkTriangle> triangle = vtkSmartPointer<vtkTriangle>::New();
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
triangle->GetPointIds()->SetId(i, vertex_mapping[w.vertex_indices[i]]);
}
triangles->InsertNextCell(triangle);
}
// create input polydata
vtkSmartPointer<vtkPolyData> polydata = vtkSmartPointer<vtkPolyData>::New();
polydata->SetPoints(points);
polydata->SetPolys(triangles);
// clean them up
vtkSmartPointer<vtkTriangleFilter> tri = vtkSmartPointer<vtkTriangleFilter>::New();
tri->SetInputData(polydata);
vtkSmartPointer<vtkCleanPolyData> clean = vtkSmartPointer<vtkCleanPolyData>::New();
clean->SetInputConnection(tri->GetOutputPort());
clean->Update();
// also copy this information to our object
return clean->GetOutput();
}
static bool convert_objects_to_clean_polydata(World* world, GeomObjectInfoVector& counted_objects) {
bool res = true;
for (GeomObjectInfo& obj_info: counted_objects) {
GeometryObject& obj = world->get_geometry_object(obj_info.geometry_object_id);
vtkSmartPointer<vtkPolyData> polydata = convert_geometry_object_to_polydata(world, obj);
int closed = vtkSelectEnclosedPoints::IsSurfaceClosed(polydata.Get());
if (closed != 1) {
mcell_warn("Counting object must be closed, error for %s.", obj.name.c_str());
res = false;
continue;
}
// copy a reference to object info as well
obj_info.polydata = polydata;
}
return res;
}
// the objects do not collide
static bool is_noncolliding_obj1_fully_contained_in_obj2(vtkSmartPointer<vtkPolyData> poly1, vtkSmartPointer<vtkPolyData> poly2) {
// NOTE: it will be sufficient to check just one point whether it is outside since we know that there is no intersect,
// optimize in the future
// is the object contained?
auto select_enclosed_points = vtkSmartPointer<vtkSelectEnclosedPoints>::New();
select_enclosed_points->SetSurfaceData(poly2); // poly 2 is supposed to be the larger object
select_enclosed_points->SetInputData(poly1); // and we are trying whether poly1 fits into that
select_enclosed_points->Update();
vtkDataArray* inside_array = vtkDataArray::SafeDownCast(
select_enclosed_points->GetOutput()->GetPointData()->GetAbstractArray("SelectedPoints"));
for(vtkIdType i = 0; i < inside_array->GetNumberOfTuples(); i++)
{
if(inside_array->GetComponent(i,0) == 1)
{
// there was no collision so if any of the points is inside, the object is inside
return true;
}
}
return false;
}
static bool objs_have_identical_points(vtkSmartPointer<vtkPolyData> poly1, vtkSmartPointer<vtkPolyData> poly2) {
vtkSmartPointer<vtkPoints> points1 = poly1->GetPoints();
vtkSmartPointer<vtkPoints> points2 = poly2->GetPoints();
vtkIdType num_points1 = points1->GetNumberOfPoints();
vtkIdType num_points2 = points2->GetNumberOfPoints();
if (num_points1 != num_points2) {
return false;
}
bool all_same = true;
double verts1[3];
double verts2[3];
for(vtkIdType i = 0; i < num_points1; i++)
{
points1->GetPoint(i, verts1);
points2->GetPoint(i, verts2);
if (verts1[0] != verts2[0] || verts1[1] != verts2[1] || verts1[2] != verts2[2])
{
return false;
}
}
return all_same;
}
static ContainmentResult geom_object_containment_test(vtkSmartPointer<vtkPolyData> poly1, vtkSmartPointer<vtkPolyData> poly2) {
// counting objects must be closed (already checked during conversion)
assert(vtkSelectEnclosedPoints::IsSurfaceClosed(poly1) == 1);
assert(vtkSelectEnclosedPoints::IsSurfaceClosed(poly2) == 1);
// 1) do they collide?
auto matrix1 = vtkSmartPointer<vtkMatrix4x4>::New();
auto transform0 = vtkSmartPointer<vtkTransform>::New();
vtkSmartPointer<vtkCollisionDetectionFilter> collide = vtkSmartPointer<vtkCollisionDetectionFilter>::New();
collide->SetInputData( 0, poly1);
collide->SetTransform(0, transform0);
collide->SetInputData( 1, poly2);
collide->SetMatrix(1, matrix1);
collide->SetBoxTolerance(0.0);
collide->SetCellTolerance(0.0);
collide->SetNumberOfCellsPerNode(2);
collide->SetCollisionModeToFirstContact();
collide->GenerateScalarsOn();
collide->Update();
if (collide->GetNumberOfContacts() == 0) {
// objects do not collide
if (is_noncolliding_obj1_fully_contained_in_obj2(poly1, poly2)) {
return ContainmentResult::Obj1InObj2;
}
else if (is_noncolliding_obj1_fully_contained_in_obj2(poly2, poly1)) {
return ContainmentResult::Obj2InObj1;
}
else {
return ContainmentResult::Disjoint;
}
}
else {
// the objects collide
if (objs_have_identical_points(poly1, poly2)) {
// do not necessarily have to be identical, but let's assume that if the points are the same,
// the objects are the same
return ContainmentResult::Identical;
}
else {
return ContainmentResult::Intersect;
#if 0
// this is how intersect is computed once it will be needed
vtkSmartPointer<vtkBooleanOperationPolyDataFilter> booleanOperation =
vtkSmartPointer<vtkBooleanOperationPolyDataFilter>::New();
booleanOperation->SetOperationToIntersection();
booleanOperation->SetInputData( 0, poly1 );
booleanOperation->SetInputData( 1, poly2 );
booleanOperation->Update();
#endif
}
}
}
// returns false if theee was any error
bool compute_containement_mapping(
const World* world, const GeomObjectInfoVector& counted_objects,
ContainmentMap& contained_in_mapping,
IntersectingSet& intersecting_objects
) {
// keep it simple for now, let's just compute 'contained in' relation for each pair of objects
// can be optimized in the future
bool res = true;
contained_in_mapping.clear();
for (uint obj1 = 0; obj1 < counted_objects.size(); obj1++) {
for (uint obj2 = obj1 + 1; obj2 < counted_objects.size(); obj2++) {
ContainmentResult containment_res =
geom_object_containment_test(counted_objects[obj1].polydata, counted_objects[obj2].polydata);
switch (containment_res) {
case ContainmentResult::Obj1InObj2:
contained_in_mapping[counted_objects[obj1]].insert(counted_objects[obj2]);
break;
case ContainmentResult::Obj2InObj1:
contained_in_mapping[counted_objects[obj2]].insert(counted_objects[obj1]);
break;
case ContainmentResult::Disjoint:
// nothing to do
break;
case ContainmentResult::Intersect:
// we are not processing all pairs so we need to insert both object ids
intersecting_objects.insert(counted_objects[obj1]);
intersecting_objects.insert(counted_objects[obj2]);
break;
case ContainmentResult::Identical:
case ContainmentResult::Error: {
std::string fmt;
if (containment_res == ContainmentResult::Identical) {
fmt = "Identical counted objects are not supported yet, error for %s and %s." ;
}
else {
fmt = "Error while of counted object is not supported yet, error for %s and %s.";
}
if (world != nullptr) {
mcell_warn(
fmt.c_str(),
counted_objects[obj1].get_geometry_object(world).name.c_str(),
counted_objects[obj2].get_geometry_object(world).name.c_str()
);
}
else {
mcell_warn(
fmt.c_str(),
counted_objects[obj1].name.c_str(),
counted_objects[obj2].name.c_str()
);
}
res = false;
}
break;
default:
assert(false);
}
}
}
return res;
}
static int get_max_path_length_recursive(
const GeomObjectInfo& child,
const ContainmentMap& contained_in_mapping,
const GeomObjectInfo** best_parent = nullptr) {
// need to find an object that is a direct parent
// we can find it by counting length of paths to from child to an object that has no parents
// E.g., this is the contents of contained_in_mapping and we would like to determine parent of O3
// O3 -> O1, O2
// O2 -> O1
//
// Listing all possible paths from O3:
//
// 1: O3 -> O1
// 2: O3 -> O2 -> O1
//
// the longest is 2:, therefore the direct parent of O3 is O2
// partial overlaps and loops are not allowed here
int max_length = 0;
const auto& it_obj_contained_in = contained_in_mapping.find(child);
if (it_obj_contained_in == contained_in_mapping.end()) {
if (best_parent != nullptr) {
*best_parent = nullptr;
}
return 1; // end, final object
}
for (const GeomObjectInfo& parent: it_obj_contained_in->second) {
int length = get_max_path_length_recursive(parent, contained_in_mapping);
if (length > max_length) {
max_length = length;
if (best_parent != nullptr) {
*best_parent = &parent;
}
}
}
return max_length + 1;
}
const GeomObjectInfo* get_direct_parent_info(
const GeomObjectInfo& obj_info, const ContainmentMap& contained_in_mapping) {
const GeomObjectInfo* best_parent;
get_max_path_length_recursive(obj_info, contained_in_mapping, &best_parent);
return best_parent;
}
static const GeometryObject* get_direct_parent(
const World* world, const GeomObjectInfo& obj_info, const ContainmentMap& contained_in_mapping) {
const GeomObjectInfo* info = get_direct_parent_info(obj_info, contained_in_mapping);
if (info == nullptr) {
return nullptr;
}
else {
return &info->get_geometry_object(world);
}
}
static counted_volume_index_t get_counted_volume_index_using_parents(
World* world,
const geometry_object_id_t obj_id,
const ContainmentMap& contained_in_mapping,
const IntersectingSet& intersecting_objects
) {
// search in this map uses only object id
GeomObjectInfo obj_info(PARTITION_ID_INVALID, obj_id);
if (intersecting_objects.count(obj_info) != 0) {
return COUNTED_VOLUME_INDEX_INTERSECTS;
}
const std::set<GeomObjectInfo>* obj_contained_in;
auto it = contained_in_mapping.find(obj_info);
if (it == contained_in_mapping.end()) {
// not found - has no parent (intersection already checked)
obj_contained_in = nullptr;
}
else {
obj_contained_in = &it->second;
}
// we need to find or add a new counted volume to the partition
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
// first prepare the counted volume
CountedVolume cv;
cv.contained_in_objects.insert(obj_id);
if (obj_contained_in != nullptr) {
for (const GeomObjectInfo& info: *obj_contained_in) {
// if any of the parents intersects, let's assume that for counting this object intersects
// as well, maybe some optimization can be done in the future
if (intersecting_objects.count(info) != 0) {
return COUNTED_VOLUME_INDEX_INTERSECTS;
}
geometry_object_index_t index = p.get_geometry_object(info.geometry_object_id).index;
cv.contained_in_objects.insert_unique(index);
}
}
return p.find_or_add_counted_volume(cv);
}
static void define_counted_volumes(
World* world,
const GeomObjectInfoVector& counted_objects,
const ContainmentMap& contained_in_mapping,
const IntersectingSet& intersecting_objects
) {
for (const GeomObjectInfo& obj_info: counted_objects) {
GeometryObject& current_obj = obj_info.get_geometry_object_noconst(world);
// set inside index for our object
if (intersecting_objects.count(obj_info) != 0) {
// intersects with other objects - not sure in which counted volume
// a molecule ends up when entering this object
current_obj.counted_volume_index_inside = COUNTED_VOLUME_INDEX_INTERSECTS;
}
else {
// does not intersect - get counted volume from its parents
current_obj.counted_volume_index_inside =
get_counted_volume_index_using_parents(
world, obj_info.geometry_object_id, contained_in_mapping, intersecting_objects);
}
const GeometryObject* direct_parent_obj = get_direct_parent(world, obj_info, contained_in_mapping);
// set outside index for our object
counted_volume_index_t outside_index;
// parent was found
if (direct_parent_obj != nullptr) {
outside_index =
get_counted_volume_index_using_parents(
world, direct_parent_obj->id, contained_in_mapping, intersecting_objects);
}
else {
// parent is unclear
if (intersecting_objects.count(obj_info) == 0) {
// this is a top level object that has no parent but still needs a counted volume to be created
outside_index = COUNTED_VOLUME_INDEX_OUTSIDE_ALL;
}
else {
// it is not clear what the outside is
outside_index = COUNTED_VOLUME_INDEX_INTERSECTS;
}
}
current_obj.counted_volume_index_outside = outside_index;
}
}
// return true if counted volumes were correctly set up
// the only entry point to this utility file (so far)
bool initialize_counted_volumes(World* world, bool& has_intersecting_counted_objects) {
GeomObjectInfoVector counted_objects;
// get counted objects
for (const Partition& p: world->get_partitions()) {
for (const GeometryObject& obj: p.get_geometry_objects()) {
if (obj.is_counted_volume_or_compartment()) {
counted_objects.push_back( GeomObjectInfo(p.id, obj.id) );
}
}
}
// prepare VTK polydata objects
convert_objects_to_clean_polydata(world, counted_objects);
// holds mapping that tells in which geometry objects is a given object contained
ContainmentMap contained_in_mapping;
// set of object ids that intersect
IntersectingSet intersecting_objects;
// compute 'contained-in' mapping
bool ok = compute_containement_mapping(world, counted_objects, contained_in_mapping, intersecting_objects);
if (!ok) {
return false;
}
// define counted volumes, sets inside and outside volume id for geometry objects
define_counted_volumes(world, counted_objects, contained_in_mapping, intersecting_objects);
has_intersecting_counted_objects = !intersecting_objects.empty();
return true;
}
#if 0
bool is_point_inside_counted_volume(GeometryObject& obj, const Vec3& point) {
assert(obj.is_counted_volume_or_compartment());
assert(obj.counted_volume_polydata.Get() != nullptr);
double point_coords[3] = {point.x, point.y, point.z};
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
points->InsertNextPoint(point_coords);
vtkSmartPointer<vtkPolyData> points_polydata = vtkSmartPointer<vtkPolyData>::New();
points_polydata->SetPoints(points);
auto select_enclosed_points = vtkSmartPointer<vtkSelectEnclosedPoints>::New();
select_enclosed_points->SetSurfaceData(obj.counted_volume_polydata);
select_enclosed_points->SetInputData(points_polydata); // and we are trying whether poly1 fits into that
select_enclosed_points->Update();
return select_enclosed_points->IsInside(0) ;
}
#endif
static double is_watertight(vtkSmartPointer<vtkPolyData> polydata) {
// check if the object is watertight,
// based on https://lorensen.github.io/VTKExamples/site/Cxx/Meshes/BoundaryEdges/
vtkSmartPointer<vtkFeatureEdges> featureEdges =
vtkSmartPointer<vtkFeatureEdges>::New();
featureEdges->SetInputData(polydata.Get());
featureEdges->BoundaryEdgesOn();
featureEdges->FeatureEdgesOff();
featureEdges->ManifoldEdgesOff();
featureEdges->NonManifoldEdgesOff();
featureEdges->Update();
// if there are no edges, the object is watertight
return featureEdges->GetOutput()->GetNumberOfCells() < 1;
}
// auxiliary function to compute volume, not related to counted volumes but uses VTK
// returns FLT_INVALID if the object is not watertight
double get_geometry_object_volume(const World* world, const GeometryObject& obj) {
vtkSmartPointer<vtkPolyData> polydata = convert_geometry_object_to_polydata(world, obj);
if (!is_watertight(polydata)) {
return FLT_INVALID;
}
// volume computation is based on
// https://lorensen.github.io/VTKExamples/site/Cxx/Utilities/MassProperties/
vtkSmartPointer<vtkTriangleFilter> triangleFilter =
vtkSmartPointer<vtkTriangleFilter>::New();
triangleFilter->SetInputData(polydata);
// Make the triangle windong order consistent
vtkSmartPointer<vtkPolyDataNormals> normals =
vtkSmartPointer<vtkPolyDataNormals>::New();
normals->SetInputConnection(triangleFilter->GetOutputPort());
normals->ConsistencyOn();
normals->SplittingOff();
vtkSmartPointer<vtkMassProperties> massProperties =
vtkSmartPointer<vtkMassProperties>::New();
massProperties->SetInputConnection(normals->GetOutputPort());
massProperties->Update();
return massProperties->GetVolume();
}
void export_geometry_objects_to_obj(
const World* world, const GeometryObjectVector& objs, const std::string& file_prefix) {
vtkNew<vtkRenderer> renderer;
vector<string> names;
for (const GeometryObject& o: objs) {
// convert objects
vtkSmartPointer<vtkPolyData> polydata =
convert_geometry_object_to_polydata(world, o, true);
vtkNew<vtkPolyDataMapper> mapper;
mapper->SetInputData(polydata);
vtkNew<vtkActor> actor;
actor->SetMapper(mapper);
// material, the default is white with 25% transparency
// note: same as DEFAULT_COLOR
actor->GetProperty()->SetDiffuseColor(1, 1, 1);
actor->GetProperty()->SetOpacity(0.25);
renderer->AddActor(actor);
// we must also set names to the exported objects,
// there is no support for object names in VTK and
// the OBJ exporter needed to be updated
names.push_back(o.name);
}
vtkNew<vtkRenderWindow> window;
window->AddRenderer(renderer);
vtkNew<vtkOBJExporter> exporter;
exporter->SetRenderWindow(window);
exporter->SetFilePrefix(file_prefix.c_str());
exporter->SetActorNames(names); // custom MCell method
exporter->Write();
}
} // namespace VtkUtils
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/release_event.cpp | .cpp | 44,760 | 1,322 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "rng.h" // MCell 3
#include "isaac64.h"
#include "mcell_structs_shared.h"
#include "logging.h"
#include <iostream>
#include <algorithm>
#include "defines.h"
#include "release_event.h"
#include "world.h"
#include "partition.h"
#include "diffuse_react_event.h"
#include "datamodel_defines.h"
#include "geometry_utils.h"
#include "geometry_utils.inl"
#include "collision_utils.inl"
#include "grid_utils.inl"
using namespace std;
namespace MCell {
void dump_cumm_area_and_pwall_index_pairs(
const std::vector<CummAreaPWallIndexPair>& cumm_area_and_pwall_index_pairs, const std::string ind) {
cout << ind << "cumm_area_and_pwall_index_pairs:\n";
size_t max = cumm_area_and_pwall_index_pairs.size();
#ifdef NDEBUG
if (max > 4) {
cout << ind << "Printing only the first 4 of " << max << "\n";
max = 4;
}
#endif
for (size_t i = 0; i < max; i++) {
cout << ind << i << ": ";
const CummAreaPWallIndexPair& area_wall = cumm_area_and_pwall_index_pairs[i];
cout <<
"area: " << area_wall.first << ", partition_id: " << area_wall.second.first <<
", wall_index: " << area_wall.second.first << "\n";
}
}
size_t cum_area_bisect_high(const std::vector<CummAreaPWallIndexPair>& array, double val) {
size_t low = 0;
size_t hi = array.size() - 1;
size_t mid = 0;
while (hi - low > 1) {
mid = (hi + low) / 2;
if (array[mid].first > val) {
hi = mid;
} else {
low = mid;
}
}
if (array[low].first > val)
{
return low;
}
else {
return hi;
}
}
void ReleaseEvent::report_release_failure(const std::string& msg) {
switch (world->config.molecule_placement_failure) {
case API::WarningLevel::IGNORE:
notifys() << msg << "\n";
break;
case API::WarningLevel::WARNING:
warns() << msg << "\n";
break;
case API::WarningLevel::ERROR:
errs() << msg << "\n";
exit(1);
break;
}
}
bool ReleaseEvent::update_event_time_for_next_scheduled_time() {
// see https://mcell.org/tutorials/_images/plot.png
assert(number_of_trains == NUMBER_OF_TRAINS_UNLIMITED || current_train_from_0 <= number_of_trains);
// did we process all trains?
if (current_train_from_0 == number_of_trains) {
return false;
}
// set the new times for schedule
actual_release_time =
delay +
current_train_from_0 * train_interval +
current_release_in_train_from_0 * release_interval;
// floor_to_multiple adds EPS to the value before flooring
event_time = floor_to_multiple_f(actual_release_time, 1);
// increment release counter
current_release_in_train_from_0++;
// should we start a new train next time this method is called?
int number_of_releases_per_train = get_num_releases_per_train();
assert(number_of_releases_per_train >= 1);
assert(current_release_in_train_from_0 <= number_of_releases_per_train);
if (current_release_in_train_from_0 == number_of_releases_per_train) {
current_train_from_0++;
current_release_in_train_from_0 = 0;
}
return true;
}
#define CASE_TO_STR(name) case name: return #name
static const char* release_shape_to_str(const ReleaseShape s) {
switch (s) {
CASE_TO_STR(ReleaseShape::UNDEFINED);
CASE_TO_STR(ReleaseShape::SPHERICAL);
CASE_TO_STR(ReleaseShape::SPHERICAL_SHELL);
CASE_TO_STR(ReleaseShape::REGION);
CASE_TO_STR(ReleaseShape::LIST);
CASE_TO_STR(ReleaseShape::INITIAL_SURF_REGION);
default: return "invalid_release_shape";
}
}
static const char* release_number_method_to_str(const ReleaseNumberMethod m) {
switch (m) {
CASE_TO_STR(ReleaseNumberMethod::INVALID);
CASE_TO_STR(ReleaseNumberMethod::CONST_NUM);
CASE_TO_STR(ReleaseNumberMethod::GAUSS_NUM);
CASE_TO_STR(ReleaseNumberMethod::VOL_NUM);
CASE_TO_STR(ReleaseNumberMethod::CONCENTRATION_NUM);
CASE_TO_STR(ReleaseNumberMethod::DENSITY_NUM);
default: return "invalid_release_number_method";
}
}
void ReleaseEvent::dump(const string ind) const {
cout << "Release event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
cout << ind2 << "name: \t\t" << release_site_name << " [string]\n";
cout << ind2 << "species_id: \t\t" << species_id << " [species_id_t]\n";
cout << ind2 << "actual_release_time: \t\t" << actual_release_time << " [double]\n";
cout << ind2 << "release_number_method: \t\t" << release_number_method_to_str(release_number_method) << " [ReleaseNumberMethod]\n";
cout << ind2 << "release_number: \t\t" << release_number << " [uint]\n";
cout << ind2 << "concentration: \t\t" << concentration << " [double]\n";
cout << ind2 << "orientation: \t\t" << orientation << " [double]\n";
cout << ind2 << "release_shape: \t\t" << release_shape_to_str(release_shape) << " [ReleaseShape]\n";
cout << ind2 << "location: \t\t" << location << " [Vec3]\n";
cout << ind2 << "diameter: \t\t" << diameter << " [Vec3]\n";
dump_cumm_area_and_pwall_index_pairs(cumm_area_and_pwall_index_pairs, ind2);
cout << ind2 << "region_llf: \t\t" << region_llf << " [Vec3]\n";
cout << ind2 << "region_urb: \t\t" << region_urb << " [Vec3]\n";
if (region_expr.root != nullptr) {
region_expr.root->dump(world);
}
cout << ind2 << "delay: \t\t" << delay << " [double]\n";
cout << ind2 << "number_of_trains: \t\t" << number_of_trains << " [uint]\n";
cout << ind2 << "train_interval: \t\t" << train_interval << " [double]\n";
cout << ind2 << "train_duration: \t\t" << train_duration << " [double]\n";
cout << ind2 << "release_interval: \t\t" << release_interval << " [double]\n";
}
// returns the name of the release pattern,
// empty string if release pattern is not needed
std::string ReleaseEvent::release_pattern_to_data_model(Json::Value& mcell_node) const {
if (!needs_release_pattern()) {
// no release pattern is needed
return "";
}
Json::Value& define_release_patterns = mcell_node[KEY_DEFINE_RELEASE_PATTERNS];
// version might be already there
if (define_release_patterns.isMember(KEY_DATA_MODEL_VERSION)) {
DMUtils::add_version(define_release_patterns, VER_DM_2014_10_24_1638);
}
Json::Value& release_pattern_list = define_release_patterns[KEY_RELEASE_PATTERN_LIST];
string name;
if (release_pattern_name != "") {
// should be usually set when rel pat is needed
name = release_pattern_name;
}
else {
name = RELEASE_PATTERN_PREFIX + release_site_name;
}
// the current pattern may be already present, skip it in this case,
// release patterns must have unique names, checked while MDL is parsed
// TODO: is this true also for MCell4?
for (Json::ArrayIndex i = 0; i < release_pattern_list.size(); i++) {
if (release_pattern_list[i][KEY_NAME].asString() == release_pattern_name) {
return name;
}
}
Json::Value release_pattern_item;
DMUtils::add_version(release_pattern_item, VER_DM_2018_01_11_1330);
release_pattern_item[KEY_DELAY] = f_to_str(delay * world->config.time_unit);
release_pattern_item[KEY_NUMBER_OF_TRAINS] = to_string(number_of_trains);
release_pattern_item[KEY_TRAIN_INTERVAL] = f_to_str(train_interval * world->config.time_unit);
release_pattern_item[KEY_TRAIN_DURATION] = f_to_str(train_duration * world->config.time_unit);
release_pattern_item[KEY_RELEASE_INTERVAL] = f_to_str(release_interval * world->config.time_unit);
release_pattern_item[KEY_NAME] = name;
release_pattern_item[KEY_DESCRIPTION] = "";
release_pattern_list.append(release_pattern_item);
return name;
}
void ReleaseEvent::to_data_model_as_one_release_site(
Json::Value& mcell_node,
const species_id_t species_id_override,
const orientation_t orientation_override,
// points_list indices are set only when
// release_shape == ReleaseShape::LIST
const string& name_override,
const uint points_list_begin_index,
const uint points_list_end_index
) const {
// these items might already exist
Json::Value& release_sites = mcell_node[KEY_RELEASE_SITES];
DMUtils::add_version(release_sites, VER_DM_2014_10_24_1638);
Json::Value& release_site_list = release_sites[KEY_RELEASE_SITE_LIST];
Json::Value release_site;
DMUtils::add_version(release_site, VER_DM_2018_01_11_1330);
release_site[KEY_DESCRIPTION] = "";
release_site[KEY_NAME] = DMUtils::remove_obj_name_prefix(name_override);
release_site[KEY_MOLECULE] = world->get_all_species().get(species_id_override).name;
release_site[KEY_ORIENT] = DMUtils::orientation_to_str(orientation_override);
// how many to release
switch (release_number_method) {
case ReleaseNumberMethod::CONST_NUM:
release_site[KEY_QUANTITY_TYPE] = VALUE_NUMBER_TO_RELEASE;
if (release_shape != ReleaseShape::LIST) {
release_site[KEY_QUANTITY] = to_string(release_number);
}
else {
release_site[KEY_QUANTITY] = ""; // number for release of LIST is given by the number of points
}
break;
case ReleaseNumberMethod::GAUSS_NUM:
release_site[KEY_QUANTITY_TYPE] = VALUE_GAUSSIAN_RELEASE_NUMBER;
CONVERSION_UNSUPPORTED("Release event " + release_site_name + " has unsupported release_number_method GaussNum.");
break;
case ReleaseNumberMethod::VOL_NUM:
CONVERSION_UNSUPPORTED("Release event " + release_site_name + " has unsupported release_number_method VolNum.");
break;
case ReleaseNumberMethod::CONCENTRATION_NUM:
case ReleaseNumberMethod::DENSITY_NUM:
release_site[KEY_QUANTITY_TYPE] = VALUE_DENSITY;
release_site[KEY_QUANTITY] = f_to_str(concentration);
break;
default:
CONVERSION_UNSUPPORTED("Release event " + release_site_name + " has invalid release_number_method.");
break;
}
string data_model_release_pattern_name = release_pattern_to_data_model(mcell_node);
release_site[KEY_PATTERN] = data_model_release_pattern_name;
release_site[KEY_STDDEV] = "0"; // TODO
release_site[KEY_RELEASE_PROBABILITY] = f_to_str(release_probability);
// where to release
switch (release_shape) {
case ReleaseShape::SPHERICAL:
release_site[KEY_SHAPE] = VALUE_SPHERICAL;
break;
case ReleaseShape::SPHERICAL_SHELL:
release_site[KEY_SHAPE] = VALUE_SPHERICAL_SHELL;
break;
case ReleaseShape::REGION:
release_site[KEY_SHAPE] = VALUE_OBJECT;
release_site[KEY_OBJECT_EXPR] = region_expr.root->to_string(world, true);
break;
case ReleaseShape::LIST:
release_site[KEY_SHAPE] = VALUE_LIST;
break;
default:
CONVERSION_UNSUPPORTED("Release event " + release_site_name + " has shape different from SHPERE and OBJECT.");
break;
}
if (release_shape != ReleaseShape::REGION) {
if (release_shape != ReleaseShape::LIST) {
release_site[KEY_LOCATION_X] = f_to_str(location.x * world->config.length_unit);
release_site[KEY_LOCATION_Y] = f_to_str(location.y * world->config.length_unit);
release_site[KEY_LOCATION_Z] = f_to_str(location.z * world->config.length_unit);
}
else {
assert(points_list_begin_index < points_list_end_index);
Json::Value& points_list = release_site[KEY_POINTS_LIST];
for (uint i = points_list_begin_index; i < points_list_end_index; i++) {
assert(i < molecule_list.size());
Vec3 pos_scaled = molecule_list[i].pos * Vec3(world->config.length_unit);
DMUtils::append_triplet(points_list, pos_scaled.x, pos_scaled.y, pos_scaled.z);
}
}
CONVERSION_CHECK(diameter.x == diameter.y && diameter.y == diameter.z, "Datamodel does not support different diameters.");
release_site[KEY_SITE_DIAMETER] = f_to_str(diameter.x * world->config.length_unit);
}
release_site_list.append(release_site);
}
void ReleaseEvent::to_data_model(Json::Value& mcell_node) const {
if (event_time != 0 && !needs_release_pattern()) {
// the MCell4 API supports this, but there is not way how to store it into data model
// TODO: extend data model? - or implement using release patterns?
mcell_warn(
"Release event %s starts at time different from 0, conversion to data model is not supported yet, ignoring it.",
release_site_name.c_str()
);
return;
}
if (release_shape == ReleaseShape::INITIAL_SURF_REGION) {
// not converting this one - is default
}
else if (release_shape == ReleaseShape::LIST) {
// this release event needs to be split into chunks that use the same
// species and orientation
uint release_site_index = 0;
uint current_index = 0;
do {
uint begin_index = current_index;
species_id_t current_species_id = molecule_list[current_index].species_id;
orientation_t current_orientation = molecule_list[current_index].orientation;
// find the largest chunk we can convert as a single release site
do {
current_index++;
} while (
current_index < molecule_list.size() &&
molecule_list[current_index].species_id == current_species_id &&
molecule_list[current_index].orientation == current_orientation
);
string name;
if (begin_index == 0 && current_index == molecule_list.size()) {
// we are going to generate a single release site
name = release_site_name;
}
else {
// more release sites - append index
name = release_site_name + "_" + to_string(release_site_index);
}
to_data_model_as_one_release_site(
mcell_node, current_species_id, current_orientation, name, begin_index, current_index
);
release_site_index++;
} while (current_index < molecule_list.size());
}
else {
// usual case, generate a single release site
to_data_model_as_one_release_site(
mcell_node, species_id, orientation, release_site_name, 0, 0
);
}
}
static void get_walls_for_release_recursively(
const Partition& p, const RegionExprNode* node,
set<wall_index_t>& walls_for_release) {
walls_for_release.clear();
if (node->op == RegionExprOperator::LEAF_SURFACE_REGION) {
// simply collect all walls of this region
const Region& reg = p.get_region_by_id(node->region_id);
for (auto& it: reg.walls_and_edges) {
walls_for_release.insert(it.first);
}
}
else if (node->has_binary_op()) {
set<wall_index_t> walls_left, walls_right;
get_walls_for_release_recursively(p, node->left, walls_left);
get_walls_for_release_recursively(p, node->right, walls_right);
switch (node->op) {
case RegionExprOperator::UNION:
std::set_union(
walls_left.begin(), walls_left.end(),
walls_right.begin(), walls_right.end(),
std::inserter(walls_for_release, walls_for_release.begin()));
break;
case RegionExprOperator::INTERSECT:
std::set_intersection(
walls_left.begin(), walls_left.end(),
walls_right.begin(), walls_right.end(),
std::inserter(walls_for_release, walls_for_release.begin()));
break;
case RegionExprOperator::DIFFERENCE:
std::set_difference(
walls_left.begin(), walls_left.end(),
walls_right.begin(), walls_right.end(),
std::inserter(walls_for_release, walls_for_release.begin()));
break;
default:
assert(false);
}
}
else {
assert(false && "Geometry objects are not allowed in surf region release");
}
}
bool ReleaseEvent::initialize_walls_for_release() {
assert(region_expr.root != nullptr);
assert(release_number_method != ReleaseNumberMethod::INVALID);
cumm_area_and_pwall_index_pairs.clear();
// no need to initialize
const BNG::Species& species = world->get_all_species().get(species_id);
if (species.is_vol() &&
(release_number_method == ReleaseNumberMethod::CONST_NUM ||
release_number_method == ReleaseNumberMethod::CONCENTRATION_NUM
)
) {
// no need to initialize walls for this case
return true;
}
// only a single partition for now
const Partition& p = world->get_partition(PARTITION_ID_INITIAL);
set<wall_index_t> wall_for_release;
get_walls_for_release_recursively(p, region_expr.root, wall_for_release);
// assuming that iterating over std::set is ordered
for (wall_index_t wi: wall_for_release) {
const Wall& w = world->get_partition(PARTITION_ID_INITIAL).get_wall(wi);
CummAreaPWallIndexPair item;
item.first = w.area;
item.second.first = PARTITION_ID_INITIAL;
item.second.second = wi;
if (!cumm_area_and_pwall_index_pairs.empty()) {
item.first += cumm_area_and_pwall_index_pairs.back().first;
}
cumm_area_and_pwall_index_pairs.push_back(item);
}
return true;
}
static void check_max_release_count(double num_to_release, const std::string& name) {
long long num = (long long)num_to_release;
if (num < 0 || num > (long long)INT_MAX) {
mcell_error(
"Release site '%s' tries to release more than INT_MAX (2147483647) molecules, "
"the unit for concentration-based release into volume is M/l (molar) and "
"for density-based release onto surface is N/um^2 (molecules per square micron).",
name.c_str());
}
}
uint ReleaseEvent::calculate_number_to_release() {
switch (release_number_method) {
case ReleaseNumberMethod::CONST_NUM:
return release_number;
case ReleaseNumberMethod::CONCENTRATION_NUM:
if (diameter == Vec3(LENGTH_INVALID)) {
// set for instance for ReleaseShape::SPHERICAL
return 0;
}
else {
double vol;
switch (release_shape) {
case ReleaseShape::SPHERICAL:
//case ReleaseShape::ELLIPTIC:
vol = (1.0 / 6.0) * MY_PI * diameter.x * diameter.y * diameter.z;
break;
/*case SHAPE_RECTANGULAR:
case SHAPE_CUBIC:
vol = rso->diameter->x * rso->diameter->y * rso->diameter->z;
break;*/
case ReleaseShape::SPHERICAL_SHELL:
mcell_error("Release site \"%s\" tries to release a concentration on a "
"spherical shell.", release_site_name.c_str());
return 0;
break;
case ReleaseShape::REGION:
// number is computed in release_inside_regions
return 0;
default:
mcell_internal_error("Release by concentration on invalid release site "
"shape (%d) for release site \"%s\".",
(int)release_shape, release_site_name.c_str());
return 0;
break;
}
assert(concentration != FLT_INVALID);
double num_to_release =
N_AV * 1e-15 * concentration * vol * pow_f(world->config.length_unit, 3.0) + 0.5;
check_max_release_count(num_to_release, release_site_name);
return (uint)num_to_release;
}
break;
case ReleaseNumberMethod::DENSITY_NUM: {
// computed in release_onto_regions in MCell3
assert(!cumm_area_and_pwall_index_pairs.empty());
double max_A = cumm_area_and_pwall_index_pairs.back().first;
double est_sites_avail = (int)max_A;
assert(concentration != FLT_INVALID);
double num_to_release = concentration * est_sites_avail / world->config.grid_density;
check_max_release_count(num_to_release, release_site_name);
return (uint)num_to_release;
}
break;
default:
assert(false);
return 0;
}
}
// returns the number of actually removed molecules
int ReleaseEvent::randomly_remove_molecules(
Partition& p, const MoleculeIdsVector& mol_ids_in_region, int number_to_remove) {
// randomly remove molecules
int num_removed = 0;
for (size_t i = 0; i < mol_ids_in_region.size(); i++) {
molecule_id_t m_id = mol_ids_in_region[i];
int remaining = mol_ids_in_region.size() - i;
if (rng_dbl(&world->rng) < ((double)(number_to_remove)) / ((double)remaining)) {
p.set_molecule_as_defunct(p.get_m(m_id));
num_removed++;
number_to_remove--;
}
}
release_assert(number_to_remove >= 0);
return num_removed;
}
/***************************************************************************
vacuum_from_regions:
Molecules of the specified type are
removed uniformly at random from the free area in the regions
specified by the release site object.
Note: if the user requests to remove more molecules than actually exist,
the function will return success and not give a warning.
***************************************************************************/
int ReleaseEvent::vacuum_from_regions(int number_to_remove) {
assert(!cumm_area_and_pwall_index_pairs.empty());
assert(number_to_remove > 0);
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
MoleculeIdsVector mol_ids_on_region;
for (auto& item: cumm_area_and_pwall_index_pairs) {
assert(item.second.first == PARTITION_ID_INITIAL);
const Wall& w = p.get_wall(item.second.second);
for (molecule_id_t m_id: w.grid.get_molecules_per_tile()) {
if (m_id != MOLECULE_ID_INVALID) {
const Molecule& m = p.get_m(m_id);
assert(m.is_surf());
if (m.is_defunct()) {
continue;
}
if (m.species_id != species_id) {
continue;
}
// NOTE: MCell3 does not care about orientation
if (orientation != ORIENTATION_NONE && m.s.orientation != orientation) {
continue;
}
mol_ids_on_region.push_back(m_id);
}
}
}
return randomly_remove_molecules(p, mol_ids_on_region, number_to_remove);
}
void ReleaseEvent::release_onto_regions(int& computed_release_number) {
int success = 0, failure = 0;
double seek_cost = 0;
assert(!cumm_area_and_pwall_index_pairs.empty());
double total_area = cumm_area_and_pwall_index_pairs.back().first; // extending to double
double est_sites_avail = (int)total_area;
const double rel_list_gen_cost = 10.0; /* Just a guess */
double pick_cost = rel_list_gen_cost * est_sites_avail;
int n = computed_release_number;
if (n < 0) {
computed_release_number = -vacuum_from_regions(-n);
return;
}
const int too_many_failures = 10; /* Just a guess */
while (n > 0) {
if (failure >= success + too_many_failures) {
seek_cost =
n * (((double)(success + failure + 2)) / ((double)(success + 1)));
}
if (seek_cost < pick_cost) {
double A = rng_dbl(&world->rng) * total_area;
size_t cum_area_index = cum_area_bisect_high(cumm_area_and_pwall_index_pairs, A);
PartitionWallIndexPair pw = cumm_area_and_pwall_index_pairs[cum_area_index].second;
Partition& p = world->get_partition(pw.first);
Wall& wall = p.get_wall(pw.second);
if (!wall.has_initialized_grid()) {
wall.initialize_grid(p); // sets wall's grid_index
}
Grid& grid = wall.grid;
// get the random number for the current wall
if (cum_area_index != 0) {
A -= cumm_area_and_pwall_index_pairs[cum_area_index - 1].first;
}
tile_index_t tile_index = (grid.num_tiles_along_axis * grid.num_tiles_along_axis) * (A / wall.area);
if (tile_index >= grid.num_tiles) {
tile_index = grid.num_tiles - 1;
}
if (grid.get_molecule_on_tile(tile_index) != MOLECULE_ID_INVALID) {
failure++;
continue;
}
molecule_id_t sm_id =
GridUtils::place_single_molecule_onto_grid(
p, world->rng, wall, tile_index, false, Vec2(),
species_id, orientation, event_time, get_release_delay_time()
);
schedule_for_immediate_diffusion_if_needed(sm_id, WallTileIndexPair(wall.index, tile_index));
#ifdef DEBUG_RELEASES
p.get_m(sm_id).dump(p, "Released sm:", "", p.stats.get_current_iteration(), actual_release_time, true);
#endif
success++;
n--;
}
else {
// simply choose the first empty tiles
// behaves correctly but not randomly (but it should not really matter)
// MCell3 uses a similar strategy
int placed = 0;
for (auto& pair_a_pindex: cumm_area_and_pwall_index_pairs) {
Partition& p = world->get_partition(pair_a_pindex.second.first);
wall_index_t wi = pair_a_pindex.second.second;
Wall& wall = p.get_wall(wi);
if (!wall.has_initialized_grid()) {
wall.initialize_grid(p);
}
const Grid& grid = wall.grid;
if (grid.get_num_free_tiles() == 0) {
continue;
}
for (tile_index_t ti = 0; ti < grid.get_molecules_per_tile().size(); ti++) {
if (grid.get_molecule_on_tile(ti) == MOLECULE_ID_INVALID) {
// place molecule onto this tile
molecule_id_t sm_id =
GridUtils::place_single_molecule_onto_grid(
p, world->rng, wall, ti, false, Vec2(),
species_id, orientation, event_time, get_release_delay_time()
);
schedule_for_immediate_diffusion_if_needed(sm_id, WallTileIndexPair(wi, ti));
#ifdef DEBUG_RELEASES
p.get_m(sm_id).dump(p, "Released sm:", "", p.stats.get_current_iteration(), actual_release_time, true);
#endif
success++;
n--;
}
if (n == 0) {
break;
}
}
if (n == 0) {
break;
}
}
if (n > 0) {
// prepare detailed information for error message
uint total_tiles = 0;
uint free_tiles = 0;
for (const auto& area_index_pair: cumm_area_and_pwall_index_pairs) {
PartitionWallIndexPair pw = area_index_pair.second;
const Partition& p = world->get_partition(pw.first);
const Wall& w = p.get_wall(pw.second);
total_tiles += w.grid.num_tiles;
free_tiles += w.grid.get_num_free_tiles();
}
// TODO_LATER: MCell3 handles these cases better, however we were able to fill the whole
// region even with this implementation
const BNG::Species& species = world->get_all_species().get(species_id);
stringstream msg;
msg << "Could not release " << n << " of total " << computed_release_number << " of " << species.name <<
" at " << release_site_name << ", too many failed attempts to place surface molecules. "
"The surface region has total of " << total_tiles << " tiles and " << free_tiles <<
" were left empty after release attempts.";
report_release_failure(msg.str());
// how many molecules did we place
computed_release_number = computed_release_number - n;
break;
}
}
}
}
bool ReleaseEvent::is_point_inside_region_expr_recursively(Partition& p, const Vec3& pos, const RegionExprNode* region_expr_node) {
assert(region_expr_node->op != RegionExprOperator::INVALID);
if (region_expr_node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
const GeometryObject& go = p.get_geometry_object(region_expr_node->geometry_object_id);
Region& reg = p.get_region_by_id(go.encompassing_region_id);
return reg.is_point_inside(p, pos);
}
else if (region_expr_node->op == RegionExprOperator::LEAF_SURFACE_REGION) {
release_assert(false && "This method may be called only for volume regions.");
}
bool satisfies_l = is_point_inside_region_expr_recursively(p, pos, region_expr_node->left);
bool satisfies_r = is_point_inside_region_expr_recursively(p, pos, region_expr_node->right);
switch (region_expr_node->op) {
case RegionExprOperator::UNION:
return satisfies_l || satisfies_r;
case RegionExprOperator::INTERSECT:
return satisfies_l && satisfies_r;
case RegionExprOperator::DIFFERENCE:
return satisfies_l && !satisfies_r;
default:
assert(false);
return false;
}
}
/*
* num_vol_mols_from_conc computes the number of volume molecules to be
* released within a closed object. There are two cases:
* - for a single closed object we know the exact volume and can thus compute
* the exact number of molecules required and release them by setting
* exactNumber to true.
* - for a release object consisting of a boolean expression of closed objects
* we are currently not able to compute the volume exactly. Instead we compute
* the number of molecules in the bounding box and then release an approximate
* number by setting exactNumber to false.
*/
uint ReleaseEvent::num_vol_mols_from_conc(bool &exact_number) {
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
double vol = 0.0;
if (region_expr.root->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
const GeometryObject& go = p.get_geometry_object_by_id(region_expr.root->geometry_object_id);
Region& r = p.get_region_by_id(go.encompassing_region_id);
r.initialize_volume_info_if_needed(p);
release_assert(r.is_manifold() && "Trying to release into a regions that is not a manifold and has no volume");
vol = r.get_volume();
exact_number = true;
}
else if (region_expr.root->op == RegionExprOperator::LEAF_SURFACE_REGION) {
release_assert(false);
}
else {
// estimate the volume
vol =
(region_urb.x - region_llf.x) *
(region_urb.y - region_llf.y) *
(region_urb.z - region_llf.z);
exact_number = false;
}
double num_to_release =
N_AV * 1e-15 * concentration * vol * pow_f(world->config.length_unit, 3) + 0.5;
check_max_release_count(num_to_release, release_site_name);
return num_to_release;
}
/*************************************************************************
vacuum_inside_regions:
Note: if more molecules are to be removed than actually exist, all
existing molecules of the specified type are removed.
Returns number of actually removed molecules.
*************************************************************************/
int ReleaseEvent::vacuum_inside_regions(int number_to_remove) {
assert(number_to_remove > 0);
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
MoleculeIdsVector mol_ids_in_region;
// get all molecules that match the removed species
// MCell3 knows which molecules are in which subparts, we don't know this
// so we must go through all molecule
for (const Molecule& m: p.get_molecules()) {
if (m.is_defunct()) {
continue;
}
if (m.species_id != species_id) {
continue;
}
release_assert(m.is_vol());
// filter by bounding box
if (!point_in_box(m.v.pos, region_llf, region_urb)) {
continue;
}
// then precisely by region
if (!is_point_inside_region_expr_recursively(p, m.v.pos, region_expr.root)) {
continue;
}
mol_ids_in_region.push_back(m.id);
}
return randomly_remove_molecules(p, mol_ids_in_region, number_to_remove);
}
/*************************************************************************
release_inside_regions:
Note: if the CCNNUM release method is used, the number of molecules
passed in is ignored.
*************************************************************************/
void ReleaseEvent::release_inside_regions(int& computed_release_number) {
assert(region_expr.root != nullptr);
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
bool exact_number = false;
if (release_number_method == ReleaseNumberMethod::CONCENTRATION_NUM) {
computed_release_number = num_vol_mols_from_conc(exact_number);
}
int n = computed_release_number;
if (n < 0) {
computed_release_number = -vacuum_inside_regions(-n);
return;
}
while (n > 0) {
Vec3 pos;
pos.x = region_llf.x + (region_urb.x - region_llf.x) * rng_dbl(&world->rng);
pos.y = region_llf.y + (region_urb.y - region_llf.y) * rng_dbl(&world->rng);
pos.z = region_llf.z + (region_urb.z - region_llf.z) * rng_dbl(&world->rng);
if (!is_point_inside_region_expr_recursively(p, pos, region_expr.root)) {
if (release_number_method == ReleaseNumberMethod::CONCENTRATION_NUM && !exact_number) {
computed_release_number--;
n--;
}
continue;
}
Molecule& new_vm = p.add_volume_molecule(
Molecule(MOLECULE_ID_INVALID, species_id, pos, event_time), get_release_delay_time()
);
new_vm.set_flag(MOLECULE_FLAG_VOL);
new_vm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
schedule_for_immediate_diffusion_if_needed(new_vm.id);
n--;
#ifdef DEBUG_RELEASES
new_vm.dump(p, "Released vm:", "", p.stats.get_current_iteration(), actual_release_time, true);
#endif
}
}
void ReleaseEvent::release_ellipsoid_or_rectcuboid(int computed_release_number) {
assert(computed_release_number >= 0 && "Cannot have negative SPHERICAL release");
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
double time_step = world->get_all_species().get(species_id).time_step;
const int is_spheroidal = (release_shape == ReleaseShape::SPHERICAL ||
/*release_shape == SHAPE_ELLIPTIC ||*/
release_shape == ReleaseShape::SPHERICAL_SHELL);
for (int i = 0; i < computed_release_number; i++) {
Vec3 pos;
do /* Pick values in unit square, toss if not in unit circle */
{
pos.x = (rng_dbl(&world->rng) - 0.5);
pos.y = (rng_dbl(&world->rng) - 0.5);
pos.z = (rng_dbl(&world->rng) - 0.5);
} while (is_spheroidal && len3_squared(pos) >= 0.25);
if (release_shape == ReleaseShape::SPHERICAL_SHELL) {
pos_t r = sqrt_p(len3_squared(pos)) * 2;
if (r == 0) {
pos = Vec3(0.0, 0.0, 0.5);
} else {
pos /= r;
}
}
pos_t base_location[1][4];
base_location[0][0] = pos.x * diameter.x + location.x;
base_location[0][1] = pos.y * diameter.y + location.y;
base_location[0][2] = pos.z * diameter.z + location.z;
base_location[0][3] = 1;
Vec3 molecule_location;
molecule_location.x = base_location[0][0];
molecule_location.y = base_location[0][1];
molecule_location.z = base_location[0][2];
Molecule& new_vm = p.add_volume_molecule(
Molecule(MOLECULE_ID_INVALID, species_id, molecule_location, event_time), get_release_delay_time()
);
new_vm.set_flag(MOLECULE_FLAG_VOL);
new_vm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
schedule_for_immediate_diffusion_if_needed(new_vm.id);
#ifdef DEBUG_RELEASES
new_vm.dump(p, "Released vm:", "", p.stats.get_current_iteration(), actual_release_time, true);
#endif
}
}
void ReleaseEvent::release_list() {
for (const SingleMoleculeReleaseInfo& info: molecule_list) {
BNG::Species& species = world->get_all_species().get(info.species_id);
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
if (species.is_vol()) {
Molecule& new_vm = p.add_volume_molecule(
Molecule(MOLECULE_ID_INVALID, info.species_id, info.pos, event_time), get_release_delay_time()
);
new_vm.set_flag(MOLECULE_FLAG_VOL);
new_vm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
schedule_for_immediate_diffusion_if_needed(new_vm.id);
cout
<< "Released 1 " << species.name << " from \"" << release_site_name << "\""
<< " at iteration " << world->get_current_iteration() << ".\n";
}
else {
orientation_t orient;
assert(info.orientation != ORIENTATION_NOT_SET);
if (info.orientation == ORIENTATION_NONE) {
orient = (rng_uint(&world->rng) & 1) ? 1 : -1;
}
else {
orient = info.orientation;
}
double diam = diameter.x;
assert(diam != FLT_INVALID);
molecule_id_t sm_id = GridUtils::place_surface_molecule_to_closest_pos(
p, world->rng, info.pos, info.species_id, orient, diameter.x,
event_time, get_release_delay_time()
);
if (sm_id != MOLECULE_ID_INVALID) {
const Molecule& sm = p.get_m(sm_id);
schedule_for_immediate_diffusion_if_needed(sm_id, WallTileIndexPair(sm.s.wall_index, sm.s.grid_tile_index));
cout
<< "Released 1 " << species.name << " from \"" << release_site_name << "\""
<< " at iteration " << world->get_current_iteration() << ".\n";
}
else {
stringstream msg;
msg << "Could not release " << species.name << " from " << release_site_name <<
" possibly the release diameter is too short.\n";
report_release_failure(msg.str());
}
}
}
}
void ReleaseEvent::init_surf_mols_by_number(Partition& p, const Region& reg, const InitialSurfaceReleases& info) {
uint n_free_sm = 0;
/* initialize surface molecule grids in region as needed and */
/* count total number of free surface molecule sites in region */
vector<WallTileIndexPair> free_tiles;
for (auto wall_edge_it: reg.walls_and_edges) {
Wall& w = p.get_wall(wall_edge_it.first);
if (!w.has_initialized_grid()) {
w.initialize_grid(p);
}
Grid& g = w.grid;
n_free_sm += g.get_num_free_tiles();
for (tile_index_t ti = 0; ti < g.num_tiles; ti++) {
if (g.get_molecule_on_tile(ti) == MOLECULE_ID_INVALID) {
free_tiles.push_back(WallTileIndexPair(w.index, ti));
}
}
}
assert(n_free_sm == free_tiles.size() && "Num free tiles does not match");
if (info.release_num > 0 && n_free_sm == 0) {
mcell_error("Number of free surface molecule tiles in region %s = %d", reg.name.c_str(), n_free_sm);
}
if (info.release_num > n_free_sm / 2) {
mcell_warn("Implementation of filling more than half of free tiles is different in MCell4 from MCell3.");
}
for (uint i = 0; i < info.release_num; i++) {
uint num_attempts = 0;
/* Loop until we find a vacant tile. */
while (1) {
uint slot_num = (int)(rng_dbl(&world->rng) * n_free_sm);
const WallTileIndexPair& wip = free_tiles[slot_num];
Wall& w = p.get_wall(wip.wall_index);
if (w.grid.get_molecule_on_tile(wip.tile_index) == MOLECULE_ID_INVALID) {
GridUtils::place_single_molecule_onto_grid(
p, world->rng, w, wip.tile_index, false, Vec2(),
info.species_id, info.orientation, event_time, get_release_delay_time()
);
break;
}
if (num_attempts != 0 && num_attempts % 10000 == 0) {
mcell_warn("Made %d of attempts while placing molecule in release event %s.",
num_attempts, reg.name.c_str());
}
}
}
}
void ReleaseEvent::init_surf_mols_by_density(
Partition& p, Wall& w,
map<species_id_t, uint>& num_released_per_species
) {
if (!w.has_initialized_grid()) {
w.initialize_grid(p);
}
double tot_prob = 0;
double tot_density = 0;
vector<pair<double, InitialSurfaceReleases>> prob_info_pairs;
// do for all surface regions of a wall at once
for (region_index_t reg_index: w.regions) {
const Region& reg = p.get_region(reg_index);
for (const InitialSurfaceReleases& info: reg.initial_region_molecules) {
if (!info.is_release_by_density()) {
// skip release by number, they will be handled later
continue;
}
tot_prob += (w.area * info.release_density) / (w.grid.num_tiles * world->config.grid_density);
// make an array with cummulative probs
prob_info_pairs.push_back(make_pair(tot_prob, info));
tot_density += info.release_density;
}
}
if (tot_density > world->config.grid_density) {
mcell_warn(
"Total surface molecule density too high: %f. Filling all available "
"surface molecule sites.",
tot_density);
}
if (prob_info_pairs.empty()) {
// nothing to do
return;
}
// for each tile of the wall
for (tile_index_t ti = 0; ti < w.grid.num_tiles; ti++) {
double rnd = rng_dbl(&world->rng);
size_t index;
for (index = 0; index < prob_info_pairs.size(); ++index) {
if (rnd <= prob_info_pairs[index].first) {
break;
}
}
if (index >= prob_info_pairs.size()) {
continue;
}
species_id_t species_id = prob_info_pairs[index].second.species_id;
GridUtils::place_single_molecule_onto_grid(
p, world->rng, w, ti, false, Vec2(),
prob_info_pairs[index].second.species_id, prob_info_pairs[index].second.orientation,
event_time, get_release_delay_time()
);
auto it = num_released_per_species.find(species_id);
if (it != num_released_per_species.end()) {
it->second++;
}
else {
num_released_per_species[species_id] = 1;
}
}
}
// based on init_wall_surf_mols
void ReleaseEvent::release_initial_molecules_onto_surf_regions() {
release_assert(running_diffuse_event_to_update == nullptr && "Cannot be executed during diffusion&react event");
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
// first collect all walls that are affected
vector<wall_index_t> walls;
for (const Wall& w: p.get_walls()) {
for (region_index_t reg_index: w.regions) {
const Region& reg = p.get_region(reg_index);
if (reg.has_initial_molecules()) {
walls.push_back(w.index);
break;
}
}
}
map<species_id_t, uint> num_released_per_species;
for (wall_index_t wi: walls) {
Wall& w = p.get_wall(wi);
init_surf_mols_by_density(p, w, num_released_per_species);
}
for (auto it: num_released_per_species) {
cout <<
"Released " << it.second << " " << world->get_all_species().get(it.first).name << " onto surface regions " <<
"at iteration " << world->get_current_iteration() << " (specified with density).\n";
}
for (const Region& reg: p.get_regions()) {
// for each specifies initial molecules
for (const InitialSurfaceReleases& info: reg.initial_region_molecules) {
if (!info.is_release_by_num()) {
// skip density, they were already handled
continue;
}
init_surf_mols_by_number(p, reg, info);
cout
<< "Released " << info.release_num << " " << world->get_all_species().get(info.species_id).name << " on region \"" << reg.name << "\""
<< " at iteration " << world->get_current_iteration() << " (specified with number).\n";
}
}
}
bool ReleaseEvent::skip_due_to_release_probability() {
if (release_probability < 1) {
double k = rng_dbl(&world->rng);
return release_probability < k;
}
else {
return false;
}
}
void ReleaseEvent::step() {
if (skip_due_to_release_probability()) {
// release patterns are handled automatically in update_event_time_for_next_scheduled_time
return;
}
perf() << "Starting release from \"" << release_site_name << "\".\n";
int num_released = 0;
if (release_shape == ReleaseShape::REGION) {
int number = calculate_number_to_release();
const BNG::Species& species = world->get_all_species().get(species_id);
if (species.is_surf()) {
release_onto_regions(number);
}
else {
release_inside_regions(number);
}
num_released = number;
}
else if (release_shape == ReleaseShape::SPHERICAL) {
int number = calculate_number_to_release();
assert(diameter.is_valid());
release_ellipsoid_or_rectcuboid(number);
num_released = number;
}
else if (release_shape == ReleaseShape::LIST) {
release_list();
}
else if (release_shape == ReleaseShape::INITIAL_SURF_REGION) {
release_initial_molecules_onto_surf_regions();
}
else {
assert(false);
}
if (release_shape == ReleaseShape::REGION || release_shape == ReleaseShape::SPHERICAL) {
const BNG::Species& species = world->get_all_species().get(species_id);
const char* type;
int count;
if (num_released >= 0) {
type = "Released ";
count = num_released;
}
else {
type = "Removed ";
count = -num_released;
}
cout
<< type << count << " " << species.name << " from \"" << release_site_name << "\""
<< " at iteration " << world->get_current_iteration() << ".\n";
}
}
void ReleaseEvent::schedule_for_immediate_diffusion_if_needed(
const molecule_id_t id, const WallTileIndexPair& where_released) {
// NOTE: we do nto care about partitions here but we should
if (running_diffuse_event_to_update != nullptr) {
running_diffuse_event_to_update->add_diffuse_action(DiffuseAction(id, where_released));
}
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/geometry_utils.h | .h | 1,137 | 49 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_GEOMETRY_UTILS_H_
#define SRC4_GEOMETRY_UTILS_H_
#include "defines.h"
namespace MCell {
class Partition;
class Wall;
struct Vec3;
struct Vec2;
namespace GeometryUtils {
// some commonly used utilities for which one does not need to
// include the whole geometry_utils.inc
static inline Vec3 uv2xyz(const Vec2& a, const Wall& w, const Vec3& wall_vert0) {
return Vec3(a.u) * w.unit_u + Vec3(a.v) * w.unit_v + wall_vert0;
}
// only the needed functions for now
static pos_t closest_interior_point(
const Partition& p,
const Vec3& pt,
const Wall& w,
Vec2& ip
);
} // namespace WallUtil
} // namespace MCell
#endif // SRC4_GEOMETRY_UTILS_H_
| Unknown |
3D | mcellteam/mcell | src4/vtk_utils.h | .h | 3,548 | 119 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_COUNTED_VOLUME_UTIL_H_
#define SRC4_COUNTED_VOLUME_UTIL_H_
#include <vector>
#include <map>
#include <vtkSmartPointer.h>
#include <vtkPolyData.h>
#include "defines.h"
#include "geometry.h"
namespace MCell {
class World;
class Partition;
class GeometryObject;
namespace VtkUtils {
class GeomObjectInfo {
public:
GeomObjectInfo(const partition_id_t partition_id_, const geometry_object_id_t geometry_object_id_)
: for_counted_objects(true), partition_id(partition_id_), geometry_object_id(geometry_object_id_) {
}
GeomObjectInfo(const std::string& name_)
: for_counted_objects(false), partition_id(PARTITION_ID_INVALID), geometry_object_id(GEOMETRY_OBJECT_ID_INVALID),
name(name_) {
}
// true - for counted objects
// false - for compartments
bool for_counted_objects;
// partition_id and geometry_object_id are used when
// we are computing containment for counted objects
// TODO: remove partition_id - it is not needed because we can get this info from geometry_object_id
partition_id_t partition_id;
geometry_object_id_t geometry_object_id;
// name is used when we are computing containment for compartments
std::string name;
vtkSmartPointer<vtkPolyData> polydata;
GeometryObject& get_geometry_object_noconst(World* world) const;
const GeometryObject& get_geometry_object(const World* world) const;
// comparison uses geometry_object_id only, used in maps
bool operator < (const GeomObjectInfo& other) const {
if (for_counted_objects) {
return geometry_object_id < other.geometry_object_id;
}
else {
return name < other.name;
}
}
bool operator == (const GeomObjectInfo& other) const {
if (for_counted_objects) {
return geometry_object_id == other.geometry_object_id;
}
else {
return name == other.name;
}
}
};
typedef std::vector<GeomObjectInfo> GeomObjectInfoVector;
// containment mapping of counted geometry objects
typedef std::map<GeomObjectInfo, std::set<GeomObjectInfo>> ContainmentMap;
typedef std::set<GeomObjectInfo> IntersectingSet;
// return true if counted volumes were correctly set up
bool initialize_counted_volumes(World* world, bool& has_intersecting_counted_objects);
#if 0
bool is_point_inside_counted_volume(GeometryObject& obj, const Vec3& point);
#endif
// world is nullptr for compartment hierarchy computation
bool compute_containement_mapping(
const World* world, const GeomObjectInfoVector& counted_objects,
ContainmentMap& contained_in_mapping,
IntersectingSet& intersecting_objects);
const GeomObjectInfo* get_direct_parent_info(
const GeomObjectInfo& obj_info, const ContainmentMap& contained_in_mapping);
// auxiliary function to compute volume, not related to counted volumes but uses VTK
double get_geometry_object_volume(const World* world, const GeometryObject& obj);
void export_geometry_objects_to_obj(
const World* world, const GeometryObjectVector& objs, const std::string& file_prefix);
}; // namespace VtkUtils
} // namespace MCell
#endif // SRC4_COUNTED_VOLUME_UTIL_H_
| Unknown |
3D | mcellteam/mcell | src4/count_buffer.h | .h | 3,373 | 130 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_COUNT_BUFFER_H_
#define SRC4_COUNT_BUFFER_H_
#include <fstream>
#include "defines.h"
#include "generated/gen_constants.h"
namespace MCell {
using API::CountOutputFormat;
class CountValue {
public:
CountValue()
: column_index(UINT_INVALID), time(TIME_INVALID), value(0) {
}
CountValue(const double time_, const double value_)
: column_index(UINT_INVALID), time(time_), value(value_) {
}
void inc_or_dec(const int sign, const int count = 1) {
assert(sign == 1 || sign == -1);
value += (sign * count);
}
uint column_index; // index in CountBuffer
double time; // time is in outside units, was already precomputed for printing
double value; // e.g. count
void write_as_dat(std::ostream& out) const;
};
typedef small_vector<CountValue> CountValueVector;
// might need to be a template in the future
class CountBuffer {
public:
CountBuffer(
const CountOutputFormat output_format_,
const std::string filename_,
const std::vector<std::string> column_names_,
const size_t buffer_size_,
const bool open_for_append_) :
output_format(output_format_),
filename(filename_),
column_names(column_names_),
buffer_size(buffer_size_),
open_for_append(open_for_append_) {
assert(output_format != CountOutputFormat::UNSET);
assert(!column_names.empty());
// there is a single column
data.resize(column_names.size());
}
void add(const CountValue& value) {
assert(value.column_index < data.size());
if (data[value.column_index].size() >= buffer_size) {
flush();
}
data[value.column_index].push_back(value);
}
// close, create an empty file
void flush_and_close();
const std::string& get_filename() const {
return filename;
}
CountOutputFormat get_output_format() const {
return output_format;
}
const std::string& get_column_name(const uint column_index) const {
assert(column_index < column_names.size());
return column_names[column_index];
}
// open file, return false if file could not be opened and error_is_fatal is false
bool open(bool error_is_fatal = true);
// flush buffer, open output file if needed, keep file open afterwards
void flush();
private:
void write_gdat_header();
CountOutputFormat output_format;
// name of the output file with the full path
std::string filename;
// does not include 'time' column
// unused when output_format is CountOutputFormat::DAT
std::vector<std::string> column_names;
// number of rows to be stored, automatically flushes afterwards
size_t buffer_size;
// output stream
std::ofstream fout;
// buffer columns, size of this vector is the
// same as column_names size
std::vector<CountValueVector> data;
bool open_for_append;
};
typedef std::vector<CountBuffer> CountBufferVector;
} /* namespace MCell */
#endif /* SRC4_COUNT_BUFFER_H_ */
| Unknown |
3D | mcellteam/mcell | src4/memory_limit_checker.cpp | .cpp | 3,054 | 112 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <chrono>
#ifndef _WIN64
#include <sys/resource.h>
#endif
#include "memory_limit_checker.h"
#include "world.h"
#include "libs/gperftools/src/gperftools/malloc_extension.h"
using namespace CppTime;
using namespace std;
using namespace std::chrono;
namespace MCell {
const int PERIODICITY_SECONDS = 30;
const int KB_IN_GB = 1024*1024;
MemoryLimitChecker::~MemoryLimitChecker() {
if (timer != nullptr) {
timer->remove(created_timer_id);
delete timer;
}
}
void MemoryLimitChecker::start_timed_check(
World* world_, const int limit_gb_, const bool exit_when_over_limit_) {
if (limit_gb_ < 0) {
return;
}
release_assert(timer == nullptr && "May be called only once");
// not completely sure how lambdas work, copying arguments
// to be sure that they are available even when we return from function
world = world_;
limit_gb = limit_gb_;
exit_when_over_limit = exit_when_over_limit_;
#ifdef PROFILE_MEMORY
static int counter = 0;
#endif
timer = new Timer();
created_timer_id = timer->add(
seconds(0),
[this](CppTime::timer_id) {
#ifdef PROFILE_MEMORY
const std::string outfile = "mem" + std::to_string(counter) + ".dump";
counter++;
std::string data;
MallocExtension::instance()->GetHeapSample(&data);
ofstream out;
out.open(outfile);
out.write(data.c_str(), data.size());
cout << "Written mem profile to " << outfile << "\n";
out.close();
#endif
uint64_t usage = get_mem_usage(); // returns value in kB
if ((long long)usage > this->limit_gb * KB_IN_GB) {
// skip if we are currently executing MolRxnCountEvent because this can mean
// that flushed buffers are in an inconsistent state, this should be rare
if (exit_when_over_limit &&
(world->scheduler.get_event_being_executed() == nullptr ||
world->scheduler.get_event_being_executed()->type_index != EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT
) ) {
this->world->fatal_error(
"Memory limit of " + to_string(this->limit_gb) + " GB reached, currently using " +
to_string(usage / KB_IN_GB) + " GB. Flushing count observable buffers and terminating simulation.\n"
);
}
else {
over_limit = true;
}
}
},
seconds(PERIODICITY_SECONDS)
);
}
void MemoryLimitChecker::stop_timed_check() {
if (timer != nullptr) {
timer->remove(created_timer_id);
delete timer;
timer = nullptr;
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/species_cleanup_event.h | .h | 1,119 | 45 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_SPECIES_CLEANUP_EVENT_H_
#define SRC4_SPECIES_CLEANUP_EVENT_H_
#include "base_event.h"
namespace MCell {
class World;
/**
* Removes all surface and volume species that whose instantiation count is 0.
* Removes all rxn classes because they might reference the removed species.
* Also removes unused reactant classes.
*/
class SpeciesCleanupEvent: public BaseEvent {
public:
SpeciesCleanupEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_RXN_CLASS_CLEANUP),
world(world_) {
}
void step() override;
void dump(const std::string indent) const override;
private:
void remove_unused_reactant_classes();
World* world;
};
} /* namespace MCell */
#endif /* SRC4_SPECIES_CLEANUP_EVENT_H_ */
| Unknown |
3D | mcellteam/mcell | src4/bng_data_to_datamodel_converter.h | .h | 1,831 | 71 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_BNGDATA_TO_DATAMODEL_CONVERTER_H_
#define SRC4_BNGDATA_TO_DATAMODEL_CONVERTER_H_
#include <cassert>
#include "defines.h"
namespace Json {
class Value;
}
namespace BNG {
class BNGEngine;
class RxnRule;
class ElemMolType;
}
namespace MCell {
class World;
/**
* We want to keep the BNG independent,
* so this is an extra too to convert the GND data to the
* cellblender datamodel.
*/
class BngDataToDatamodelConverter {
public:
BngDataToDatamodelConverter();
// does nothing for now, there will be changes in BNG data and
// converting species is not needed at this point
void to_data_model(const World* world_, Json::Value& mcell_node, const bool only_for_viz);
private:
void reset();
Vec3 get_next_color();
void convert_molecules(Json::Value& mcell_node);
void convert_single_mol_type(const BNG::ElemMolType& s, Json::Value& molecule_node);
void convert_single_rxn_rule(const BNG::RxnRule& r, Json::Value& species_node);
std::string get_surface_class_name(const BNG::RxnRule& r);
void convert_single_surface_class(const BNG::RxnRule& r, Json::Value& rxn_node);
void convert_rxns(Json::Value& mcell_node);
const World* world;
const BNG::BNGEngine* bng_engine;
uint next_color_index;
uint rxn_counter;
std::set<std::string> processed_surface_classes;
std::vector<Vec3> colors;
bool conversion_failed;
};
} // namespace MCell
#endif // SRC4_BNGDATA_TO_DATAMODEL_CONVERTER_H_
| Unknown |
3D | mcellteam/mcell | src4/run_n_iterations_end_event.h | .h | 1,212 | 52 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_RUN_N_ITERATIONS_END_EVENT_H_
#define SRC4_RUN_N_ITERATIONS_END_EVENT_H_
#include <iostream>
#include <string>
#include "base_event.h"
namespace MCell {
/**
* This is a dummy event that only serves as a marker
* of time where we must check whether we already reached target number
* of iterations.
*/
class RunNIterationsEndEvent: public BaseEvent {
public:
RunNIterationsEndEvent()
: BaseEvent(EVENT_TYPE_INDEX_SIMULATION_END_CHECK) {
}
void step() override {
// empty
}
bool is_barrier() const override {
return true;
}
void dump(const std::string ind) const override {
std::cout << ind << "Simulation end check event\n";
std::string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
};
} /* namespace MCell */
#endif /* SRC4_RUN_N_ITERATIONS_END_EVENT_H_ */
| Unknown |
3D | mcellteam/mcell | src4/geometry.cpp | .cpp | 40,836 | 1,347 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include "bng/bng.h"
#include "rng.h" // MCell 3
#include "isaac64.h"
#include "mcell_structs_shared.h"
#include "logging.h"
#include "wall_util.h"
#include "partition.h"
#include "geometry.h"
#include "release_event.h"
#include "datamodel_defines.h"
#include "geometry_utils.h"
#include "geometry_utils.inl" // uses get_wall_bounding_box, maybe not include this file
#include "collision_utils.inl"
#include "dump_state.h"
using namespace std;
namespace MCell {
/***************************************************************************
compatible_edges:
In: array of pointers to walls
index of first wall
index of edge in first wall
index of second wall
index of edge in second wall
indices may be -1
Out: 1 if the edge joins the two walls
0 if not (i.e. the wall doesn't contain the edge or the edge is
traversed in the same direction in each or the two walls are
actually the same wall)
***************************************************************************/
static int compatible_edges(
const Partition& p,
const vector<wall_index_t>& faces, int wA, int eA, int wB, int eB) {
const Vec3 *vA0, *vA1, *vA2, *vB0, *vB1, *vB2;
const Wall& wall_a = p.get_wall(faces[wA]);
const Wall& wall_b = p.get_wall(faces[wB]);
if ((wA < 0) || (eA < 0) || (wB < 0) || (eB < 0))
return 0;
vA0 = &p.get_wall_vertex(wall_a, eA);
if (eA == 2) {
vA1 = &p.get_wall_vertex(wall_a, 0);
}
else {
vA1 = &p.get_wall_vertex(wall_a, eA + 1);
}
if (eA == 0) {
vA2 = &p.get_wall_vertex(wall_a, 2);
}
else {
vA2 = &p.get_wall_vertex(wall_a, eA - 1);
}
vB0 = &p.get_wall_vertex(wall_b, eB);
if (eB == 2) {
vB1 = &p.get_wall_vertex(wall_b, 0);
}
else {
vB1 = &p.get_wall_vertex(wall_b, eB + 1);
}
if (eB == 0) {
vB2 = &p.get_wall_vertex(wall_b, 2);
}
else {
vB2 = &p.get_wall_vertex(wall_b, eB - 1);
}
return ((vA0 == vB1 && vA1 == vB0 && vA2 != vB2) ||
(vA0->x == vB1->x && vA0->y == vB1->y && vA0->z == vB1->z &&
vA1->x == vB0->x && vA1->y == vB0->y && vA1->z == vB0->z &&
!(vA2->x == vB2->x && vA2->y == vB2->y && vA2->z == vB2->z)));
}
/*****************************************************************************
have_common_region checks if wall1 and wall2 located on the (same) object
are part of a common region or not
******************************************************************************/
static bool have_common_region(
const Partition& p, const GeometryObject& obj, wall_index_t wall1, wall_index_t wall2) {
const Wall& w1 = p.get_wall(obj.wall_indices[wall1]);
const Wall& w2 = p.get_wall(obj.wall_indices[wall2]);
for (region_index_t index: w1.regions) {
if (w2.regions.count(index) == 1) {
return true;
}
}
return false;
}
/***************************************************************************
refine_edge_pairs:
In: the head of a linked list of shared edges
array of pointers to walls
Out: No return value. The best-matching pair of edges percolates up
to be first in the list. "Best-matching" means that the edge
is traversed in different directions by each face, and that the
normals of the two faces are as divergent as possible.
***************************************************************************/
static void refine_edge_pairs(
const Partition& p, const GeometryObject& obj, poly_edge *pe, const vector<wall_index_t>& faces) {
#define TSWAP(x, y) temp = (x); (x) = (y); (y) = temp
int temp;
pos_t best_align = 2;
bool share_region = false;
poly_edge* best_p1 = pe;
poly_edge* best_p2 = pe;
int best_n1 = 1;
int best_n2 = 2;
poly_edge* p1 = pe;
int n1 = 1;
while (p1 != NULL && p1->n >= n1) {
int wA, eA;
if (n1 == 1) {
wA = p1->face[0];
eA = p1->edge[0];
}
else {
wA = p1->face[1];
eA = p1->edge[1];
}
poly_edge* p2;
int n2;
if (n1 == 1) {
n2 = n1 + 1;
p2 = p1;
}
else {
n2 = 1;
p2 = p1->next;
}
while (p2 != NULL && p2->n >= n2) {
int wB, eB;
if (n2 == 1) {
wB = p2->face[0];
eB = p2->edge[0];
} else {
wB = p2->face[1];
eB = p2->edge[1];
}
// as soon as we hit an incompatible edge we can break out of the p2 loop
// and continue scanning the next p1
if (compatible_edges(p, faces, wA, eA, wB, eB)) {
const Wall& wall_a = p.get_wall(wA);
const Wall& wall_b = p.get_wall(wB);
assert(wall_a.wall_constants_initialized);
assert(wall_b.wall_constants_initialized);
pos_t align = dot(wall_a.normal, wall_b.normal);
// as soon as two walls have a common region we only consider walls who
// share (any) region. We need to reset the best_align to make sure we
// don't pick any wall that don't share a region discovered previously
bool common_region = have_common_region(p, obj, wA, wB);
if (common_region) {
if (!share_region) {
best_align = 2;
}
share_region = true;
}
if (common_region || !share_region) {
if (align < best_align) {
best_p1 = p1;
best_p2 = p2;
best_n1 = n1;
best_n2 = n2;
best_align = align;
}
}
}
else {
break;
}
if (n2 == 1) {
n2++;
}
else {
p2 = p2->next;
n2 = 1;
}
}
if (n1 == 1) {
n1++;
}
else {
p1 = p1->next;
n1 = 1;
}
}
/* swap best match into top spot */
if (best_align > 1) {
return; /* No good pairs. */
}
TSWAP(best_p1->face[best_n1-1], pe->face[0]);
TSWAP(best_p1->edge[best_n1-1], pe->edge[0]);
TSWAP(best_p2->face[best_n2-1], pe->face[1]);
TSWAP(best_p2->edge[best_n2-1], pe->edge[1]);
#undef TSWAP
}
/***************************************************************************
surface_net:
In: array of pointers to walls
integer length of array
Out: -1 if the surface is a manifold, 0 if it is not, 1 on malloc failure
Walls end up connected across their edges.
Note: Two edges must have their vertices listed in opposite order (i.e.
connect two faces pointing the same way) to be linked. If more than
two faces share the same edge and can be linked, the faces with
normals closest to each other will be linked. We do not assume that
the object is connected. All pieces must be a manifold, however,
for the entire object to be a manifold. (That is, there must not
be any free edges anywhere.) It is possible to build weird, twisty
self-intersecting things. The behavior of these things during a
simulation is not guaranteed to be well-defined.
***************************************************************************/
static int surface_net(Partition& p, GeometryObject& obj) {
uint nfaces = obj.wall_indices.size();
vector<wall_index_t> facelist = obj.wall_indices;
Edge *e;
int is_closed = 1;
struct edge_hashtable eht;
int nkeys = (3 * nfaces) / 2;
if (ehtable_init(&eht, nkeys))
return 1;
for (uint face_index = 0; face_index < nfaces; face_index++) {
Wall& w = p.get_wall(facelist[face_index]);
int k;
int nedge = 3;
for (int j = 0; j < nedge; j++) {
if (j + 1 < nedge)
k = j + 1;
else
k = 0;
poly_edge pe;
const Vec3& vert_j = p.get_wall_vertex(w, j);
pe.v1x = vert_j.x;
pe.v1y = vert_j.y;
pe.v1z = vert_j.z;
const Vec3& vert_k = p.get_wall_vertex(w, k);
pe.v2x = vert_k.x;
pe.v2y = vert_k.y;
pe.v2z = vert_k.z;
pe.face[0] = face_index;
pe.edge[0] = j;
if (ehtable_add(&eht, &pe))
return 1;
}
}
for (int i = 0; i < nkeys; i++) {
poly_edge *pep = (eht.data + i);
#ifdef DEBUG_GEOM_OBJ_INITIALIZATION
dump_poly_edge(i, pep);
#endif
while (pep != NULL) {
if (pep->n > 2) {
refine_edge_pairs(p, obj, pep, facelist);
}
if (pep->n >= 2) {
if (pep->face[0] != -1 && pep->face[1] != -1) {
if (compatible_edges(p, facelist, pep->face[0], pep->edge[0], pep->face[1], pep->edge[1])) {
Wall& face0 = p.get_wall(facelist[pep->face[0]]);
Wall& face1 = p.get_wall(facelist[pep->face[1]]);
assert(pep->face[0] < (int)facelist.size());
assert(pep->face[1] < (int)facelist.size());
face0.nb_walls[pep->edge[0]] = facelist[pep->face[1]];
face1.nb_walls[pep->edge[1]] = facelist[pep->face[0]];
Edge e;
e.forward_index = facelist[pep->face[0]];
e.backward_index = facelist[pep->face[1]];
e.edge_num_used_for_init = pep->edge[0];
assert(face0.wall_constants_initialized);
assert(face1.wall_constants_initialized);
e.reinit_edge_constants(p);
face0.edges[pep->edge[0]] = e;
face1.edges[pep->edge[1]] = e;
}
}
else {
is_closed = 0;
}
}
else if (pep->n == 1) {
is_closed = 0;
Edge e;
e.forward_index = facelist[pep->face[0]];
e.backward_index = WALL_INDEX_INVALID;
/* Don't call reinit_edge_constants unless both edges are set */
}
pep = pep->next;
}
}
ehtable_kill(&eht);
return -is_closed; /* We use 1 to indicate malloc failure so return 0/-1 */
}
void GeometryObject::initialize_neighboring_walls_and_their_edges(Partition& p) {
surface_net(p, *this);
}
// returns indices of all vertices in this object that are connected through an edge
const std::set<vertex_index_t>& GeometryObject::get_connected_vertices(
const Partition& p, const vertex_index_t vi) {
// check cache first
auto it = connected_vertices_cache.find(vi);
if (it != connected_vertices_cache.end()) {
return it->second;
}
// create a new entry
set<vertex_index_t>& connected_vertices = connected_vertices_cache[vi];
for (wall_index_t wi: wall_indices) {
const Wall& w = p.get_wall(wi);
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
if (w.vertex_indices[i] == vi) {
// add all other vertices
for (uint k = 0; k < VERTICES_IN_TRIANGLE; k++) {
if (w.vertex_indices[k] != vi) {
connected_vertices.insert(w.vertex_indices[k]);
}
}
break;
}
}
}
return connected_vertices;
}
wall_index_t GeometryObject::get_wall_for_vertex_pair(
const Partition& p, const vertex_index_t vi1, const vertex_index_t vi2) {
assert(vi1 != vi2);
// check cache first
UnorderedPair<vertex_index_t> vp(vi1, vi2);
auto it = vertex_pair_to_wall_cache.find(vp);
if (it != vertex_pair_to_wall_cache.end()) {
return it->second;
}
// create a new entry
for (wall_index_t wi: wall_indices) {
const Wall& w = p.get_wall(wi);
uint cnt = 0;
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
if (w.vertex_indices[i] == vi1 || w.vertex_indices[i] == vi2) {
cnt++;
}
}
if (cnt == 2) {
vertex_pair_to_wall_cache[vp] = w.index;
return w.index;
}
}
return WALL_INDEX_INVALID;
}
// checks all walls and their regions and if all are only transparent to all molecules,
// sets member is_fully_transparent to true
void GeometryObject::initialize_is_fully_transparent(Partition& p) {
is_fully_transparent = false;
const BNG::SpeciesRxnClassesMap* all_molecules_rxns =
p.get_all_rxns().get_bimol_rxns_for_reactant(p.get_all_species().get_all_molecules_species_id());
if (all_molecules_rxns == nullptr) {
// no transparent surface classes for all molecules were defined at all
return;
}
set<species_id_t> transparent_surf_classes_cache;
// for each wall
for (wall_index_t wi: wall_indices) {
const Wall& w = p.get_wall(wi);
bool is_transparent = false;
// check all regions
for (region_index_t ri: w.regions) {
const Region& reg = p.get_region(ri);
if (!reg.is_reactive()) {
continue;
}
if (transparent_surf_classes_cache.count(reg.species_id) != 0) {
is_transparent = true;
continue;
}
auto reactions_it = all_molecules_rxns->find(reg.species_id);
if (reactions_it == all_molecules_rxns->end()) {
// no reactions for this type of region -> wall is not transparent
return;
}
BNG::RxnClass* rxn_class = reactions_it->second;
if (rxn_class->is_transparent_type()) {
transparent_surf_classes_cache.insert(reg.species_id);
is_transparent = true;
}
}
if (!is_transparent) {
// wall has other surface classes -> object is not fully transparent
return;
}
}
// ok, all walls are fully transparent
is_fully_transparent = true;
}
std::string GeometryObject::validate_volumetric_mesh(const Partition& p) const {
std::stringstream res;
for (wall_index_t wi: wall_indices) {
const Wall& w = p.get_wall(wi);
// check that each wall has all neighbors
for (uint k = 0; k < EDGES_IN_TRIANGLE; k++) {
if (w.nb_walls[k] == WALL_INDEX_INVALID) {
res << "Wall side " << w.side << ": neighbor wall with index " << k << " not found.\n";
}
}
// check that all edges were initialized
for (uint k = 0; k < EDGES_IN_TRIANGLE; k++) {
if (w.edges[k].edge_num_used_for_init == EDGE_INDEX_INVALID) {
res << "Wall side " << w.side << ": edge with index " << k << " was not initialized.\n";
}
if (w.edges[k].forward_index == WALL_INDEX_INVALID) {
res << "Wall side " << w.side << ": edge with index " << k << " has no forward wall index.\n";
}
if (w.edges[k].backward_index == WALL_INDEX_INVALID) {
res << "Wall side " << w.side << ": edge with index " << k << " has no backward wall index.\n";
}
}
}
return res.str();
}
void GeometryObject::dump(const Partition& p, const std::string ind) const {
cout << ind <<
"GeometryObject: id:" << id << ", name:" << name <<
", compartment_id " << vol_compartment_id <<
", is_used_in_mol_rxn_counts " << is_used_in_mol_rxn_counts << "\n";
for (wall_index_t i: wall_indices) {
cout << ind << " " << i << ": \n";
p.get_wall(i).dump(p, ind + " ");
}
}
void GeometryObject::dump_array(const Partition& p, const std::vector<GeometryObject>& vec) {
cout << "GeometryObject array: " << (vec.empty() ? "EMPTY" : "") << "\n";
for (size_t i = 0; i < vec.size(); i++) {
cout << i << ":\n";
vec[i].dump(p, " ");
}
}
void GeometryObject::to_data_model_as_geometrical_object(
const Partition& p, const SimulationConfig& config,
Json::Value& object,
std::set<rgba_t>& used_colors) const {
object[KEY_NAME] = DMUtils::remove_obj_name_prefix(parent_name, name);
bool first = true; // to indicate when to use a comma
// first note which vertices this object uses
uint_set<vertex_index_t> used_vertex_indices;
for (wall_index_t wall_index: wall_indices) {
const Wall& w = p.get_wall(wall_index);
for (vertex_index_t vertex_index: w.vertex_indices) {
used_vertex_indices.insert(vertex_index);
}
}
// then generate vertices and remember mapping
Json::Value& vertex_list = object[KEY_VERTEX_LIST];
map<vertex_index_t, uint> map_vertex_index_to_vertex_list_index;
uint current_index_in_vertex_list = 0;
for (vertex_index_t i = 0; i < p.get_geometry_vertex_count(); i++) {
if (used_vertex_indices.count(i) == 1) {
// define mapping vertex_index -> index in vertex array
map_vertex_index_to_vertex_list_index[i] = current_index_in_vertex_list;
current_index_in_vertex_list++;
// append triple x, y, z
Vec3 pos = p.get_geometry_vertex(i) * Vec3(p.config.length_unit);
DMUtils::append_triplet(vertex_list, pos.x, pos.y, pos.z);
}
}
// element connections - they correspond to the ordering of walls
Json::Value& element_connections = object[KEY_ELEMENT_CONNECTIONS];
for (wall_index_t wall_index: wall_indices) {
const Wall& w = p.get_wall(wall_index);
Json::Value vertex_indices;
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
assert(map_vertex_index_to_vertex_list_index.count(w.vertex_indices[i]) == 1);
vertex_indices.append(map_vertex_index_to_vertex_list_index[w.vertex_indices[i]]);
}
element_connections.append(vertex_indices);
}
// surface regions
insertion_ordered_set<region_index_t> region_indices;
map<wall_index_t, uint> map_wall_index_to_order_index_in_object;
for (size_t i = 0; i < wall_indices.size(); i++) {
map_wall_index_to_order_index_in_object[wall_indices[i]] = i;
const Wall& w = p.get_wall(wall_indices[i]);
for (region_index_t region_index: w.regions) {
region_indices.insert_ordered(region_index);
}
}
vector<Json::Value> surface_regions_vec;
for (region_index_t region_index: region_indices.get_as_vector()) {
const Region& reg = p.get_region(region_index);
if (reg.name_has_suffix_ALL()) {
continue;
}
Json::Value surface_region;
string name = DMUtils::get_surface_region_name(reg.name);
surface_region[KEY_NAME] = name;
Json::Value include_elements;
for (auto it: reg.walls_and_edges) {
include_elements.append(map_wall_index_to_order_index_in_object[it.first]);
}
surface_region[KEY_INCLUDE_ELEMENTS] = include_elements;
surface_regions_vec.push_back(surface_region);
}
// we may create the define_surface_regions only when there is at least one region
if (!surface_regions_vec.empty()) {
Json::Value& define_surface_regions = object[KEY_DEFINE_SURFACE_REGIONS];
for (auto& surface_region: surface_regions_vec) {
define_surface_regions.append(surface_region);
}
}
// colors
if (default_color != DEFAULT_COLOR || !wall_specific_colors.empty()) {
used_colors.insert(default_color);
std::map<rgba_t, int> colors_this_object;
colors_this_object[default_color] = 0;
// collect all wall_specific_colors and define their ID
for (const auto& pair_index_color: wall_specific_colors) {
rgba_t wall_color = pair_index_color.second;
auto it = colors_this_object.find(wall_color);
if (it == colors_this_object.end()) {
// new item
int local_index = colors_this_object.size();
colors_this_object[wall_color] = local_index;
}
}
// generate material names for this object, must be sorted by their id
vector<rgba_t> sorted_colors;
sorted_colors.resize(colors_this_object.size());
for (const auto& pair_color_local_index: colors_this_object) {
sorted_colors[pair_color_local_index.second] = pair_color_local_index.first;
}
Json::Value& material_names = object[KEY_MATERIAL_NAMES];
for (const rgba_t color: sorted_colors) {
material_names.append(DMUtils::color_to_mat_name(color));
}
// and finally assign element_material_indices
Json::Value& element_material_indices = object[KEY_ELEMENT_MATERIAL_INDICES];
for (wall_index_t wi: wall_indices) {
rgba_t color;
auto it = wall_specific_colors.find(wi);
if (it != wall_specific_colors.end()) {
color = it->second;
used_colors.insert(color);
}
else {
color = default_color;
}
assert(colors_this_object.count(color) == 1);
element_material_indices.append(colors_this_object[color]);
}
}
else {
// material_names must not be empty
object[KEY_MATERIAL_NAMES].append(Json::Value(KEY_VALUE_MEMBRANE));
}
}
void GeometryObject::to_data_model_as_model_object(
const Partition& p, Json::Value& model_object) const {
model_object[KEY_DESCRIPTION] = "";
model_object[KEY_OBJECT_SOURCE] = VALUE_BLENDER;
model_object[KEY_DYNAMIC_DISPLAY_SOURCE] = "script";
model_object[KEY_SCRIPT_NAME] = "";
string obj_name = DMUtils::remove_obj_name_prefix(parent_name, name);
model_object[KEY_NAME] = obj_name;
// set defaults that may be overwritten
model_object[KEY_MEMBRANE_NAME] = "";
model_object[KEY_PARENT_OBJECT] = "";
const BNG::BNGData& bng_data = p.get_all_species().get_bng_data();
if (represents_compartment()) {
model_object[KEY_IS_BNGL_COMPARTMENT] = true;
const BNG::Compartment& comp3d = bng_data.get_compartment(vol_compartment_id);
assert(comp3d.is_3d);
if (comp3d.name != obj_name) {
mcell_error(
"For data model export, name of object %s must be the same as its compartment name %s.",
obj_name.c_str(), comp3d.name.c_str());
}
if (comp3d.has_parent()) {
const BNG::Compartment& comp_parent = bng_data.get_compartment(comp3d.parent_compartment_id);
if (!comp_parent.is_3d) {
// parent of this 3d object is its membrane
model_object[KEY_MEMBRANE_NAME] = comp_parent.name;
if (comp_parent.has_parent()) {
const BNG::Compartment& comp3d_parent =
bng_data.get_compartment(comp_parent.parent_compartment_id);
assert(comp3d_parent.is_3d);
// parent of this 3d object is its membrane
model_object[KEY_PARENT_OBJECT] = comp3d_parent.name;
}
}
else {
// parent is this 3d object, membrane has no name
model_object[KEY_PARENT_OBJECT] = comp_parent.name;
}
}
}
else {
model_object[KEY_IS_BNGL_COMPARTMENT] = false;
}
model_object[KEY_DYNAMIC] = false;
}
// checks only in debug mode whether the wall index belongs to this object
rgba_t GeometryObject::get_wall_color(const wall_index_t wi) const {
assert(!wall_indices.empty());
assert(wi >= wall_indices.front() && wi <= wall_indices.back());
auto it = wall_specific_colors.find(wi);
if (it == wall_specific_colors.end()) {
return default_color;
}
else {
return it->second;
}
}
// checks only in debug mode whether the wall index belongs to this object
void GeometryObject::set_wall_color(const wall_index_t wi, const rgba_t color) {
assert(!wall_indices.empty());
assert(wi >= wall_indices.front() && wi <= wall_indices.back());
wall_specific_colors[wi] = color;
}
void InitialSurfaceReleases::to_data_model(
const BNG::SpeciesContainer& all_species,
Json::Value& initial_region_molecules
) const {
initial_region_molecules[KEY_MOLECULE] = all_species.get(species_id).name;
initial_region_molecules[KEY_ORIENT] = DMUtils::orientation_to_str(orientation);
if (const_num_not_density) {
initial_region_molecules[KEY_MOLECULE_NUMBER] = to_string(release_num);
}
else {
initial_region_molecules[KEY_MOLECULE_DENSITY] = f_to_str(release_density);
}
}
void InitialSurfaceReleases::dump(const std::string ind) const {
cout << ind <<
"species_id: " << species_id <<
", orientation: " << orientation <<
", const_num_not_density: " << const_num_not_density <<
", release_num: " << release_num <<
", release_density: " << release_density <<
"\n";
}
void Region::init_from_whole_geom_object(const GeometryObject& obj) {
name = obj.name + REGION_ALL_SUFFIX_W_COMMA;
geometry_object_id = obj.id;
// simply add all walls
for (const wall_index_t& wi: obj.wall_indices) {
add_wall_to_walls_and_edges(wi, false);
}
}
void Region::init_surface_region_edges(const Partition& p) {
assert(!walls_and_edges.empty());
// must be run after edge must be initializaion,
// however, not all edges need to be initialized
for (auto& it: walls_and_edges) {
const Wall& w = p.get_wall(it.first);
for (edge_index_t ei = 0; ei < EDGES_IN_TRIANGLE; ei++) {
const Edge& edge = w.edges[ei];
// uninitialized edges are considered to be bordering
if (!edge.is_initialized()) {
it.second.insert(ei);
}
else {
// is one of the forward or backward walls in our region?
// if not, then the edge is on the border of this region
if (walls_and_edges.count(edge.forward_index) == 0 ||
walls_and_edges.count(edge.backward_index) == 0) {
it.second.insert(ei);
}
}
}
}
}
/* tetrahedralVol returns the (signed) volume of the tetrahedron spanned by
* the vertices a, b, c, and d.
* The formula was taken from "Computational Geometry" (2nd Ed) by J. O'Rourke
*/
static pos_t tetrahedral_volume(
const Vec3& a, const Vec3& b,
const Vec3& c, const Vec3& d
) {
// TODO: maybe use vector operators
return (pos_t)1 / (pos_t)6 *
(-1 * (a.z - d.z) * (b.y - d.y) * (c.x - d.x) +
(a.y - d.y) * (b.z - d.z) * (c.x - d.x) +
(a.z - d.z) * (b.x - d.x) * (c.y - d.y) -
(a.x - d.x) * (b.z - d.z) * (c.y - d.y) -
(a.y - d.y) * (b.x - d.x) * (c.z - d.z) +
(a.x - d.x) * (b.y - d.y) * (c.z - d.z));
}
/***************************************************************************
Based on is_manifold:
In: r: A region. This region must already be painted on walls. The edges must
have already been added to the object (i.e. sharpened).
count_regions_flag: This is usually set, unless we are only checking
volumes for dynamic geometries.
Out: 1 if the region is a manifold, 0 otherwise.
Note: by "manifold" we mean "orientable compact two-dimensional
manifold without boundaries embedded in R3"
***************************************************************************/
void Region::initialize_volume_info_if_needed(const Partition& p) {
if (volume_info_initialized) {
return;
}
if (walls_and_edges.empty()) {
mcell_internal_error("Region '%s' has NULL wall array!", name.c_str());
}
// initialize bounding box
compute_bounding_box(p, bounding_box_llf, bounding_box_urb);
// use the center of the region bounding box as reference point for
// computing the volume
Vec3 d = (bounding_box_llf + bounding_box_urb) * Vec3(0.5);
perf() << "Computing volume of region " << name << "\n";
volume = 0;
pos_t current_volume = 0;
for (auto it: walls_and_edges) {
if (!it.second.empty()) {
// does this wall represent a region border?
region_is_manifold = false;
volume_info_initialized = true;
}
const Wall& w = p.get_wall(it.first);
// compute volume of tetrahedron with w as its face
current_volume += tetrahedral_volume(
p.get_wall_vertex(w, 0), p.get_wall_vertex(w, 1), p.get_wall_vertex(w, 2), d);
}
perf() << " - volume computed\n";
volume = current_volume;
region_is_manifold = true;
volume_info_initialized = true;
}
void Region::initialize_wall_subpart_mapping_if_needed(const Partition& p) {
if (walls_per_subpart_initialized) {
return;
}
perf() << "Preparing wall subpart mapping for region " << name << "\n";
// first initialize region wall subpart mapping
walls_per_subpart.clear();
// FIXME: update when a wall of this region is moved
for (const auto& wall_and_edges_pair: walls_and_edges) {
const Wall& w = p.get_wall(wall_and_edges_pair.first);
for (subpart_index_t si: w.present_in_subparts) {
walls_per_subpart[si].push_back(w.index);
}
}
perf() << " - wall subpart mapping prepared\n";
walls_per_subpart_initialized = true;
}
// returns true if the waypoint with current_waypoint_index is in this region
// similar code as in Partition::create_waypoint
bool Region::initialize_region_waypoint(
Partition& p,
const IVec3& current_waypoint_index,
const bool use_previous_waypoint,
const IVec3& previous_waypoint_index,
const bool previous_waypoint_present_in_region
) {
// waypoint is always in the center of a subpartition
// thanks to the extra margin on each side, we might be out of the partition
if (p.is_valid_waypoint_index(current_waypoint_index)) {
Waypoint& waypoint = p.get_waypoint(current_waypoint_index);
bool previous_waypoint_use_ok = false;
uint num_crossed;
if (use_previous_waypoint) {
const Waypoint& previous_waypoint = p.get_waypoint(previous_waypoint_index);
bool must_redo_test = false;
num_crossed = CollisionUtils::get_num_crossed_region_walls(
p, waypoint.pos, previous_waypoint.pos,
*this, must_redo_test
);
if (!must_redo_test) {
previous_waypoint_use_ok = true;
}
}
if (previous_waypoint_use_ok) {
// ok, test passed safely
if ((num_crossed % 2 == 0 && previous_waypoint_present_in_region) ||
(num_crossed % 2 == 1 && !previous_waypoint_present_in_region)) {
// still in the same region
waypoints_in_this_region.insert(current_waypoint_index);
return true;
}
else {
return false;
}
}
bool must_redo_test = false;
bool inside = false;
do {
inside = CollisionUtils::is_point_inside_region_no_waypoints(p, waypoint.pos, *this, must_redo_test);
if (must_redo_test) {
// updates values referenced by waypoint
p.move_waypoint_because_positioned_on_wall(current_waypoint_index);
}
} while (must_redo_test);
if (inside) {
waypoints_in_this_region.insert(current_waypoint_index);
return true;
}
}
return false;
}
void Region::initialize_region_waypoints_if_needed(Partition& p) {
if (region_waypoints_initialized) {
return;
}
perf() << "Initializing waypoints for region " << name << "\n";
assert(walls_per_subpart_initialized);
// get initial waypoint
waypoints_in_this_region.clear();
IVec3 llf_waypoint_index;
subpart_index_t subpart_index = p.get_subpart_index(bounding_box_llf);
p.get_subpart_3d_indices_from_index(subpart_index, llf_waypoint_index);
// then compute how many waypoints in each dimension we need to check
Vec3 region_dims = bounding_box_urb - bounding_box_llf;
// num_waypoints need to be incremented by 2 - for each of the side regions
IVec3 num_waypoints = region_dims / Vec3(p.config.subpart_edge_length) + Vec3(2);
bool previous_waypoint_present = false;
bool use_previous_waypoint = false;
IVec3 previous_waypoint_index;
for (int x = 0; x < num_waypoints.x; x++) {
for (int y = 0; y < num_waypoints.y; y++) {
for (int z = 0; z < num_waypoints.z; z++) {
IVec3 current_waypoint_index( llf_waypoint_index + IVec3(x, y, z) );
previous_waypoint_present = initialize_region_waypoint(
p, current_waypoint_index,
use_previous_waypoint, previous_waypoint_index, previous_waypoint_present
);
use_previous_waypoint = true;
previous_waypoint_index = current_waypoint_index;
}
// starting a new line - start from scratch
// NOTE: maybe we do not need to restart this every line
use_previous_waypoint = false;
previous_waypoint_present = false;
}
}
region_waypoints_initialized = true;
perf() << " - region waypoints initialized\n";
}
bool Region::is_point_inside(Partition& p, const Vec3& pos) {
initialize_volume_info_if_needed(p);
initialize_wall_subpart_mapping_if_needed(p);
initialize_region_waypoints_if_needed(p);
if (!is_manifold()) {
mcell_error("Cannot check whether a point is a non-manifold volumetric region %s. (possibly during a molecule release)", name.c_str());
}
// get a waypoint close to this position
IVec3 waypoint_index;
subpart_index_t subpart_index = p.get_subpart_index(pos); // TODO: get indices directly
p.get_subpart_3d_indices_from_index(subpart_index, waypoint_index);
const Waypoint& waypoint = p.get_waypoint(waypoint_index);
map<geometry_object_index_t, uint> num_crossed_walls_per_object;
bool must_redo_test = false;
uint num_crossed = CollisionUtils::get_num_crossed_region_walls(
p, pos, waypoint.pos,
*this, must_redo_test
);
if (!must_redo_test) {
// ok, using waypoint passed
bool waypoint_is_inside_this_region = waypoints_in_this_region.count(waypoint_index) != 0;
if (waypoint_is_inside_this_region) {
return num_crossed % 2 == 0;
}
else {
return num_crossed % 2 == 1;
}
}
else {
// let's try to compute the containment without waypoints as a fallback
bool inside = CollisionUtils::is_point_inside_region_no_waypoints(p, pos, *this, must_redo_test);
release_assert(!must_redo_test);
return inside;
}
}
void Region::dump(const std::string ind, const bool with_geometry) const {
cout << ind << "Region : " <<
"name:" << name <<
", species_id: " << ((species_id == SPECIES_ID_INVALID) ? string("invalid") : to_string(species_id)) <<
"\n";
cout << ind << " " << "initial_region_molecules :\n";
for (const auto& initial_mols: initial_region_molecules) {
initial_mols.dump(ind + " ");
}
if (with_geometry) {
for (auto& wall_it: walls_and_edges) {
cout << ind << " " << "wall " << wall_it.first << ", region edges: {";
for (auto& edge: wall_it.second) {
cout << edge << ", ";
}
cout << "}\n";
}
}
}
void Region::dump_array(const std::vector<Region>& vec) {
cout << "Region array: " << (vec.empty() ? "EMPTY" : "") << "\n";
for (size_t i = 0; i < vec.size(); i++) {
cout << i << ":\n";
vec[i].dump(" ");
}
}
void Region::to_data_model(const Partition& p, Json::Value& modify_surface_region) const {
if (initial_region_molecules.empty()) {
DMUtils::add_version(modify_surface_region, VER_DM_2018_01_11_1330);
}
else {
DMUtils::add_version(modify_surface_region, VER_DM_2020_07_12_1600);
}
modify_surface_region[KEY_DESCRIPTION] = "";
modify_surface_region[KEY_OBJECT_NAME] =
DMUtils::remove_obj_name_prefix(p.get_geometry_object(geometry_object_id).name);
string region_name = DMUtils::get_region_name(name);
if (region_name == "ALL") {
modify_surface_region[KEY_REGION_SELECTION] = VALUE_ALL;
modify_surface_region[KEY_REGION_NAME] = "";
}
else {
modify_surface_region[KEY_REGION_SELECTION] = VALUE_SEL;
modify_surface_region[KEY_REGION_NAME] = region_name;
}
modify_surface_region[KEY_NAME] = ""; // don't care
if (species_id != SPECIES_ID_INVALID) {
modify_surface_region[KEY_SURF_CLASS_NAME] = p.get_species(species_id).name;
}
if (!initial_region_molecules.empty()) {
Json::Value& initial_region_molecules_list = modify_surface_region[KEY_INITIAL_REGION_MOLECULES_LIST];
for (const InitialSurfaceReleases& info: initial_region_molecules) {
Json::Value initial_region_molecules_item;
info.to_data_model(p.get_all_species(), initial_region_molecules_item);
initial_region_molecules_list.append(initial_region_molecules_item);
}
}
}
namespace Geometry {
double compute_geometry_object_area(const Partition& p, const GeometryObject& obj) {
double res = 0;
for (wall_index_t wi: obj.wall_indices) {
res += p.get_wall(wi).area;
}
return res;
}
/***************************************************************************
eval_rel_region_bbox:
In: release expression for a 3D region release
place to store LLF corner of the bounding box for the release
place to store URB corner
Out: true on success, false on failure. Bounding box is set based on release
expression (based boolean intersection of bounding boxes for each
region). The function reports failure if any region is unclosed.
***************************************************************************/
// TODO: not checking whether object is closed - use some library for that
bool compute_region_expr_bounding_box(
World* world, const RegionExprNode* expr,
Vec3& llf, Vec3& urb
) {
int count_regions_flag = 1;
Partition& p = world->get_partition(0);
if (expr->op == RegionExprOperator::LEAF_SURFACE_REGION) {
Region& reg = p.get_region_by_id(expr->region_id);
reg.compute_bounding_box(p, llf, urb);
return true;
}
else if (expr->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
GeometryObject& go = p.get_geometry_object(expr->geometry_object_id);
Region& reg = p.get_region_by_id(go.encompassing_region_id);
reg.compute_bounding_box(p, llf, urb);
return true;
}
else {
Vec3 llf_left, urb_left;
compute_region_expr_bounding_box(world, expr->left, llf_left, urb_left);
Vec3 llf_right, urb_right;
compute_region_expr_bounding_box(world, expr->right, llf_right, urb_right);
llf = llf_left;
urb = urb_left;
if (expr->op == RegionExprOperator::UNION) {
if (llf.x > llf_right.x) {
llf.x = llf_right.x;
}
if (llf.y > llf_right.y) {
llf.y = llf_right.y;
}
if (llf.z > llf_right.z) {
llf.z = llf_right.z;
}
if (urb.x < urb_right.x) {
urb.x = urb_right.x;
}
if (urb.y < urb_right.y) {
urb.y = urb_right.y;
}
if (urb.z < urb_right.z) {
urb.z = urb_right.z;
}
}
else if (expr->op == RegionExprOperator::DIFFERENCE) {
// for difference/subtraction the MCell3 implementation returns
// the llf_left/urb_left
}
else if (expr->op == RegionExprOperator::INTERSECT) {
if (llf.x < llf_right.x) {
llf.x = llf_right.x;
}
if (llf.y < llf_right.y) {
llf.y = llf_right.y;
}
if (llf.z < llf_right.z) {
llf.z = llf_right.z;
}
if (urb.x > urb_right.x) {
urb.x = urb_right.x;
}
if (urb.y > urb_right.y) {
urb.y = urb_right.y;
}
if (urb.z > urb_right.z) {
urb.z = urb_right.z;
}
}
else {
assert(false);
return false;
}
return true;
}
}
// this is the entry point called from Partition class
void update_moved_walls(
Partition& p,
const std::vector<VertexMoveInfo*>& scheduled_vertex_moves,
// we can compute all the information already from scheduled_vertex_moves,
// but the keys of the map walls_with_their_moves are the walls that we need to update
const WallsWithTheirMovesMap& walls_with_their_moves
) {
// move all vertices
for (const VertexMoveInfo* move_info: scheduled_vertex_moves) {
// ignore moves where walls are fixed
if (!move_info->vertex_walls_are_movable) {
continue;
}
Vec3& vertex_ref = p.get_geometry_vertex(move_info->vertex_index);
vertex_ref = vertex_ref + move_info->displacement;
if (! p.in_this_partition(vertex_ref) ) {
mcell_log("Error: Crossing partitions is not supported yet.\n");
exit(1);
}
}
// update walls
for (auto it: walls_with_their_moves) {
wall_index_t wall_index = it.first;
Wall& w = p.get_wall(wall_index);
// first we need to update all wall constants
w.initialize_wall_constants(p);
// then update wall_collision_rejection_data that hold a copy
p.update_wall_collision_rejection_data(w);
// reinitialize grid
if (w.grid.is_initialized()) {
w.grid.initialize(p, w);
}
}
// edges need to be fixed after all wall have been moved
// otherwise the edge initialization would be using
// inconsistent data
// we need to update also edges of neighboring walls
uint_set<wall_index_t> walls_to_be_updated;
// NOTE: we might consider sharing edges in the same way as in MCell3
for (auto it: walls_with_their_moves) {
wall_index_t wall_index = it.first;
Wall& w = p.get_wall(wall_index);
walls_to_be_updated.insert(wall_index);
for (uint n = 0; n < EDGES_IN_TRIANGLE; n++) {
walls_to_be_updated.insert(w.nb_walls[n]);
}
}
for (wall_index_t wall_index: walls_to_be_updated) {
if (wall_index == WALL_INDEX_INVALID) {
continue;
}
Wall& w = p.get_wall(wall_index);
w.initialize_edge_constants(p);
}
}
void rgba_to_components(
const rgba_t rgba,
double& red, double& green, double& blue, double& alpha) {
const double MAX = 255.0;
red = (((uint)rgba >> 24) & 0xFF) / MAX;
green = (((uint)rgba >> 16) & 0xFF) / MAX;
blue = (((uint)rgba >> 8) & 0xFF) / MAX;
alpha = ((uint)rgba & 0xFF) / MAX;
}
} /* namespace Geometry */
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/wall.h | .h | 14,829 | 483 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_WALL_H_
#define SRC4_WALL_H_
#include <vector>
#include <set>
#include "defines.h"
#include "molecule.h"
#include "simulation_config.h"
#include "dyn_vertex_structs.h"
namespace Json {
class Value;
}
namespace MCell {
/* Used to transform coordinates of surface molecules diffusing between
* adjacent walls, owned by its wall */
class Edge {
public:
Edge()
: forward_index(WALL_INDEX_INVALID), backward_index(WALL_INDEX_INVALID),
edge_num_used_for_init(EDGE_INDEX_INVALID), translate(0), cos_theta(0), sin_theta(0)
{
}
bool is_initialized() const {
return edge_num_used_for_init != EDGE_INDEX_INVALID;
}
bool is_shared_edge() const {
return forward_index != WALL_INDEX_INVALID && backward_index != WALL_INDEX_INVALID;
}
// must not be called on non-shared edge
void reinit_edge_constants(const Partition& p);
void dump(const std::string ind = "") const;
void debug_check_values_are_uptodate(const Partition& p);
wall_index_t forward_index; /* For which wall is this a forwards transform? */
wall_index_t backward_index; /* For which wall is this a reverse transform? */
// used only for debug, checks that the precomputed values are correct
edge_index_t edge_num_used_for_init;
const Vec2& get_translate() const {
return translate;
}
pos_t get_cos_theta() const {
return cos_theta;
}
pos_t get_sin_theta() const {
return sin_theta;
}
void set_translate(const Vec2& value) {
translate = value;
}
void set_cos_theta(const pos_t value) {
cos_theta = value;
}
void set_sin_theta(const pos_t value) {
sin_theta = value;
}
private:
// --- egde constants ---
Vec2 translate; /* Translation vector between coordinate systems */
pos_t cos_theta; /* Cosine of angle between coordinate systems */
pos_t sin_theta; /* Sine of angle between coordinate systems */
};
class Wall;
/**
* Surface grid.
* Owned by its wall.
*
* Contains an array of tiles.
*/
class Grid {
public:
bool is_initialized() const {
// Every initialized grid has at least one item in this array
return !molecules_per_tile.empty();
}
void initialize(const Partition& p, const Wall& w);
wall_index_t wall_index;
uint num_tiles_along_axis; // Number of slots along each axis (originally n)
uint num_tiles; // Number of tiles in effector grid (triangle: grid_size^2, rectangle: 2*grid_size^2) (originally n_tiles)
pos_t strip_width_rcp; /* Reciprocal of the width of one strip */ // inv_strip_wid originally
pos_t vert2_slope; /* Slope from vertex 0 to vertex 2 */
pos_t fullslope; /* Slope of full width of triangle */
Vec2 vert0; /* Projection of vertex zero onto unit_u and unit_v of wall */
pos_t binding_factor;
void set_molecule_tile(tile_index_t tile_index, molecule_id_t id) {
assert(is_initialized());
assert(tile_index != TILE_INDEX_INVALID);
assert(num_tiles == molecules_per_tile.size());
assert(tile_index < molecules_per_tile.size());
assert(molecules_per_tile[tile_index] == MOLECULE_ID_INVALID && "Cannot overwite a molecule that is already on tile");
molecules_per_tile[tile_index] = id;
num_occupied++;
}
void reset_molecule_tile(tile_index_t tile_index) {
assert(is_initialized());
assert(tile_index != TILE_INDEX_INVALID);
assert(num_tiles == molecules_per_tile.size());
assert(tile_index < molecules_per_tile.size());
assert(molecules_per_tile[tile_index] != MOLECULE_ID_INVALID && "Cannot reset a tile that has no molecule");
molecules_per_tile[tile_index] = MOLECULE_ID_INVALID;
num_occupied--;
}
// returns MOLECULE_ID_INVALID when tile is not occupied
molecule_id_t get_molecule_on_tile(tile_index_t tile_index) const {
assert(is_initialized());
assert(tile_index != TILE_INDEX_INVALID);
assert(num_tiles == molecules_per_tile.size());
assert(tile_index < molecules_per_tile.size());
return molecules_per_tile[tile_index];
}
// populates array molecules with ids of molecules belonging to this grid
void get_contained_molecules(
small_vector<molecule_id_t>& molecule_ids
) const;
const MoleculeIdsVector& get_molecules_per_tile() const {
return molecules_per_tile;
}
void reset_all_tiles() {
std::fill(molecules_per_tile.begin(), molecules_per_tile.end(), MOLECULE_ID_INVALID);
num_occupied = 0;
}
bool is_full() const {
assert(is_initialized());
assert(num_occupied <= num_tiles);
return num_occupied == num_tiles;
}
uint get_num_occupied_tiles() const {
return num_occupied;
}
uint get_num_free_tiles() const {
assert(num_tiles >= num_occupied);
return num_tiles - num_occupied;
}
void dump() const;
private:
uint num_occupied; // How many tiles are occupied
// For now, there can be just one molecule per tile,
// value is MOLECULE_ID_INVALID when the tile is not occupied
// indexed by type tile_index_t
// Every initialized grid has at least one item in this array
MoleculeIdsVector molecules_per_tile;
};
/**
* Data that are used for fast rejection of wall collisions,
* stored as a copy in partition to optimize cache performance.
*/
class WallCollisionRejectionData {
public:
WallCollisionRejectionData()
: normal(POS_INVALID), distance_to_origin(POS_INVALID) {
}
WallCollisionRejectionData(const Vec3& normal_, const pos_t& distance_to_origin_)
: normal(normal_), distance_to_origin(distance_to_origin_) {
}
// for checking of consistency, the argument is usually Wall
bool has_identical_data_as_wall(const WallCollisionRejectionData& w) const {
return normal == w.normal && distance_to_origin == w.distance_to_origin;
}
Vec3 normal; /* Normal vector for this wall */
pos_t distance_to_origin; // distance to origin (point normal form)
};
class WallSharedData {
public:
std::vector<wall_index_t> shared_among_walls;
// merges shared_among_walls contents
void merge_initial_wall_data(const WallSharedData* wsd);
};
/**
* Single instance of a wall (mesh face).
* Owned by partition, also its vertices are owned by partition.
* Represented by a triangle.
*/
class Wall: public WallCollisionRejectionData {
public:
// wall_shared_data_ is owned by Partition and must not be not a nullptr when this is a Wall owned by
// a Partition, i.e. not used from WallWithVertices
// wall_id_ argument is used only when this constructor is called from constructor of WallWithVertices
Wall(WallSharedData* wall_shared_data_, const wall_id_t wall_id_ = WALL_ID_INVALID)
: id(wall_id_), index(WALL_INDEX_INVALID), side(0),
object_id(GEOMETRY_OBJECT_ID_INVALID), object_index(GEOMETRY_OBJECT_INDEX_INVALID),
is_movable(true),
wall_constants_initialized(false),
uv_vert1_u(POS_INVALID), uv_vert2(POS_INVALID),
unit_u(POS_INVALID), unit_v(POS_INVALID),
wall_shared_data(wall_shared_data_) {
nb_walls[0] = WALL_INDEX_INVALID;
nb_walls[1] = WALL_INDEX_INVALID;
nb_walls[2] = WALL_INDEX_INVALID;
vertex_indices[0] = VERTEX_INDEX_INVALID;
vertex_indices[1] = VERTEX_INDEX_INVALID;
vertex_indices[2] = VERTEX_INDEX_INVALID;
assert(!exists_in_partition() || wall_shared_data != nullptr);
}
bool exists_in_partition() const {
return id != WALL_ID_NOT_IN_PARTITION;
}
// needs vertex indices to be set
void initialize_wall_constants(const Partition& p);
// needs wall constants to be precomputed (all adjacent walls)
void initialize_edge_constants(const Partition& p);
bool is_same_region(const Wall& w) const {
if (w.object_id == object_id && w.regions == regions) {
return true;
}
else {
return false;
}
}
// shared
wall_id_t id; // world-unique identifier of this wall, mainly for debugging
wall_index_t index; // index in the partition where it is contained, must be fixed if moved
uint side; // index in its parent object, used only for printouts to the user - per object
geometry_object_id_t object_id; // id of object to which this wall belongs - per object
geometry_object_index_t object_index; // index of object in this partition to which this wall belongs - per object
bool is_movable;
bool wall_constants_initialized;
// indices of the three triangle's vertices,
// they are shared in a partition and a single vertex should be usually represented by just one item
// so when a position of one vertex changes, it should affect all the triangles that use it
vertex_index_t vertex_indices[VERTICES_IN_TRIANGLE]; // order is important since is specifies orientation
// note: edges can be shared among walls to save memory
// also they may be stored using std::vector to make the Wall object smaller
Edge edges[EDGES_IN_TRIANGLE];
// NOTE: what about walls that are neighboring over a partition edge?
wall_index_t nb_walls[EDGES_IN_TRIANGLE]; // neighboring wall indices - per object
pos_t uv_vert1_u; /* Surface u-coord of 2nd corner (v=0) */
Vec2 uv_vert2; /* Surface coords of third corner */
Vec3 unit_u; /* U basis vector for this wall */
Vec3 unit_v; /* V basis vector for this wall */
// owned by Partition, cannot use indexes due to
// cyclic header file dependency
WallSharedData* wall_shared_data;
// primary wall is the first listed in 'shared_among_walls'
bool is_primary_wall() const {
assert(wall_shared_data != nullptr);
return wall_shared_data->shared_among_walls[0] == index;
}
// overlapped wall is not the the first listed in 'shared_among_walls'
bool is_overlapped_wall() const {
assert(wall_shared_data != nullptr);
return wall_shared_data->shared_among_walls[0] != index;
}
// regions, one wall can belong to multiple regions, regions are owned by partition
// region may represent a surface class
// all regions listed here must be a part of 'regions' in the parent geometry object
uint_set<region_index_t> regions; // all regions for all objects -> shared?
SubpartIndicesSet present_in_subparts; // in what subpartitions is this wall located
Grid grid; // shared among overlapping walls
// --- wall constants ---
pos_t area; /* Area of this element (triangle) */
// p must be the partition that contains this object
void dump(const Partition& p, const std::string ind, const bool for_diff = false) const;
bool has_initialized_grid() const {
return grid.is_initialized();
}
void initialize_grid(const Partition& p) {
assert(!has_initialized_grid());
grid.initialize(p, *this);
}
};
// variant of a wall but this version has its vertices stored in its object,
// not in the partition,
// a Wall reference based on WallWithVertices has its id == WALL_ID_NOT_IN_PARTITION because it was
// not inserted into a partition
class WallWithVertices: public Wall {
public:
// edge constants initialization is not supported
WallWithVertices(const Partition& p,
const Vec3& v0, const Vec3& v1, const Vec3& v2,
const bool do_precompute_wall_constants) :
Wall(nullptr, WALL_ID_NOT_IN_PARTITION) {
wall_shared_data = new WallSharedData;
vertices[0] = v0;
vertices[1] = v1;
vertices[2] = v2;
if (do_precompute_wall_constants) {
initialize_wall_constants(p);
}
}
~WallWithVertices() {
delete wall_shared_data;
}
Vec3 vertices[VERTICES_IN_TRIANGLE];
};
enum class GridPosType {
NOT_INITIALIZED,
NOT_ASSIGNED, // already holds information on position but not used by product
REACA_UV,
REACB_UV,
POS_UV,
//USE_REACB_UV,
RANDOM
};
class GridPos;
typedef std::vector<GridPos> GridPosVector;
// auxiliary class used to hold information on
// grid position for reactions in DiffuseReactEvent::find_surf_product_positions
class GridPos {
public:
GridPos()
: type(GridPosType::NOT_INITIALIZED),
wall_index(WALL_INDEX_INVALID), tile_index(TILE_INDEX_INVALID),
pos_is_set(false), pos(POS_INVALID) {
}
static GridPos make_with_pos(const Vec2& pos, const WallTileIndexPair& wall_tile_index_pair) {
GridPos res;
res.type = GridPosType::NOT_ASSIGNED;
res.wall_index = wall_tile_index_pair.wall_index;
res.tile_index = wall_tile_index_pair.tile_index;
res.pos = pos;
res.pos_is_set = true;
return res;
}
static GridPos make_with_mol_pos(const Molecule& sm) {
assert(sm.is_surf());
assert(sm.s.pos.is_valid());
GridPos res;
res.type = GridPosType::NOT_ASSIGNED;
res.wall_index = sm.s.wall_index;
res.tile_index = sm.s.grid_tile_index;
res.pos = sm.s.pos;
res.pos_is_set = true;
return res;
}
static GridPos make_without_pos(const WallTileIndexPair& wall_tile_index_pair) {
assert(wall_tile_index_pair.tile_index != TILE_INDEX_INVALID);
GridPos res;
res.type = GridPosType::NOT_ASSIGNED;
res.wall_index = wall_tile_index_pair.wall_index;
res.tile_index = wall_tile_index_pair.tile_index;
res.pos_is_set = false;
return res;
}
// returns null if not found, asserts in debug mode if there are multiple options
static const GridPos* get_second_surf_product_pos(const GridPosVector& vec, const uint first_index) {
const GridPos* res = nullptr;
for (uint i = 0; i < vec.size(); i++) {
if (i != first_index && vec[i].is_assigned()) {
assert(res == nullptr);
res = &vec[i];
}
}
return res;
}
bool is_initialized() const {
return type != GridPosType::NOT_INITIALIZED;
}
bool is_assigned() const {
return is_initialized() && type != GridPosType::NOT_ASSIGNED;
}
void set_reac_type(const GridPosType t) {
assert(is_initialized() && !is_assigned());
assert(t >= GridPosType::REACA_UV && t <= GridPosType::RANDOM);
type = t;
}
bool has_same_wall_and_grid(const Molecule& m) const {
assert(m.is_surf());
return m.s.wall_index == wall_index && m.s.grid_tile_index == tile_index;
}
bool has_same_wall_and_grid(const GridPos& gp) const {
return gp.wall_index == wall_index && gp.tile_index == tile_index;
}
GridPosType type; // was this info initialized
wall_index_t wall_index; /* wall where the tile is on */
tile_index_t tile_index; /* index on that tile */
bool pos_is_set;
Vec2 pos;
};
} // namespace MCell
#endif /* SRC4_WALL_H_ */
| Unknown |
3D | mcellteam/mcell | src4/clamp_release_event.h | .h | 1,921 | 77 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_CLAMP_RELEASE_EVENT_H_
#define SRC4_CLAMP_RELEASE_EVENT_H_
#include <vector>
#include "base_event.h"
namespace MCell {
enum class ClampType {
INVALID,
CONCENTRATION,
FLUX
};
/**
* Molecules are released at:
* 1) concentration-clamped surfaces to maintain the desired concentration
* or
* 2) flux-clamped surfaces to maintain the desired influx
*
* Separate event from releases because it must be run after all releases and
* viz/count outputs before diffusion.
*/
class ClampReleaseEvent: public BaseEvent {
public:
ClampReleaseEvent(World* world_) :
BaseEvent(EVENT_TYPE_INDEX_CLAMP_RELEASE),
type(ClampType::INVALID),
species_id(SPECIES_ID_INVALID),
surf_class_species_id(SPECIES_ID_INVALID),
concentration(FLT_INVALID),
orientation(ORIENTATION_NONE),
scaling_factor(FLT_INVALID),
world(world_) {
}
virtual ~ClampReleaseEvent() {}
void step() override;
void dump(const std::string indent) const override;
void to_data_model(Json::Value& mcell_node) const override;
void update_cumm_areas_and_scaling();
public:
ClampType type; // used only when converting to data model
species_id_t species_id;
species_id_t surf_class_species_id;
double concentration;
orientation_t orientation;
double scaling_factor;
std::vector<CummAreaPWallIndexPair> cumm_area_and_pwall_index_pairs;
private:
World* world;
};
} // namespace mcell
#endif // SRC4_CLAMP_RELEASE_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/viz_output_event.h | .h | 1,822 | 68 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_VIZ_OUTPUT_EVENT_H_
#define SRC4_VIZ_OUTPUT_EVENT_H_
#include "base_event.h"
#include "mcell_structs_shared.h"
namespace MCell {
class Partition;
class Molecule;
/**
* Dumps world state either in a textual or cellblender format.
*/
class VizOutputEvent: public BaseEvent {
public:
VizOutputEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_VIZ_OUTPUT),
viz_mode(NO_VIZ_MODE),
visualize_all_species(false),
world(world_) {
}
virtual ~VizOutputEvent() {}
void step() override;
void dump(const std::string ind = "") const override;
void to_data_model(Json::Value& mcell_node) const override;
// DiffuseReactEvent must execute only up to this event
bool is_barrier() const override { return true; }
bool should_visualize_all_species() const;
static std::string iterations_to_string(const uint64_t current_iterations, const uint64_t total_iterations);
viz_mode_t viz_mode;
std::string file_prefix_name;
bool visualize_all_species;
uint_set<species_id_t> species_ids_to_visualize;
World* world;
private:
void compute_where_and_norm(
const Partition& p, const Molecule& m,
Vec3& where, Vec3& norm
);
FILE* create_and_open_output_file_name();
void output_ascii_molecules();
void output_cellblender_molecules();
};
} // namespace mcell
#endif // SRC4_VIZ_OUTPUT_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/viz_output_event.cpp | .cpp | 9,622 | 323 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <sstream>
#include <iomanip>
#include <stdio.h>
#include <errno.h>
#include "logging.h"
#include "mem_util.h"
#include "util.h"
#include "mcell_structs_shared.h"
#include "viz_output_event.h"
#include "geometry.h"
#include "world.h"
#include "datamodel_defines.h"
#include "geometry_utils.h"
#include "geometry_utils.inl"
#include "bng/filesystem_utils.h"
using namespace std;
namespace MCell {
void VizOutputEvent::dump(const std::string ind) const {
cout << ind << "Viz output event:\n";
std::string ind2 = ind + " ";
BaseEvent::dump(ind2);
cout << ind2 << "viz_mode: \t\t" << viz_mode << " [viz_mode_t] \t\t\n";
cout << ind2 << "file_prefix_name: \t\t" << file_prefix_name << " [const char*] \t\t\n";
}
void VizOutputEvent::step() {
switch (viz_mode) {
case NO_VIZ_MODE:
break;
case ASCII_MODE:
output_ascii_molecules();
break;
case CELLBLENDER_MODE_V1:
case CELLBLENDER_MODE_V2:
output_cellblender_molecules();
break;
default:
assert(false);
}
}
string VizOutputEvent::iterations_to_string(const uint64_t current_iterations, const uint64_t total_iterations) {
stringstream res;
uint64_t lli = 10;
int ndigits;
for (ndigits = 1; lli <= total_iterations && ndigits < 20; ndigits++) {
lli *= 10;
}
res << setfill('0') << std::setw(ndigits) << current_iterations;
return res.str();
}
FILE* VizOutputEvent::create_and_open_output_file_name() {
long long current_iteration = round(event_time); // NOTE: usage of round might be a little shaky here, maybe we will need a better way how to get the iteration index
//fprintf(stderr, "***dumps: %lld\n", current_iteration);
const char* type_name = (viz_mode == ASCII_MODE) ? "ascii" : "cellbin";
char* cf_name = CHECKED_SPRINTF(
"%s.%s.%s.dat",
file_prefix_name.c_str(),
type_name,
iterations_to_string(world->stats.get_current_iteration(), world->total_iterations).c_str()
);
assert(cf_name != nullptr);
FSUtils::make_dir_for_file_w_multiple_attempts(cf_name);
FILE *custom_file = ::open_file(cf_name, (viz_mode == ASCII_MODE) ? "w" : "wb");
if (custom_file == nullptr)
mcell_die();
else {
no_printf("Writing to file %s\n", cf_name);
}
free(cf_name);
return custom_file;
}
void VizOutputEvent::compute_where_and_norm(
const Partition& p, const Molecule& m,
Vec3& where, Vec3& norm
) {
const BNG::Species& species = world->get_all_species().get(m.species_id);
if (species.is_vol()) {
// neither surface nor on grid
where = m.v.pos;
norm = Vec3(0);
}
else if (species.is_surf()) {
const Wall& wall = p.get_wall(m.s.wall_index);
const Vec3& wall_vert0 = p.get_geometry_vertex(wall.vertex_indices[0]);
where = GeometryUtils::uv2xyz(m.s.pos, wall, wall_vert0);
norm = Vec3(m.s.orientation) * wall.normal;
}
else {
assert(false && "Unexpected molecule type");
where = Vec3(0); // to silence compiler warnings
norm = Vec3(0);
}
where *= world->config.length_unit;
}
void VizOutputEvent::output_ascii_molecules() {
// assuming that fdlp->type == ALL_MOL_DATA
FILE *custom_file = create_and_open_output_file_name();
// simply go through all partitions and dump all molecules
for (Partition& p: world->get_partitions()) {
for (const Molecule& m: p.get_molecules()) {
if (m.is_defunct()) {
continue;
}
if (!visualize_all_species && species_ids_to_visualize.count(m.species_id) == 0) {
continue;
}
Vec3 where;
Vec3 norm;
compute_where_and_norm(p, m, where, norm);
const BNG::Species& species = world->get_all_species().get(m.species_id);
// cast to double for printouts
glm::dvec3 dwhere = where;
glm::dvec3 dnorm = norm;
assert(sizeof(dwhere.x) == sizeof(double));
errno = 0;
fprintf(custom_file, "%s %u %.9g %.9g %.9g %.9g %.9g %.9g\n",
species.name.c_str(), m.id,
dwhere.x, dwhere.y, dwhere.z,
dnorm.x, dnorm.y, dnorm.z
);
assert(errno == 0);
}
}
errno = 0;
fclose(custom_file);
assert(errno == 0);
}
void VizOutputEvent::output_cellblender_molecules() {
assert(sizeof(u_int) == sizeof(uint));
FILE *custom_file = create_and_open_output_file_name();
double length_unit = world->config.length_unit;
// sort all molecules by species
typedef pair<const Partition*, const Molecule*> PartitionMoleculePair;
// indexed by species id
map<species_id_t, vector<PartitionMoleculePair> > volume_molecules_by_species;
for (Partition& p: world->get_partitions()) {
for (const Molecule& m: p.get_molecules()) {
if (m.is_defunct()) {
continue;
}
if (!visualize_all_species && species_ids_to_visualize.count(m.species_id) == 0) {
continue;
}
volume_molecules_by_species[m.species_id].push_back(PartitionMoleculePair(&p, &m));
}
}
/* Write file header */
uint ver = (viz_mode == CELLBLENDER_MODE_V2) ? 2 : 1;
fwrite(&ver, sizeof(uint), 1, custom_file);
/* Write all the molecules whether EXTERNAL_SPECIES or not (for now) */
for (species_id_t species_idx = 0; species_idx < world->get_all_species().get_count(); species_idx++) {
// count of molecules for this species
vector<PartitionMoleculePair>& species_molecules = volume_molecules_by_species[species_idx];
if (species_molecules.empty()) {
continue;
}
/* Write species name: */
const BNG::Species& species = world->get_all_species().get(species_idx);
string mol_name = species.name;
if (ver == 1) {
unsigned char name_len = mol_name.length();
fwrite(&name_len, sizeof(unsigned char), 1, custom_file);
}
else {
uint name_len = mol_name.length();
fwrite(&name_len, sizeof(uint), 1, custom_file);
}
fwrite(mol_name.c_str(), sizeof(char), mol_name.length(), custom_file);
/* Write species type: */
unsigned char species_type = 0;
if (species.is_surf()) {
species_type = 1;
}
fwrite(&species_type, sizeof(unsigned char), 1, custom_file);
/* write number of x,y,z floats for mol positions to follow: */
if (ver == 1) {
uint n_floats = 3 * species_molecules.size();
fwrite(&n_floats, sizeof(uint), 1, custom_file);
}
else {
uint n_mols = species_molecules.size();
fwrite(&n_mols, sizeof(uint), 1, custom_file);
}
/* Write molecule ids: */
if (ver == 2) {
for (const PartitionMoleculePair& partition_molecule_ptr_pair :species_molecules) {
fwrite(&partition_molecule_ptr_pair.second->id, sizeof(uint), 1, custom_file);
}
}
/* Write positions of volume and surface molecules: */
std::vector<Vec3> norms;
for (const PartitionMoleculePair& partition_molecule_ptr_pair :species_molecules) {
Vec3 where;
Vec3 norm;
compute_where_and_norm(
*partition_molecule_ptr_pair.first, *partition_molecule_ptr_pair.second,
where, norm
);
// the values are always stored as float
glm::fvec3 fwhere = where;
assert(sizeof(fwhere.x) == sizeof(float));
fwrite(&fwhere.x, sizeof(float), 1, custom_file);
fwrite(&fwhere.y, sizeof(float), 1, custom_file);
fwrite(&fwhere.z, sizeof(float), 1, custom_file);
if (species.is_surf()) {
norms.push_back(norm);
}
}
// store norm - presence of this information is determined by species_type
for (const Vec3& norm :norms) {
glm::fvec3 fnorm = norm;
fwrite(&fnorm.x, sizeof(float), 1, custom_file);
fwrite(&fnorm.y, sizeof(float), 1, custom_file);
fwrite(&fnorm.z, sizeof(float), 1, custom_file);
}
}
fclose(custom_file);
}
bool VizOutputEvent::should_visualize_all_species() const {
if (visualize_all_species) {
return true;
}
// we are counting only specific vol & surf species, not reactive surfaces
uint vol_surf_species_count = 0;
for (const BNG::Species* s: world->get_all_species().get_species_vector()) {
release_assert(s != nullptr);
if (!BNG::is_species_superclass(s->name) && !s->is_reactive_surface()) {
vol_surf_species_count++;
}
}
return species_ids_to_visualize.size() == vol_surf_species_count;
}
void VizOutputEvent::to_data_model(Json::Value& mcell_node) const {
// there can be just one viz_output section
CONVERSION_CHECK(!mcell_node.isMember(KEY_VIZ_OUTPUT), "Only one viz_output section is allowed");
Json::Value& viz_output = mcell_node[KEY_VIZ_OUTPUT];
DMUtils::add_version(viz_output, VER_DM_2014_10_24_1638);
viz_output[KEY_EXPORT_ALL] = should_visualize_all_species();
viz_output[KEY_START] = f_to_str(event_time);
viz_output[KEY_ALL_ITERATIONS] = cmp_eq(periodicity_interval, 1.0);
if (periodicity_interval == 0) {
warns() << "Viz output periodicity is 0, this is not supported by MDL, exporting it as 1e6.\n";
viz_output[KEY_STEP] = f_to_str(1e6);
}
else {
viz_output[KEY_STEP] = f_to_str(periodicity_interval);
}
viz_output[KEY_END] = to_string(world->total_iterations);
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/geometry.h | .h | 13,503 | 412 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_GEOMETRY_H_
#define SRC4_GEOMETRY_H_
#include <vector>
#include <set>
#include "defines.h"
#include "molecule.h"
#include "simulation_config.h"
#include "dyn_vertex_structs.h"
#include "wall.h"
namespace Json {
class Value;
}
namespace MCell {
class Partition;
class World;
class RegionExprNode;
const char* const REGION_ALL_SUFFIX_W_COMMA = ",ALL";
// counted volumes are represented as a set of all counted
// geometry objects that wholly contain the volume region
class CountedVolume {
public:
CountedVolume()
: index(COUNTED_VOLUME_INDEX_INVALID) {
}
counted_volume_index_t index;
uint_set<geometry_object_index_t> contained_in_objects;
// for search in a map, does not compare index
bool operator < (const CountedVolume& other) const {
return contained_in_objects < other.contained_in_objects;
}
void dump() const {
contained_in_objects.dump();
}
};
/**
* A single geometrical object composed of multiple walls.
* Vertices are accessible through the wall indices.
* Owned by partition.
*/
class GeometryObject {
public:
GeometryObject()
: id(GEOMETRY_OBJECT_ID_INVALID), index(GEOMETRY_OBJECT_INDEX_INVALID),
encompassing_region_id(REGION_ID_INVALID),
vol_compartment_id(BNG::COMPARTMENT_ID_NONE),
surf_compartment_id(BNG::COMPARTMENT_ID_NONE),
counted_volume_index_inside(COUNTED_VOLUME_INDEX_INVALID),
counted_volume_index_outside(COUNTED_VOLUME_INDEX_INVALID),
is_fully_transparent(false),
has_overlapped_walls(false),
default_color(DEFAULT_COLOR),
is_used_in_mol_rxn_counts(false)
{
}
geometry_object_id_t id; // world-unique geometry object ID
geometry_object_index_t index; // partition-unique geometry object index
region_id_t encompassing_region_id; // ID of Region that represents this whole object, used only in pymcell4 for now
// ID of compartment that represents volume enclosed by this object,none by default
BNG::compartment_id_t vol_compartment_id;
// ID of compartment that represents the surface of this object, none by default
BNG::compartment_id_t surf_compartment_id;
std::string name;
std::string parent_name;
// all walls (triangles) that form this object,
// wall indices are unique in each partition, i.e. they are not counted from 0 for each object
std::vector<wall_index_t> wall_indices;
// all regions located on this object
uint_set<region_index_t> regions;
// counted volume to be set when a molecule goes inside of this object
// might be set to COUNTED_VOLUME_INDEX_INTERSECTS if this object intersects
// with another object
counted_volume_index_t counted_volume_index_inside;
// counted volume to be set when a molecule goes outside of this object
// might be set to COUNTED_VOLUME_INDEX_INTERSECTS if the direct parent of
// this object intersects with another object
counted_volume_index_t counted_volume_index_outside;
// set in initialize_is_fully_transparent, true if all walls have only surface class
// that makes them transparent to all molecules, used in overlapping wall detections
bool is_fully_transparent;
// to true set in check_for_overlapped_walls iff at least one of this object's
// wall is overlapped, such object does not allow surface releases and cannot be a
// BNGL compartment
bool has_overlapped_walls;
// default color id of this object
rgba_t default_color;
// if wall index is not present in this map the wall's color is the default_color
std::map<wall_index_t, rgba_t> wall_specific_colors;
bool represents_compartment() const {
return vol_compartment_id != BNG::COMPARTMENT_ID_NONE;
}
bool is_counted_volume_or_compartment() const {
assert(vol_compartment_id != BNG::COMPARTMENT_ID_INVALID);
return is_used_in_mol_rxn_counts || represents_compartment();
}
void initialize_neighboring_walls_and_their_edges(Partition& p);
void set_is_used_in_mol_rxn_counts(const bool value = true) {
is_used_in_mol_rxn_counts = value;
}
// returns indices of all vertices in this object that are connected through an edge
// uses caching because initial discovery is expensive
const std::set<vertex_index_t>& get_connected_vertices(
const Partition& p, const vertex_index_t vi);
// returns wall index for a pair of vertex indices
// uses caching because initial discovery is expensive
wall_index_t get_wall_for_vertex_pair(
const Partition& p, const vertex_index_t vi1, const vertex_index_t vi2);
// checks all walls and their regions and if all are only transparent to all molecules,
// sets member is_fully_transparent to true
void initialize_is_fully_transparent(Partition& p);
// returns nonempty string on error
std::string validate_volumetric_mesh(const Partition& p) const;
// p must be the partition that contains this object
void dump(const Partition& p, const std::string ind) const;
static void dump_array(const Partition& p, const std::vector<GeometryObject>& vec);
void to_data_model_as_geometrical_object(
const Partition& p, const SimulationConfig& config,
Json::Value& object,
std::set<rgba_t>& used_colors) const;
void to_data_model_as_model_object(const Partition& p, Json::Value& model_object) const;
// checks only in debug mode whether the wall index belongs to this object
rgba_t get_wall_color(const wall_index_t wi) const;
// sets wall_specific_colors[wi] = color even if color is default_color
// checks only in debug mode whether the wall index belongs to this object
void set_wall_color(const wall_index_t wi, const rgba_t color);
private:
// true if there are MolOrRxnCountEvents that use this geometry object,
// made private to make sure that is_counted_volume() is used when checking
// whether crossing this objects' walls should be taken into account
bool is_used_in_mol_rxn_counts;
// cache with information on which vertices are connected through edges,
// used in dynamic geometry collision detection
std::map<vertex_index_t, std::set<vertex_index_t>> connected_vertices_cache;
// cache with information on which vertex pairs belong to which walls
std::map<UnorderedPair<vertex_index_t>, wall_index_t> vertex_pair_to_wall_cache;
};
typedef std::map<subpart_index_t, small_vector<wall_index_t>> WallsPerSubpartMap;
// this class holds information for initial release of molecules onto regions specified by
// MDL's MODIFY_SURFACE_REGIONS/MOLECULE_DENSITY or MOLECULE_NUMBER
class InitialSurfaceReleases {
public:
InitialSurfaceReleases(
species_id_t species_id_,
orientation_t orientation_,
bool const_num_not_density_,
uint release_num_)
: species_id(species_id_), orientation(orientation_), const_num_not_density(const_num_not_density_),
release_num(release_num_), release_density(FLT_INVALID) {
assert(const_num_not_density_ && "This ctor is for const_num");
}
InitialSurfaceReleases(
species_id_t species_id_,
orientation_t orientation_,
bool const_num_not_density_,
double release_density_)
: species_id(species_id_), orientation(orientation_), const_num_not_density(const_num_not_density_),
release_num(UINT_INVALID), release_density(release_density_) {
assert(!const_num_not_density_ && "This ctor is for density");
}
bool is_release_by_num() const {
return const_num_not_density;
}
bool is_release_by_density() const {
return !const_num_not_density;
}
void to_data_model(
const BNG::SpeciesContainer& all_species,
Json::Value& initial_region_molecules
) const;
void dump(const std::string ind) const;
species_id_t species_id;
orientation_t orientation;
bool const_num_not_density;
uint release_num;
double release_density;
};
class Region {
public:
Region()
: id(REGION_ID_INVALID), index(REGION_INDEX_INVALID), species_id(SPECIES_ID_INVALID),
geometry_object_id(GEOMETRY_OBJECT_ID_INVALID), name(""),
volume_info_initialized(false), region_is_manifold(false),
walls_per_subpart_initialized(false), region_waypoints_initialized(false),
volume(FLT_INVALID)
{
}
region_id_t id;
region_index_t index;
// the reactivity of a region is modeled using reactions,
// if this region belongs to a surface class, species_id is to to represent the surface class
// may be SPECIES_ID_INVALID is there is not surface class assigned to this region
species_id_t species_id;
bool has_surface_class() const {
return species_id != SPECIES_ID_INVALID;
}
// to which object this region belongs
geometry_object_id_t geometry_object_id;
std::string name;
// each wall contained in this map is a part of this region
// the vector of edge indices may be empty but if not, it specifies the
// edge od the wall that is a border of the region
std::map<wall_index_t, std::set<edge_index_t>> walls_and_edges;
// initial counts of molecules for this region
std::vector<InitialSurfaceReleases> initial_region_molecules;
private:
bool volume_info_initialized;
bool region_is_manifold;
bool walls_per_subpart_initialized;
bool region_waypoints_initialized;
Vec3 bounding_box_llf;
Vec3 bounding_box_urb;
pos_t volume;
WallsPerSubpartMap walls_per_subpart;
// points known to be inside of this region, optimization
// for checking whether a point is inside of this region
std::set<IVec3> waypoints_in_this_region;
public:
void initialize_volume_info_if_needed(const Partition& p);
void compute_bounding_box(const Partition& p, Vec3& llf, Vec3& urb);
bool is_manifold() const {
assert(volume_info_initialized);
return region_is_manifold;
}
pos_t get_volume() const {
assert(volume_info_initialized);
return volume;
}
const Vec3& get_bounding_box_llf() const {
assert(volume_info_initialized);
return bounding_box_llf;
}
const Vec3& get_bounding_box_urb() const {
assert(volume_info_initialized);
return bounding_box_urb;
}
const WallsPerSubpartMap& get_walls_per_subpart() const {
assert(walls_per_subpart_initialized);
return walls_per_subpart;
}
bool is_edge(wall_index_t wall_index, edge_index_t edge_index) const {
auto it = walls_and_edges.find(wall_index);
if (it != walls_and_edges.end()) {
return it->second.count(edge_index) != 0;
}
else {
return false;
}
}
bool is_reactive() const {
return species_id != SPECIES_ID_INVALID;
}
bool is_point_inside(Partition& p, const Vec3& pos);
// covers whole region
bool name_has_suffix_ALL() const {
std::string all(REGION_ALL_SUFFIX_W_COMMA);
if (name.size() > all.size()) {
return name.substr(name.size() - all.size()) == all;
}
else {
return false;
}
}
// for regions that encompass the whole geometry object ([ALL])
void init_from_whole_geom_object(const GeometryObject& obj);
// for regions that represent a surface region ([xxx])
// walls must be already set
void init_surface_region_edges(const Partition& p);
void add_wall_to_walls_and_edges(const wall_index_t wi, const bool incl_edges = false) {
walls_and_edges.insert(std::make_pair(wi, std::set<edge_index_t>()));
if (incl_edges) {
walls_and_edges[wi].insert(EDGE_INDEX_0);
walls_and_edges[wi].insert(EDGE_INDEX_1);
walls_and_edges[wi].insert(EDGE_INDEX_2);
}
}
bool has_initial_molecules() const {
return !initial_region_molecules.empty();
}
void dump(const std::string ind, const bool with_geometry = false) const;
static void dump_array(const std::vector<Region>& vec);
void to_data_model(const Partition& p, Json::Value& modify_surface_region) const;
private:
void initialize_wall_subpart_mapping_if_needed(const Partition& p);
bool initialize_region_waypoint(
Partition& p,
const IVec3& current_waypoint_index,
const bool use_previous_waypoint,
const IVec3& previous_waypoint_index,
const bool previous_waypoint_present
);
void initialize_region_waypoints_if_needed(Partition& p);
};
typedef std::vector<GeometryObject> GeometryObjectVector;
// several utility functions related to geometry
namespace Geometry {
double compute_geometry_object_area(const Partition& p, const GeometryObject& obj);
// used when creating release event
bool compute_region_expr_bounding_box(
World* world, const RegionExprNode* region_expr,
Vec3& llf, Vec3& urb
);
// this is the entry point called from Partition class
void update_moved_walls(
Partition& p,
const std::vector<VertexMoveInfo*>& scheduled_vertex_moves,
// we can compute all the information already from scheduled_vertex_moves,
// but the keys of the map walls_with_their_moves are the walls that we need to update
const WallsWithTheirMovesMap& walls_with_their_moves
);
void rgba_to_components(
const rgba_t rgba,
double& red, double& green, double& blue, double& alpha);
} // namespace Geometry
} // namespace MCell
#endif /* SRC4_GEOMETRY_H_ */
| Unknown |
3D | mcellteam/mcell | src4/partition.cpp | .cpp | 38,732 | 1,088 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <algorithm>
#include "logging.h"
#include "partition.h"
#include "datamodel_defines.h"
#include "wall_utils.h"
#include "dyn_vertex_utils.inl"
#include "collision_utils.inl"
#include "wall_utils.inl"
using namespace std;
namespace MCell {
static void zero_out_lowest_bits_pos(pos_t* val) {
uint tmp;
memcpy(&tmp, val, sizeof(uint));
tmp &= 0xFFFFF000;
memcpy(val, &tmp, sizeof(uint));
}
Partition::Partition(
const partition_id_t id_,
const Vec3& origin_corner_,
const SimulationConfig& config_,
BNG::BNGEngine& bng_engine_,
SimulationStats& stats_
)
: origin_corner(origin_corner_),
next_molecule_id(0),
volume_molecule_reactants_per_reactant_class(config_.num_subparts),
id(id_),
config(config_),
bng_engine(bng_engine_),
stats(stats_) {
#if POS_T_BYTES == 4
zero_out_lowest_bits_pos(&origin_corner.x);
zero_out_lowest_bits_pos(&origin_corner.y);
zero_out_lowest_bits_pos(&origin_corner.z);
#endif
opposite_corner = origin_corner + config.partition_edge_length;
// check that the subpart grid goes through (0, 0, 0),
// (this point does not have to be contained in this partition)
// required for correct function of raycast_with_endpoints,
// round is required because values might be negative
Vec3 how_many_subparts_from_000 = origin_corner/Vec3(config.subpart_edge_length);
release_assert(cmp_eq(round3(how_many_subparts_from_000), how_many_subparts_from_000, POS_SQRT_EPS) &&
"Partition is not aligned to the subpartition grid."
);
// pre-allocate volume_molecules arrays and also volume_molecule_indices_per_time_step
walls_per_subpart.resize(config.num_subparts);
// create an empty counted volume
CountedVolume counted_volume_outside_all;
counted_volume_index_t index = find_or_add_counted_volume(counted_volume_outside_all);
assert(index == COUNTED_VOLUME_INDEX_OUTSIDE_ALL && "The empty counted volume must have index 0");
rng_init(&aux_rng, config.initial_seed);
}
Partition::~Partition() {
// these data can be shared among multiple walls therefore they are
// owned by Partition
for (WallSharedData* ptr: wall_shared_data) {
delete ptr;
}
}
// when a wall is added with add_uninitialized_wall,
// its type and vertices are not know yet, we must include the walls
// into subvolumes and also for other purposes
void Partition::finalize_walls() {
for (Wall& w: walls) {
wall_index_t wall_index = w.index;
for (vertex_index_t vi: w.vertex_indices) {
add_wall_using_vertex_mapping(vi, wall_index);
}
w.present_in_subparts.clear();
// also insert this triangle into walls per subpartition
SubpartIndicesVector colliding_subparts;
GeometryUtils::wall_subparts_collision_test(*this, w, colliding_subparts);
for (subpart_index_t subpart_index: colliding_subparts) {
assert(subpart_index < walls_per_subpart.size());
// mapping subpart->wall
walls_per_subpart[subpart_index].insert(wall_index);
// mapping wall->subpart
w.present_in_subparts.insert(subpart_index); // TODO: use insert_unique
}
// make a cache-optimized copy of certain fields from Wall
assert(wall_collision_rejection_data.size() == wall_index);
wall_collision_rejection_data.push_back(w);
}
}
// remove items when 'insert' is false
void Partition::update_walls_per_subpart(const WallsWithTheirMovesMap& walls_with_their_moves, const bool insert) {
for (auto it: walls_with_their_moves) {
wall_index_t wall_index = it.first;
SubpartIndicesVector colliding_subparts;
Wall& w = get_wall(wall_index);
GeometryUtils::wall_subparts_collision_test(*this, w, colliding_subparts);
assert(insert || SubpartIndicesSet(colliding_subparts.begin(), colliding_subparts.end()) == w.present_in_subparts);
for (subpart_index_t subpart_index: colliding_subparts) {
assert(subpart_index < walls_per_subpart.size());
if (insert) {
walls_per_subpart[subpart_index].insert_unique(wall_index);
w.present_in_subparts.insert(subpart_index);
}
else {
walls_per_subpart[subpart_index].erase_existing(wall_index);
w.present_in_subparts.erase(subpart_index);
}
}
}
}
template<typename T>
static void randomize_vector(rng_state& rng, std::vector<T>& vec) {
uint n = vec.size();
for (uint i = n-1; i > 0; --i) {
double rand = rng_dbl(&rng);
release_assert(rand >= 0 && rand <= 1);
// scale rand to 0..n-1
uint rand_index = (double)(n-1) * rand;
assert(rand_index < n);
T tmp = vec[i];
vec[i] = vec[rand_index];
vec[rand_index] = tmp;
}
}
void Partition::apply_vertex_moves(
const bool randomize_order,
std::vector<VertexMoveInfo>& ordered_vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules) {
colliding_walls.clear();
std::vector<VertexMoveInfo*> vertex_moves;
for (VertexMoveInfo& vertex_move_info: ordered_vertex_moves) {
vertex_moves.push_back(&vertex_move_info);
}
if (randomize_order) {
randomize_vector(aux_rng, vertex_moves);
}
// due to wall-wall collision detection, we must move vertices of each object separately
// is there a single object that we are moving?
geometry_object_id_t object_id = GEOMETRY_OBJECT_ID_INVALID;
bool single_object = true;
for (const VertexMoveInfo* vertex_move_info: vertex_moves) {
if (object_id == GEOMETRY_OBJECT_ID_INVALID || object_id == vertex_move_info->geometry_object_id) {
object_id = vertex_move_info->geometry_object_id;
}
else {
single_object = false;
break;
}
}
if (single_object) {
apply_vertex_moves_per_object(
true, vertex_moves,
colliding_walls, vertex_moves_due_to_paired_molecules);
}
else {
// we must make a separate vector for each
map<geometry_object_id_t, vector<VertexMoveInfo*>> vertex_moves_per_object;
for (VertexMoveInfo* vertex_move_info: vertex_moves) {
vertex_moves_per_object[vertex_move_info->geometry_object_id].push_back(vertex_move_info);
}
// randomize ordering of objects if requested
vector<geometry_object_id_t> application_order;
for (auto& pair_id_moves: vertex_moves_per_object) {
application_order.push_back(pair_id_moves.first);
}
if (randomize_order) {
randomize_vector(aux_rng, application_order);
}
// and process objects one by one
for (geometry_object_id_t object_id: application_order) {
apply_vertex_moves_per_object(
true, vertex_moves_per_object[object_id],
colliding_walls, vertex_moves_due_to_paired_molecules);
}
}
}
void Partition::apply_vertex_moves_per_object(
const bool move_paired_walls,
std::vector<VertexMoveInfo*>& vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules) {
// 0) clamp maximum movement and collect walls that collide
clamp_vertex_moves_to_wall_wall_collisions(vertex_moves, colliding_walls);
// 1) create a set of all affected walls with information on how much each wall moves,
uint_set<vertex_index_t> moved_vertices_set;
WallsWithTheirMovesMap walls_with_their_moves;
for (VertexMoveInfo* vertex_move_info: vertex_moves) {
// expecting that there we are not moving a single vertex twice
if (moved_vertices_set.count(vertex_move_info->vertex_index) != 0) {
mcell_error(
"When moving dynamic vertices, each vertex may be listed just once, error for vertex with index %d.",
vertex_move_info->vertex_index
);
}
moved_vertices_set.insert(vertex_move_info->vertex_index);
const std::vector<wall_index_t>& wall_indices = get_walls_using_vertex(vertex_move_info->vertex_index);
// first check whether we can move all walls belonging to the vertex
for (wall_index_t wall_index: wall_indices) {
if (!get_wall(wall_index).is_movable) {
// we must not move this vertex
vertex_move_info->vertex_walls_are_movable = false;
break;
}
}
// if the move is applicable, create mapping in walls_with_their_moves
if (vertex_move_info->vertex_walls_are_movable) {
for (wall_index_t wall_index: wall_indices) {
// remember mapping wall_index -> moves
auto it = walls_with_their_moves.find(wall_index);
if (it == walls_with_their_moves.end()) {
it = walls_with_their_moves.insert(make_pair(wall_index, WallMoveInfo())).first;
}
it->second.vertex_moves.push_back(vertex_move_info);
}
}
}
// set whether walls change area
for (auto& it: walls_with_their_moves) {
// TODO: implement check to optimize performance
it.second.wall_changes_area = true;
}
// 2) for each wall, detect what molecules will be moved and move them right away
// In some cases, moving one wall might place a molecule into a path of another moved wall,
// however, they should be moved at the same time, so we use just the first move and skip any other further moves.
// Not completely sure about this, but it seems that the same behavior should be achieved when
// we would first collect all moves and do them later, however we are creating temporary walls,
// so remembering them would be more complicated.
VolumeMoleculeMoveInfoVector volume_molecule_moves;
MoleculeIdsSet already_moved_volume_molecules;
SurfaceMoleculeMoveInfoVector surface_molecule_moves;
#ifdef DEBUG_DYNAMIC_GEOMETRY_MCELL4_ONLY
cout << "*** Walls being moved:\n";
for (const auto& it: walls_with_their_moves) {
const Wall& w = get_wall(it.first);
w.dump(*this, " ", true);
}
#endif
MoleculeIdsVector paired_molecules;
for (const auto& it: walls_with_their_moves) {
DynVertexUtils::collect_volume_molecules_moved_due_to_moving_wall(
*this, it.first, it.second, already_moved_volume_molecules, volume_molecule_moves);
// required also to find paired molecules
DynVertexUtils::collect_surface_molecules_moved_due_to_moving_wall(
*this, it.first, surface_molecule_moves, paired_molecules);
}
// 3) get information on where these walls are and remove them
update_walls_per_subpart(walls_with_their_moves, false);
// 4) then we move the vertices and update relevant walls
Geometry::update_moved_walls(*this, vertex_moves, walls_with_their_moves);
// 5) update subpartition info for the walls
update_walls_per_subpart(walls_with_their_moves, true);
// 6) move volume molecules
for (const VolumeMoleculeMoveInfo& move_info: volume_molecule_moves) {
DynVertexUtils::move_volume_molecule_to_closest_wall_point(*this, move_info);
}
// 7) move surface molecules
// 7.1) clear grids of affected walls
for (const auto& it: walls_with_their_moves) {
if (it.second.wall_changes_area) {
Wall& w = get_wall(it.first);
if (w.grid.is_initialized()) {
w.grid.reset_all_tiles();
}
}
}
// 7.2) do the actual movement
// mcell3 compatibility - sort surface_molecule_moves by id in order to
// use the same grid locations as in mcell3, not really needed for correctness
sort( surface_molecule_moves.begin(), surface_molecule_moves.end(),
[ ]( const SurfaceMoleculeMoveInfo& lhs, const SurfaceMoleculeMoveInfo& rhs )
{
return lhs.molecule_id < rhs.molecule_id;
}
);
for (const SurfaceMoleculeMoveInfo& move_info: surface_molecule_moves) {
// finally fix positions of the surface molecules (only those that are on walls that change area)
DynVertexUtils::move_surface_molecule_to_closest_wall_point(*this, move_info);
}
// 8) move walls that contain paired molecules
if (move_paired_walls && !paired_molecules.empty()) {
// calls recursively Partition::apply_vertex_moves_per_object(false, ...)
// there should be no colliding walls (not completely sure?)
move_walls_with_paired_molecules(
paired_molecules, walls_with_their_moves,
vertex_moves_due_to_paired_molecules);
}
}
static Vec3 average_vec3(const std::vector<const Vec3*>& moves) {
Vec3 res = 0;
for (const Vec3* vec: moves) {
res = res + *vec;
}
res = res / Vec3(moves.size());
return res;
}
// called from apply_vertex_moves_per_object
void Partition::move_walls_with_paired_molecules(
const MoleculeIdsVector& paired_molecules,
const WallsWithTheirMovesMap& walls_with_their_moves,
std::vector<VertexMoveInfo*>& vertex_moves_due_to_paired_molecules) {
// notation:
// object A:
// - the object whose walls were moved in the call 'apply_vertex_moves_per_object'
// that initiated call of this method
// molecules on A (paired_molecules argument of this method):
// - molecules present on object A
//
// object B:
// - the object whose walls we are going to move now
// there cannot be currently multiple objects moved at the same time due to
// potentially missing some moves if molecules on A would be paired with molecules on objects B and C
// molecules on B:
// - molecules present on object B that are paired with molecules on A
// we are going to move walls of object B that contain molecules on B
// collect which vertices of B will be moved along with molecules on A that initiate their move
map<vertex_index_t, vector<const Vec3*>> vertices_from_B_with_moves;
geometry_object_id_t oid_B = GEOMETRY_OBJECT_ID_INVALID;
bool warning_printed = false;
// assuming that there are usually just a few molecules per wall so we process
// paired molecule from A one by one (just a performance assumption)
for (molecule_id_t mid_A: paired_molecules) {
const Molecule& m_A = get_m(mid_A);
assert(m_A.is_surf());
wall_index_t wi_A = m_A.s.wall_index;
molecule_id_t mid_B = get_paired_molecule(mid_A);
const Molecule& m_B = get_m(mid_B);
assert(m_B.is_surf());
wall_index_t wi_B = m_B.s.wall_index;
const Wall& w_B = get_wall(wi_B);
// check that we are moving with a single object
if (oid_B == GEOMETRY_OBJECT_ID_INVALID) {
oid_B = w_B.object_id;
}
else if (oid_B != w_B.object_id && !warning_printed) {
warns() << "Paired molecules from a single geometry object move with more than one "
"other object. This might result is some missed wall moves.\n";
warning_printed = true;
}
// find all moves for wall from A
auto it_wall_moves_A = walls_with_their_moves.find(wi_A);
if (it_wall_moves_A == walls_with_their_moves.end()) {
// no moves for this wall? should not normally happen
// but otherwise this means that the wall is not moved
assert(false);
continue;
}
// for each vertex of w_B, collect all moves
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
vertex_index_t vi_B = w_B.vertex_indices[i];
vector<const Vec3*>& displacements_B = vertices_from_B_with_moves[vi_B];
for (const VertexMoveInfo* move_B: it_wall_moves_A->second.vertex_moves) {
displacements_B.push_back(&move_B->displacement);
}
}
}
// prepare argument vector<VertexMoveInfo*>& vertex_moves
// by computing average displacement for each vertex of wall that contains a paired molecule
vector<VertexMoveInfo*> vertex_move_infos_B;
for (const auto& pair_vid_moves_B: vertices_from_B_with_moves) {
Vec3 avg_displacement = average_vec3(pair_vid_moves_B.second);
if (cmp_eq(avg_displacement, 0)) {
// no need to move vertex if it is not being moved at all
continue;
}
VertexMoveInfo* move_B = new VertexMoveInfo(
PARTITION_ID_INITIAL, oid_B, pair_vid_moves_B.first, avg_displacement
);
vertex_move_infos_B.push_back(move_B);
}
// call apply_vertex_moves_per_object to move walls in B
// the call must not cause move of paired walls (otherwise we would get infinite recursion)
// there must not be any new wall collisions (warning if they are)
std::set<GeometryObjectWallUnorderedPair> colliding_walls;
vector<VertexMoveInfo*> ignored_moves;
apply_vertex_moves_per_object(
false, vertex_move_infos_B,
colliding_walls, ignored_moves);
assert(ignored_moves.empty());
if (!colliding_walls.empty()) {
warns() << "Unexpected wall collisions detected in move_walls_with_paired_molecules.\n";
}
// remember these vertex_moves so that the Python API can
vertex_moves_due_to_paired_molecules.insert(
vertex_moves_due_to_paired_molecules.end(),
vertex_move_infos_B.begin(),
vertex_move_infos_B.end()
);
}
static Vec3 get_new_vertex_position(
const Vec3& pos, const vertex_index_t vi, const map<vertex_index_t, const Vec3*>& displacements) {
auto it = displacements.find(vi);
if (it == displacements.end()) {
// no displacement for this vertex
return pos;
}
else {
return pos + *(it->second);
}
}
void Partition::clamp_vertex_moves_to_wall_wall_collisions(
std::vector<VertexMoveInfo*>& vertex_moves,
std::set<GeometryObjectWallUnorderedPair>& colliding_walls) {
// this is a first test that checks whether our wall wont simply collide
// if we send a ray from each of the moved vertices
for (VertexMoveInfo* vertex_move_info: vertex_moves) {
assert(vertex_move_info->partition_id == id);
const std::vector<wall_index_t>& wall_indices = get_walls_using_vertex(vertex_move_info->vertex_index);
Vec3& displacement = vertex_move_info->displacement;
// check that object id is consistent
assert(!wall_indices.empty());
assert(get_wall(wall_indices[0]).object_id == vertex_move_info->geometry_object_id);
const Vec3& pos = get_geometry_vertex(vertex_move_info->vertex_index);
map<geometry_object_index_t, uint> num_crossed_walls_per_object_ignored;
bool must_redo_test;
wall_index_t closest_hit_wall_index;
Vec3 dir(
(cmp_eq(displacement.x, (pos_t)0) ? 0 : ((displacement.x > 0) ? 1 : -1)),
(cmp_eq(displacement.y, (pos_t)0) ? 0 : ((displacement.y > 0) ? 1 : -1)),
(cmp_eq(displacement.z, (pos_t)0) ? 0 : ((displacement.z > 0) ? 1 : -1))
);
// extra displacement to make sure that we will end up in front of a wall,
// not on it
Vec3 wall_gap_displacement = dir * Vec3(MIN_WALL_GAP);
// TODO: preferably use some function that does not collect what we hit,
// but we do not have such
stime_t collision_time = CollisionUtils::get_num_crossed_walls_per_object(
*this, pos, pos + displacement + wall_gap_displacement, false,
num_crossed_walls_per_object_ignored, must_redo_test,
vertex_move_info->geometry_object_id,
&closest_hit_wall_index
);
bool ignore_hit = false;
if (must_redo_test) {
mcell_log(
"Internal warning: wall collision redo in clamp_vertex_moves_to_wall_wall_collisions is not handled yet, "
"the vertex move that caused it won't be applied."
);
ignore_hit = true;
collision_time = 0;
displacement = 0;
}
assert(collision_time >= 0.0 && collision_time <= 1.0);
if (collision_time != 1.0) {
if (collision_time < STIME_SQRT_EPS) {
collision_time = 0.0;
}
else {
collision_time -= STIME_SQRT_EPS;
}
// clamp the displacement (it is a reference)
displacement = displacement * Vec3(collision_time);
// decrement by MIN_WALL_GAP because we hit a wall and would like to stay a bit in front of it
displacement = displacement - wall_gap_displacement;
if (!ignore_hit) {
assert(closest_hit_wall_index != WALL_INDEX_INVALID);
// and remember collisions for each of the walls that are moved by this single vertex
const Wall& hit_wall = get_wall(closest_hit_wall_index);
for (wall_index_t wi: wall_indices) {
colliding_walls.insert(
GeometryObjectWallUnorderedPair(
vertex_move_info->geometry_object_id,
wi,
hit_wall.object_id,
hit_wall.index
)
);
}
}
}
}
// construct a map that gives us displacement per vertex
map<vertex_index_t, const Vec3*> displacement_per_moved_vertex;
for (VertexMoveInfo* vertex_move_info: vertex_moves) {
displacement_per_moved_vertex[vertex_move_info->vertex_index] = &vertex_move_info->displacement;
}
// next, we must check all edges used by this vertex - they must not cross a different object
for (VertexMoveInfo* vertex_move_info: vertex_moves) {
GeometryObject& obj = get_geometry_object_by_id(vertex_move_info->geometry_object_id);
// get all vertices that share edge with the moved vertex
const set<vertex_index_t>& connected_vertices = obj.get_connected_vertices(*this, vertex_move_info->vertex_index);
Vec3 start = get_new_vertex_position(
get_geometry_vertex(vertex_move_info->vertex_index),
vertex_move_info->vertex_index,
displacement_per_moved_vertex);
for (vertex_index_t connected_vertex_index: connected_vertices) {
// check if a different object is not crossed
// must ignore current object because of "wall redo" checks
Vec3 end = get_new_vertex_position(
get_geometry_vertex(connected_vertex_index),
connected_vertex_index,
displacement_per_moved_vertex);
map<geometry_object_index_t, uint> num_crossed_walls_per_object;
bool must_redo_test;
wall_index_t closest_hit_wall_index;
stime_t collision_time = CollisionUtils::get_num_crossed_walls_per_object(
*this, start, end, false,
num_crossed_walls_per_object, must_redo_test,
vertex_move_info->geometry_object_id,
&closest_hit_wall_index
);
if (!num_crossed_walls_per_object.empty() || must_redo_test) {
// we hit a wall, this means that the moved triangle is partially inside another object,
// cancel the displacement
vertex_move_info->displacement = 0;
if (!must_redo_test) {
// remember that there was a wall collision, redos are infrequent and can be ignored
// which wall of the moved object collided?
wall_index_t wi = obj.get_wall_for_vertex_pair(
*this, vertex_move_info->vertex_index, connected_vertex_index);
assert(wi != WALL_INDEX_INVALID);
// choose the first colliding wall from the hit object
const Wall& hit_wall = get_wall(closest_hit_wall_index);
colliding_walls.insert(
GeometryObjectWallUnorderedPair(
vertex_move_info->geometry_object_id,
wi,
hit_wall.object_id,
hit_wall.index
)
);
}
break;
}
}
}
}
void Partition::dump(const bool with_geometry) {
if (with_geometry) {
GeometryObject::dump_array(*this, geometry_objects);
}
Region::dump_array(regions);
#ifndef NDEBUG
if (with_geometry) {
for (size_t i = 0; i < walls_per_subpart.size(); i++) {
if (!walls_per_subpart[i].empty()) {
Vec3 llf, urb;
get_subpart_llf_point(i, llf);
urb = llf + Vec3(config.subpart_edge_length);
cout << "subpart: " << i << ", llf: " << llf << ", urb: " << urb << "\n ";
for (wall_index_t wi: walls_per_subpart[i]) {
cout << wi << ", ";
}
cout << "\n";
}
}
}
#endif
}
// methods get_num_crossed_region_walls and get_num_crossed_walls_per_object
// may fail with WALL_REDO, this means that a point is on a wall and
// therefore it cannot be safely determined where it belongs
// waypoints are used as an optimization so we can place them anywhere we like
void Partition::move_waypoint_because_positioned_on_wall(
const IVec3& waypoint_index, const bool reinitialize) {
Waypoint& waypoint = get_waypoint(waypoint_index);
// rng_dbl when used in Vec3 ctor causes compiler to print warnings
// that a constant is subtracted from uint
double r1 = rng_dbl(&aux_rng);
double r2 = rng_dbl(&aux_rng);
double r3 = rng_dbl(&aux_rng);
Vec3 random_displacement = Vec3(POS_SQRT_EPS * r1, POS_SQRT_EPS * r2, POS_SQRT_EPS * r3);
waypoint.pos = waypoint.pos + random_displacement;
if (reinitialize) {
initialize_waypoint(waypoint_index, false, IVec3(0), true);
}
}
// keep_pos is false by default, when true, the waypoint position is reused and
// this function only updates the counted_volume_index for the new position
void Partition::initialize_waypoint(
const IVec3& waypoint_index,
const bool use_previous_waypoint,
const IVec3& previous_waypoint_index,
const bool keep_pos
) {
// array was allocated
Waypoint& waypoint = get_waypoint(waypoint_index);
if (!keep_pos) {
waypoint.pos =
origin_corner +
Vec3(config.subpart_edge_length) * Vec3(waypoint_index) + // llf of a subpart
Vec3(config.subpart_edge_length / 2)
;
}
// make sure that the waypoint is not on any wall, this is required for correct function
// of regions as well
pos_t dist2;
do {
wall_index_t wall_index_ignored;
Vec2 wall_pos2d_ignored;
dist2 = WallUtils::find_closest_wall_any_object(
*this, waypoint.pos, POS_SQRT_EPS, false, wall_index_ignored, wall_pos2d_ignored);
if (dist2 < POS_EPS) {
move_waypoint_because_positioned_on_wall(waypoint_index, false);
}
} while (dist2 < POS_EPS);
// another required check is that there must not be an edge between the current and
// previous waypoint, this is required for initialization of regions
if (use_previous_waypoint) {
bool redo;
int num_attempts = 0;
Vec3& previous_waypoint_pos = get_waypoint(previous_waypoint_index).pos;
do {
map<geometry_object_index_t, uint> num_crossed_walls_per_object;
CollisionUtils::get_num_crossed_walls_per_object(
*this, waypoint.pos, previous_waypoint_pos, false, // all walls
num_crossed_walls_per_object, redo
);
if (redo) {
move_waypoint_because_positioned_on_wall(waypoint_index, false);
if (num_attempts >= 5) {
// give up because we are getting redos due to the previous waypoint,
// count from scratch
break;
}
num_attempts++;
}
} while (redo);
}
// it makes sense to compute counted_volume_index if there are any
// counted objects
if (config.has_intersecting_counted_objects) {
// see if we can reuse the previous waypoint to accelerate computation
if (use_previous_waypoint) {
Waypoint& previous_waypoint = get_waypoint(previous_waypoint_index);
map<geometry_object_index_t, uint> num_crossed_walls_per_object;
bool must_redo_test = false;
CollisionUtils::get_num_crossed_walls_per_object(
*this, waypoint.pos, previous_waypoint.pos, true, // only counted objects
num_crossed_walls_per_object, must_redo_test
);
if (must_redo_test) {
// updates values referenced by waypoint
// the redo can be also due to the previous waypoint, so we
// will check whether the waypoint is contained without the previous waypoint
// do not call reinitialize to avoid recursion
move_waypoint_because_positioned_on_wall(waypoint_index, false);
}
// ok, test passed safely
else if (num_crossed_walls_per_object.empty()) {
// ok, we can simply copy counted volume from the previous waypoint
waypoint.counted_volume_index = previous_waypoint.counted_volume_index;
return;
}
}
// figure out in which counted volumes is this waypoint present
waypoint.counted_volume_index = compute_counted_volume_from_scratch(waypoint.pos);
}
else {
waypoint.counted_volume_index = COUNTED_VOLUME_INDEX_OUTSIDE_ALL;
}
}
void Partition::initialize_all_waypoints() {
// we need waypoints to be initialized all the time because they
// are used not just when dealing with counted volumes, but also
// by regions when detecting whether a point is inside
// each center of a subpartition has a waypoint
uint num_waypoints_per_dimension = config.num_subparts_per_partition_edge;
mcell_log("Initializing %d waypoints... ", powu(num_waypoints_per_dimension, 3));
bool use_previous_waypoint = false;
IVec3 previous_waypoint_index;
waypoints.resize(num_waypoints_per_dimension);
for (uint x = 0; x < num_waypoints_per_dimension; x++) {
waypoints[x].resize(num_waypoints_per_dimension);
for (uint y = 0; y < num_waypoints_per_dimension; y++) {
waypoints[x][y].resize(num_waypoints_per_dimension);
for (uint z = 0; z < num_waypoints_per_dimension; z++) {
initialize_waypoint(IVec3(x, y, z), use_previous_waypoint, previous_waypoint_index);
use_previous_waypoint = true;
previous_waypoint_index = IVec3(x, y, z);
}
// starting a new line - start from scratch
use_previous_waypoint = false;
}
}
}
// method is in .cpp file because it uses inlined implementation
counted_volume_index_t Partition::compute_counted_volume_from_scratch(const Vec3& pos) {
return CollisionUtils::compute_counted_volume_for_pos(*this, pos);
}
counted_volume_index_t Partition::compute_counted_volume_using_waypoints(const Vec3& pos) {
return CollisionUtils::compute_counted_volume_using_waypoints(*this, pos);
}
counted_volume_index_t Partition::find_or_add_counted_volume(const CountedVolume& cv) {
assert(counted_volumes_vector.size() == counted_volumes_set.size());
auto it = counted_volumes_set.find(cv);
if (it != counted_volumes_set.end()) {
return it->index;
}
else {
// we must add this new item
CountedVolume cv_copy = cv;
cv_copy.index = counted_volumes_set.size();
counted_volumes_set.insert(cv_copy);
counted_volumes_vector.push_back(cv_copy);
return cv_copy.index;
}
}
// returns compartment ID, all compartments are represented by a counted volume
// so we can use the counted volume information to determine it
BNG::compartment_id_t Partition::get_compartment_id_for_counted_volume(const counted_volume_index_t counted_volume_index) {
// caching, the mapping object->compartment is static and does not change even with dynamic geometry
auto it = counted_volume_index_to_compartment_id_cache.find(counted_volume_index);
if (it != counted_volume_index_to_compartment_id_cache.end()) {
return it->second;
}
const CountedVolume& cv = get_counted_volume(counted_volume_index);
// first collect all compartments we are in
set<BNG::compartment_id_t> inside_of_compartments;
for (geometry_object_index_t obj_index: cv.contained_in_objects) {
const GeometryObject& obj = get_geometry_object(obj_index);
if (obj.represents_compartment()) {
inside_of_compartments.insert(obj.vol_compartment_id);
}
}
if (inside_of_compartments.empty()) {
// we are outside of any defined compartment
counted_volume_index_to_compartment_id_cache[counted_volume_index] = BNG::COMPARTMENT_ID_NONE;
return BNG::COMPARTMENT_ID_NONE;
}
if (inside_of_compartments.size() == 1) {
// there is just one compartment
BNG::compartment_id_t res = *inside_of_compartments.begin();
counted_volume_index_to_compartment_id_cache[counted_volume_index] = res;
return res;
}
// find the lowest level child because volume compartments are always hierarchical
// and if we are inside of objects that correspond to EC and CP, it means that we are in CP
BNG::compartment_id_t current = *inside_of_compartments.begin();
bool child_found;
do {
const BNG::Compartment& comp = bng_engine.get_data().get_compartment(current);
assert(comp.is_3d);
// which child are we possibly in?
child_found = false;
for (BNG::compartment_id_t child: comp.children_compartments) {
const BNG::Compartment& child_comp = bng_engine.get_data().get_compartment(child);
if (!child_comp.is_3d) {
// go through children of the 2d compartment (should be just one usually)
for (BNG::compartment_id_t child3d: child_comp.children_compartments) {
if (inside_of_compartments.count(child3d) == 1) {
child_found = true;
current = child3d;
break;
}
}
}
else {
if (inside_of_compartments.count(child) == 1) {
child_found = true;
current = child;
break;
}
}
}
} while (child_found);
counted_volume_index_to_compartment_id_cache[counted_volume_index] = current;
return current;
}
void Partition::remove_from_known_vol_species(const species_id_t species_id) {
if (known_vol_species.count(species_id) == 0) {
return;
}
known_vol_species.erase(species_id);
}
void Partition::remove_reactant_class_usage(const BNG::reactant_class_id_t reactant_class_id) {
volume_molecule_reactants_per_reactant_class.remove_reactant_sets_for_reactant_class(reactant_class_id);
}
void Partition::shuffle_schedulable_molecule_ids() {
size_t n = schedulable_molecule_ids.size();
if (n == 0) {
return;
}
release_assert(n < (size_t)UINT32_MAX);
for (molecule_index_t i = n-1; i > 0; --i) {
double rand = rng_dbl(&aux_rng);
release_assert(rand >= 0 && rand <= 1);
// scale rand to 0..n-1
uint rand_index = (double)(n-1) * rand;
assert(rand_index < n);
molecule_id_t tmp = schedulable_molecule_ids[i];
schedulable_molecule_ids[i] = schedulable_molecule_ids[rand_index];
schedulable_molecule_ids[rand_index] = tmp;
}
}
static std::string check_is_valid_surface_molecule(const Partition& p, const molecule_id_t id, const char* name) {
if (id == MOLECULE_ID_INVALID || id >= p.get_molecule_id_to_index_mapping().size()) {
return string("Molecule with id '") + name + "' is invalid.";
}
const Molecule& m = p.get_m(id);
if (!m.is_surf()) {
return string("Molecule with id '") + name + "' (" + to_string(id) + ") is not a surface molecule.";
}
return "";
}
std::string Partition::pair_molecules(const molecule_id_t id1, const molecule_id_t id2) {
string res;
res = check_is_valid_surface_molecule(*this, id1, "id1");
if (res != "") { return res; }
res = check_is_valid_surface_molecule(*this, id2, "id2");
if (res != "") { return res; }
const Molecule& m1 = get_m(id1);
const Molecule& m2 = get_m(id2);
const Wall& w1 = get_wall(m1.s.wall_index);
const Wall& w2 = get_wall(m2.s.wall_index);
if (w1.object_id == w2.object_id) {
return "Molecules must be present on surfaces of different objects.";
}
if (get_paired_molecule(id1) != MOLECULE_ID_INVALID) {
return "Molecule with id 'id1' (" + to_string(id1) + ") is already paired.";
}
if (get_paired_molecule(id2) != MOLECULE_ID_INVALID) {
return "Molecule with id 'id2' (" + to_string(id2) + ") is already paired.";
}
// pair
paired_molecules[id1] = id2;
paired_molecules[id2] = id1;
return "";
}
std::string Partition::unpair_molecules(const molecule_id_t id1, const molecule_id_t id2) {
string res;
res = check_is_valid_surface_molecule(*this, id1, "id1");
if (res != "") { return res; }
res = check_is_valid_surface_molecule(*this, id2, "id2");
if (res != "") { return res; }
molecule_id_t pair1 = get_paired_molecule(id1);
if (pair1 == MOLECULE_ID_INVALID) {
return "Molecule with id 'id1' (" + to_string(id1) + ") is not paired.";
}
molecule_id_t pair2 = get_paired_molecule(id2);
if (pair2 == MOLECULE_ID_INVALID) {
return "Molecule with id 'id2' (" + to_string(id2) + ") is not paired.";
}
if (pair1 != id2) {
return "Molecules are not paired to each other.";
}
assert(pair2 == id1);
paired_molecules.erase(id1);
paired_molecules.erase(id2);
return "";
}
molecule_id_t Partition::get_paired_molecule(const molecule_id_t id) const {
auto it = paired_molecules.find(id);
if (it == paired_molecules.end()) {
return MOLECULE_ID_INVALID;
}
else {
return it->second;
}
}
void Partition::to_data_model(Json::Value& mcell, std::set<rgba_t>& used_colors) const {
// there are two places in data model where geometry objects are
// defined - in KEY_GEOMETRICAL_OBJECTS and KEY_MODEL_OBJECTS
Json::Value& geometrical_objects = mcell[KEY_GEOMETRICAL_OBJECTS];
Json::Value& object_list = geometrical_objects[KEY_OBJECT_LIST];
if (object_list.isNull()) {
object_list = Json::Value(Json::arrayValue);
}
for (const GeometryObject& g: geometry_objects) {
Json::Value object;
g.to_data_model_as_geometrical_object(*this, config, object, used_colors);
object_list.append(object);
}
Json::Value& model_objects = mcell[KEY_MODEL_OBJECTS];
DMUtils::add_version(model_objects, VER_DM_2018_01_11_1330);
Json::Value& model_object_list = model_objects[KEY_MODEL_OBJECT_LIST];
model_object_list = Json::Value(Json::arrayValue);
for (const GeometryObject& g: geometry_objects) {
Json::Value model_object;
g.to_data_model_as_model_object(*this, model_object);
model_object_list.append(model_object);
}
// mod_surf_regions
Json::Value& modify_surface_regions = mcell[KEY_MODIFY_SURFACE_REGIONS];
DMUtils::add_version(modify_surface_regions, VER_DM_2014_10_24_1638);
Json::Value& modify_surface_regions_list = modify_surface_regions[KEY_MODIFY_SURFACE_REGIONS_LIST];
modify_surface_regions_list = Json::Value(Json::arrayValue);
for (const Region& reg: regions) {
if (reg.is_reactive() || reg.has_initial_molecules()) {
Json::Value modify_surface_region;
reg.to_data_model(*this, modify_surface_region);
modify_surface_regions_list.append(modify_surface_region);
}
}
}
void Partition::print_periodic_stats() const {
std::cout <<
"Partition: molecules.size() = " << molecules.size() << "\n" <<
"Partition: molecule_id_to_index_mapping.size() = " << molecule_id_to_index_mapping.size() << "\n" <<
"Partition: next_molecule_id = " << next_molecule_id << "\n" <<
"Partition: known_vol_species.size() = " << known_vol_species.size() << "\n";
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/base_event.h | .h | 5,533 | 144 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_BASE_EVENT_H_
#define SRC4_BASE_EVENT_H_
#include "defines.h"
namespace Json {
class Value;
}
namespace MCell {
class World;
typedef int event_type_index_t;
// Value specifies ordering when two events are scheduled for exactly the same time
// The 'holes' are there on purpose for ordering of external events
const event_type_index_t EVENT_TYPE_INDEX_INVALID = -1;
// must be the very first event in an iteration
const event_type_index_t EVENT_TYPE_INDEX_CALL_START_ITERATION_CHECKPOINT = 0;
const event_type_index_t EVENT_TYPE_INDEX_RELEASE = 200;
// first counting and visualization output is done after release
const event_type_index_t EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT = 290;
// viz_output is special in the way that simulation is terminated herein the last iteration
const event_type_index_t EVENT_TYPE_INDEX_VIZ_OUTPUT = 300;
// simulation end check event is scheduled for each iteration,
// this allows us to safely terminate after all observables were collected
// (counts and viz output must be before diffuse&react for MCell3 compatibility)
const event_type_index_t EVENT_TYPE_INDEX_SIMULATION_END_CHECK = 301;
const event_type_index_t EVENT_TYPE_INDEX_RXN_CLASS_CLEANUP = 400;
const event_type_index_t EVENT_TYPE_INDEX_SPECIES_CLEANUP = 410;
const event_type_index_t EVENT_TYPE_INDEX_SORT_MOLS_BY_SUBPART = 420;
const event_type_index_t EVENT_TYPE_INDEX_CLAMP_RELEASE = 490;
const event_type_index_t EVENT_TYPE_INDEX_DIFFUSE_REACT = 500; // this event spans the whole time step
const event_type_index_t EVENT_TYPE_INDEX_DEFRAGMENTATION = 900;
const event_type_index_t EVENT_TYPE_INDEX_MOL_SHUFFLE = 910;
const event_type_index_t EVENT_TYPE_INDEX_BARRIER = 980;
const event_type_index_t EVENT_TYPE_INDEX_CALL_END_ITERATION = 990;
/**
* Base class for all events.
* Should be independent on the mcell world in order to
* integrate also other simulators.
*/
class BaseEvent {
public:
BaseEvent(const event_type_index_t t) :
event_time(TIME_INVALID), periodicity_interval(0), type_index(t) {
}
virtual ~BaseEvent() {};
virtual void step() = 0;
virtual void dump(const std::string ind = "") const;
virtual void to_data_model(Json::Value& mcell_node) const;
// some events such as release events have their event time set for
// the beginning of a timestep but internally they need to be ordered
// also according to another value such as actual release time
virtual bool needs_secondary_ordering() { return false; }
virtual double get_secondary_ordering_value() { return 0; }
// if this event should be rescheduled, updates event_time and
// possibly other attributes,
// returns true if even should be rescheduled, false if event
// should be removed from the schedule
virtual bool update_event_time_for_next_scheduled_time() {
// handling the simple case when periodicity_interval is 0 or not
if (periodicity_interval == 0) {
return false;
}
else {
event_time = event_time + periodicity_interval;
return true;
}
}
// - events such as VizOutput, Count, or Release are barriers
// to events whose execution spans over a certain time step
// such as DiffuseReactEvent
// - is_blocked_by_barrier_and_needs_set_time_step must return false
// when is_barrier returns true
virtual bool is_barrier() const { return false; }
// - some events represent simulation over a time step such as
// DiffuseReactEvent, the maximum timestep for such events
// must be limited so that the barrier event (such as molecule count)
// has data valid for its time
// - is_barrier must return false
// when is_blocked_by_barrier_and_needs_set_time_step returns true
// - periodicity_interval must not be 0 when this function return true
virtual bool may_be_blocked_by_barrier_and_needs_set_time_step() const { return false; }
// maximum search time for a barrier, i.e. we do not care whether
// there is a barrier after the time interval returned by this method
virtual double get_max_time_up_to_next_barrier() const {
// the subclass must return true in may_be_blocked_by_barrier_and_needs_set_time_step
assert(false && "Only overridden variant of this method may be called.");
return 0;
}
// if an event is blocked
virtual void set_barrier_time_for_next_execution(const double time_step) {
// the subclass must return true in may_be_blocked_by_barrier_and_needs_set_time_step
assert(false && "Only overridden variant of this method may be called.");
}
// used by checkpointing
virtual bool return_from_run_n_iterations_after_execution() const {
return false;
}
// time when this object's step() method will be called
double event_time;
// once this event is executed, schedule next one after this interval
// do not schedule if the value is 0
double periodicity_interval;
// this value specifies both id of the event and ordering when multiple
// events of a different type are sheduled for the same time
event_type_index_t type_index;
};
}
#endif // SRC4_BASE_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/custom_function_call_event.h | .h | 2,166 | 73 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_CUSTOM_FUNCTION_CALL_EVENT_H_
#define SRC4_CUSTOM_FUNCTION_CALL_EVENT_H_
#include "base_event.h"
namespace MCell {
/**
* General event that allows to call a function periodically.
* Used for example to check that the user pressed ctrl-c
* when running inside the Python interpreter.
* Always executed at the end of an iteration.
*
* Made a template to hold its context as function_arg and
* to be able to destroy it afterwards.
*/
template<typename T>
class CustomFunctionCallEvent: public BaseEvent {
public:
typedef void (*CalledFunctionType)(double, T);
CustomFunctionCallEvent(
CalledFunctionType function_ptr_,
const T& function_arg_, // makes a shallow copy
const event_type_index_t event_type_index_ = EVENT_TYPE_INDEX_CALL_END_ITERATION
)
: BaseEvent(event_type_index_),
function_ptr(function_ptr_),
function_arg(function_arg_),
return_from_run_n_iterations(false){
}
// pointer to a function to be periodically called
// first argument is event time, second is
CalledFunctionType function_ptr;
T function_arg;
bool return_from_run_n_iterations;
void step() override {
assert(function_ptr != nullptr);
function_ptr(event_time, function_arg);
}
virtual bool return_from_run_n_iterations_after_execution() const {
return return_from_run_n_iterations;
}
void dump(const std::string ind) const override {
std::cout << ind << "Periodic Call Event:\n";
std::string ind2 = ind + " ";
BaseEvent::dump(ind2);
std::cout << ind2 << "function_ptr:\t\t" << std::hex << (void*)function_ptr << std::dec << "\n";
}
};
} // namespace mcell
#endif // SRC4_CUSTOM_FUNCTION_CALL_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/grid_position.cpp | .cpp | 27,801 | 810 | /******************************************************************************
*
* Copyright (C) 2006-2017,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "grid_position.h"
#include "geometry.h"
#include "logging.h"
#include "geometry_utils.inl"
#include "grid_utils.inl"
namespace MCell {
namespace GridPosition {
using GeometryUtils::xyz2uv;
using GeometryUtils::uv2xyz;
/*************************************************************************
get_tile_vertices:
In: surface grid
tile index
tile flip information (return value)
first tile vertex R (return value)
second tile vertex S (return value)
third tile vertex T (return value)
Out: the tile vertices (R,S,T) coordinates are defined
Note: the vertices (R,S,T) are listed clockwise. For the upright tile
(orientation similar to the wall) two vertices R and S are
on the same line PQ parallel and closest to the u-axis.
For the inverted tile (orientation inverted compared to the wall)
two vertices S and T are on the same line XY parallel and furthest
to the u-axis.
*************************************************************************/
static void get_tile_vertices(
const Partition& p, const Grid& sg, const tile_index_t idx,
int& flp,
Vec2& R, Vec2& S, Vec2& T) {
/* indices of the barycentric subdivision */
int strip, stripe, flip;
int root, rootrem;
Vec2 P, Q, X, Y;
/* length of the segments PQ and XY (see below) */
pos_t pq, xy;
/* cotangent of the angle formed between the u-axis
and the wall edge opposite to the origin of the
uv-coordinate system */
pos_t cot_angle;
/* Calculate strip, stripe, and flip indices from idx */
root = (int)sqrt_p(idx);
rootrem = idx - root * root;
strip = sg.num_tiles_along_axis - root - 1;
stripe = rootrem / 2;
flip = rootrem - 2 * stripe;
/* Let PQ to be the segment on the grid containing the vertex R
and the one closest to the u-axis. Let XY to be the segment
containing the vertex T and the one furthest to the u-axis.
Let point P to be on the left side of point Q.
Let point X to be on the left side of point Y.
*/
/* find v-coordinates of P, Q, X, Y */
P.v = Q.v = strip / sg.strip_width_rcp;
X.v = Y.v = (strip + 1) / sg.strip_width_rcp;
/* find u-coordinates of P, Q, X, Y */
P.u = (P.v) * (sg.vert2_slope);
X.u = (X.v) * (sg.vert2_slope);
const Wall& surface = p.get_wall(sg.wall_index);
cot_angle = (surface.uv_vert1_u - surface.uv_vert2.u) /
(surface.uv_vert2.v);
Q.u = surface.uv_vert1_u - (Q.v) * cot_angle;
Y.u = surface.uv_vert1_u - (Y.v) * cot_angle;
pq = Q.u - P.u;
if (idx == 0) {
xy = 0;
} else {
xy = Y.u - X.u;
}
/* find coordinates of the tile vertices */
/* For the upright tile the vertices R and S lie on
the line PQ and vertex T - on the line XY.
For the inverted tile only the vertex R lies on the line PQ
while the vertices S and T lie on the line XY */
if (flip == 1) {
/* inverted tile */
R.v = P.v;
/* note: pq/(sg.num_tiles_along_axis - strip) tells us
the number of slots on the line PQ */
R.u = P.u + pq * (stripe + 1) / (sg.num_tiles_along_axis - strip);
S.v = T.v = X.v;
T.u = X.u + xy * stripe / (sg.num_tiles_along_axis - strip - 1);
S.u = X.u + xy * (stripe + 1) / (sg.num_tiles_along_axis - strip - 1);
} else {
/* upright tile */
R.v = S.v = P.v;
T.v = X.v;
/* note: pq/(sg.num_tiles_along_axis - strip) tells us
the number of slots on the line PQ */
R.u = P.u + pq * stripe / (sg.num_tiles_along_axis - strip);
S.u = P.u + pq * (stripe + 1) / (sg.num_tiles_along_axis - strip);
if (idx == 0) {
T.u = X.u;
} else {
T.u = X.u + xy * stripe / (sg.num_tiles_along_axis - strip - 1);
}
}
/* set the tile flip value */
flp = flip;
}
/****************************************************************************
find_wall_vertex_for_corner_tile:
In: surface grid
tile index on the grid
Out: corner tile should share one of it's vertices with the wall.
Returns the shared wall vertex id (index in the array wall_vert[])
****************************************************************************/
int find_wall_vertex_for_corner_tile(const Grid& grid, const tile_index_t idx) {
/* index of the wall vertex that is shared with the tile vertex */
int vertex_id = 0;
if (!GridUtils::is_corner_tile(grid, idx))
mcell_internal_error("Function 'find_wall_vertex_for_corner_tile()' is "
"called for the tile that is not the corner tile.");
if ((u_int)idx == (grid.num_tiles - 2 * (grid.num_tiles_along_axis) + 1)) {
vertex_id = 0;
}
else if ((u_int)idx == (grid.num_tiles - 1)) {
vertex_id = 1;
}
else if (idx == 0) {
vertex_id = 2;
}
else {
mcell_internal_error("Function 'find_wall_vertex_for_corner_tile()' is "
"called for the tile that is not the corner tile.");
}
return vertex_id;
}
/*****************************************************************************
get_product_shared_segment_pos:
In: segment defined by points R_shared and S_shared
point T
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between T
and midpont on (R_shared, S_shared) in the ratio k1:k2, so that
midpoint_prod/midpoint_T = k1/k2
Note: all points are on the plane
******************************************************************************/
static Vec2 get_product_shared_segment_pos(
const Vec2& R_shared, const Vec2& S_shared, const Vec2& T, pos_t k1, pos_t k2) {
Vec2 M; /* midpoint */
/* find midpoint on the segment (R_shared - S_shared) */
M.u = 0.5 * (R_shared.u + S_shared.u);
M.v = 0.5 * (R_shared.v + S_shared.v);
/* find coordinates of the point such that internally
divides the segment TM in the ratio (k1:k2)
We want to place the product close to the common edge.
*/
return Vec2(
(k1 * T.u + k2 * M.u) / (k1 + k2),
(k1 * T.v + k2 * M.v) / (k1 + k2));
}
/*****************************************************************************
get_product_shared_vertex_pos:
In: point R_shared
segment defined by points S and T
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between R_shared
and midpont on (S, T) in the ratio k1:k2, so that
R_shared_prod/prod_midpoint = k1/k2
Note: all points are on the plane
******************************************************************************/
static Vec2 get_product_shared_vertex_pos(
const Vec2& R_shared, const Vec2& S, const Vec2& T, const pos_t k1, const pos_t k2) {
struct vector2 M; /* midpoint */
/* find midpoint on the segment ST */
M.u = (pos_t)0.5 * (S.u + T.u);
M.v = (pos_t)0.5 * (S.v + T.v);
/* find coordinates of the point such that internally
divides the segment RM in the ratio (k1:k2)
*/
return Vec2(
(k1 * M.u + k2 * R_shared.u) / (k1 + k2),
(k1 * M.v + k2 * R_shared.v) / (k1 + k2));
}
/*****************************************************************************
get_product_close_to_segment_endpoint_pos:
In: segment defined by points S (start) and E (end)
position of the product (return value)
ratios k1 and k2
Out: coordinates of the point "prod" dividing the distance between S and E
in the ratio k1:k2, so that E_prod/S_prod = k1/k2
Note: all points are on the plane
******************************************************************************/
static Vec2 get_product_close_to_segment_endpoint_pos(
const Vec2& S, const Vec2& E, const pos_t k1, const pos_t k2) {
return Vec2(
(k1 * S.u + k2 * E.u) / (k1 + k2),
(k1 * S.v + k2 * E.v) / (k1 + k2));
}
/*****************************************************************************
intersect_point_segment:
In: point P and segment AB
Out: 1 if the point P lies on the segment AB, and 0 - otherwise
******************************************************************************/
static bool intersect_point_segment(
const Vec3& P, const Vec3& A, const Vec3& B) {
Vec3 ba, pa;
pos_t t; /* parameter in the line parametrical equation */
pos_t ba_length, pa_length; /* length of the vectors */
pos_t cosine_angle; /* cosine of the angle between ba and pa */
/* check for the end points */
if (!distinguishable_vec3(P, A, POS_EPS)) {
return true;
}
if (!distinguishable_vec3(P, B, POS_EPS)) {
return true;
}
ba = B - A;
pa = P - A;
ba_length = len3(ba);
pa_length = len3(pa);
/* if point intersects segment, vectors pa and ba should be collinear */
cosine_angle = dot(ba, pa) / (ba_length * pa_length);
if (distinguishable_p(cosine_angle, 1, POS_EPS)) {
return false;
}
/* Project P on AB, computing parameterized position d(t) = A + t(B - A) */
t = dot(pa, ba) / dot(ba, ba);
if ((t > 0) && (t < 1)) {
return true;
}
return false;
}
/****************************************************************************
parallel_segments:
In: segment defined by endpoints A, B
segment defined by endpoints R, S
Out: 1, if the segments are parallel.
0, otherwise
*****************************************************************************/
bool parallel_segments(
const Vec3& A, const Vec3& B,
const Vec3& R, const Vec3& S) {
double length;
Vec3 prod; /* cross product */
Vec3 ba, rs;
ba = B - A;
rs = R - S;
prod = cross(ba, rs);
length = len3(prod);
if (!distinguishable_p(length, 0, POS_EPS)) {
return true;
}
else {
return false;
}
}
/************************************************************************
find_closest_position:
In: surface grid of the first tile
first tile index
surface grid of the second tile
second (neighbor) tile index
Out: position of the product on the first tile that is closest
to the second tile. If the neighbor tiles have common edge
this position happens to be very close to the center of the
common edge but inward the first tile. If the neighbor tiles
have common vertex, this position happens to be very close to
to the vertex but inward the first tile.
*************************************************************************/
// TODO: this function needs refactor
Vec2 find_closest_position(const Partition& p, const GridPos& gp1, const GridPos& gp2) {
assert(gp1.is_assigned());
assert(gp2.is_assigned());
assert(!gp1.has_same_wall_and_grid(gp2));
/* vertices of the first tile */
Vec2 R, S, T;
Vec3 R_3d, S_3d, T_3d;
/* vertices of the second tile */
Vec2 A, B, C;
Vec3 A_3d, B_3d, C_3d;
/* vertices A,B,C in the coordinate system RST */
Vec2 A_new, B_new, C_new;
/* the ratios in which we divide the segment */
pos_t k1 = 1e-10; /* this is our good faith assumption */
pos_t k2 = 1;
int flip1; /* flip information about first tile */
int flip2; /* flip information about second tile */
int num_exact_shared_vertices = 0;
/* flags */
int R_shared = 0, S_shared = 0, T_shared = 0;
int A_shared = 0, B_shared = 0, C_shared = 0;
/* find out the vertices of the first tile where we will put the product */
const Wall& wall1 = p.get_wall(gp1.wall_index);
const Vec3& wall1_vert0 = p.get_wall_vertex(wall1, 0);
const Grid& grid1 = wall1.grid;
tile_index_t idx1 = gp1.tile_index;
get_tile_vertices(p, grid1, idx1, flip1, R, S, T);
/* the code below tries to increase accuracy for the corner tiles */
if (GridUtils::is_corner_tile(grid1, idx1)) {
/* find out the shared vertex */
int shared_wall_vertex_id_1 = find_wall_vertex_for_corner_tile(grid1, idx1);
/* note that vertices R, S, T followed clockwise rule */
if (idx1 == 0) {
T_3d = p.get_wall_vertex(wall1, shared_wall_vertex_id_1);
R_3d = uv2xyz(R, wall1, wall1_vert0);
S_3d = uv2xyz(S, wall1, wall1_vert0);
}
else if (idx1 == (grid1.num_tiles - 2 * (grid1.num_tiles_along_axis) + 1)) {
R_3d = p.get_wall_vertex(wall1, shared_wall_vertex_id_1);
S_3d = uv2xyz(S, wall1, wall1_vert0);
T_3d = uv2xyz(T, wall1, wall1_vert0);
}
else {
S_3d = p.get_wall_vertex(wall1, shared_wall_vertex_id_1);
R_3d = uv2xyz(R, wall1, wall1_vert0);
T_3d = uv2xyz(T, wall1, wall1_vert0);
}
}
else {
R_3d = uv2xyz(R, wall1, wall1_vert0);
S_3d = uv2xyz(S, wall1, wall1_vert0);
T_3d = uv2xyz(T, wall1, wall1_vert0);
}
const Wall& wall2 = p.get_wall(gp2.wall_index);
const Vec3& wall2_vert0 = p.get_wall_vertex(wall2, 0);
const Grid& grid2 = wall2.grid;
tile_index_t idx2 = gp2.tile_index;
get_tile_vertices(p, grid2, idx2, flip1, A, B, C);
/* the code below tries to increase accuracy for the corner tiles */
// TODO: make a function out of this, same code as above
if (GridUtils::is_corner_tile(grid2, idx2)) {
/* find out the shared vertex */
int shared_wall_vertex_id_1 = find_wall_vertex_for_corner_tile(grid2, idx2);
/* note that vertices A, B, C followed clockwise rule */
if (idx2 == 0) {
C_3d = p.get_wall_vertex(wall2, shared_wall_vertex_id_1);
A_3d = uv2xyz(A, wall2, wall2_vert0);
B_3d = uv2xyz(B, wall2, wall2_vert0);
}
else if (idx2 == (grid2.num_tiles - 2 * (grid2.num_tiles_along_axis) + 1)) {
A_3d = p.get_wall_vertex(wall2, shared_wall_vertex_id_1);
B_3d = uv2xyz(B, wall2, wall2_vert0);
C_3d = uv2xyz(C, wall2, wall2_vert0);
}
else {
B_3d = p.get_wall_vertex(wall2, shared_wall_vertex_id_1);
A_3d = uv2xyz(A, wall2, wall2_vert0);
C_3d = uv2xyz(C, wall2, wall2_vert0);
}
}
else {
A_3d = uv2xyz(A, wall2, wall2_vert0);
B_3d = uv2xyz(B, wall2, wall2_vert0);
C_3d = uv2xyz(C, wall2, wall2_vert0);
}
/* find shared vertices */
if (gp1.wall_index == gp2.wall_index) {
if (!distinguishable_vec2(R, A, POS_EPS) ||
(!distinguishable_vec2(R, B, POS_EPS)) ||
(!distinguishable_vec2(R, C, POS_EPS))) {
num_exact_shared_vertices++;
R_shared = 1;
}
if (!distinguishable_vec2(S, A, POS_EPS) ||
(!distinguishable_vec2(S, B, POS_EPS)) ||
(!distinguishable_vec2(S, C, POS_EPS))) {
num_exact_shared_vertices++;
S_shared = 1;
}
if (!distinguishable_vec2(T, A, POS_EPS) ||
(!distinguishable_vec2(T, B, POS_EPS)) ||
(!distinguishable_vec2(T, C, POS_EPS))) {
num_exact_shared_vertices++;
T_shared = 1;
}
} else {
/* below there are cases when the grid structures on the neighbor
walls are not shifted relative to one another */
if (!distinguishable_vec3(R_3d, A_3d, POS_EPS) ||
(!distinguishable_vec3(R_3d, B_3d, POS_EPS)) ||
(!distinguishable_vec3(R_3d, C_3d, POS_EPS))) {
num_exact_shared_vertices++;
R_shared = 1;
}
if (!distinguishable_vec3(S_3d, A_3d, POS_EPS) ||
(!distinguishable_vec3(S_3d, B_3d, POS_EPS)) ||
(!distinguishable_vec3(S_3d, C_3d, POS_EPS))) {
num_exact_shared_vertices++;
S_shared = 1;
}
if (!distinguishable_vec3(T_3d, A_3d, POS_EPS) ||
(!distinguishable_vec3(T_3d, B_3d, POS_EPS)) ||
(!distinguishable_vec3(T_3d, C_3d, POS_EPS))) {
num_exact_shared_vertices++;
T_shared = 1;
}
}
if (num_exact_shared_vertices == 1) {
if (R_shared) {
return get_product_shared_vertex_pos(R, S, T, k1, k2);
}
else if (S_shared) {
return get_product_shared_vertex_pos(S, R, T, k1, k2);
}
else { /*T is shared */
return get_product_shared_vertex_pos(T, R, S, k1, k2);
}
}
if (num_exact_shared_vertices == 2) {
if (R_shared && S_shared) {
return get_product_shared_segment_pos(R, S, T, k1, k2);
}
else if (R_shared && T_shared) {
return get_product_shared_segment_pos(R, T, S, k1, k2);
}
else { /*S_shared and T_shared */
return get_product_shared_segment_pos(S, T, R, k1, k2);
}
}
if (num_exact_shared_vertices == 0) {
/* below are the cases when the grids on the neighbor walls
are shifted relative to one another */
/* find out whether the vertices of one tile cross the sides of
another tile */
if ((intersect_point_segment(S_3d, A_3d, B_3d)) ||
(intersect_point_segment(S_3d, B_3d, C_3d)) ||
(intersect_point_segment(S_3d, A_3d, C_3d))) {
S_shared = 1;
}
if ((intersect_point_segment(R_3d, A_3d, B_3d)) ||
(intersect_point_segment(R_3d, B_3d, C_3d)) ||
(intersect_point_segment(R_3d, A_3d, C_3d))) {
R_shared = 1;
}
if ((intersect_point_segment(T_3d, A_3d, B_3d)) ||
(intersect_point_segment(T_3d, B_3d, C_3d)) ||
(intersect_point_segment(T_3d, A_3d, C_3d))) {
T_shared = 1;
}
if ((intersect_point_segment(A_3d, R_3d, S_3d)) ||
(intersect_point_segment(A_3d, S_3d, T_3d)) ||
(intersect_point_segment(A_3d, R_3d, T_3d))) {
A_shared = 1;
}
if ((intersect_point_segment(B_3d, R_3d, S_3d)) ||
(intersect_point_segment(B_3d, S_3d, T_3d)) ||
(intersect_point_segment(B_3d, R_3d, T_3d))) {
B_shared = 1;
}
if ((intersect_point_segment(C_3d, R_3d, S_3d)) ||
(intersect_point_segment(C_3d, S_3d, T_3d)) ||
(intersect_point_segment(C_3d, R_3d, T_3d))) {
C_shared = 1;
}
/* two vertices shared from the same tile */
if (R_shared && S_shared) {
return get_product_shared_segment_pos(R, S, T, k1, k2);
}
else if (R_shared && T_shared) {
return get_product_shared_segment_pos(R, T, S, k1, k2);
}
else if (S_shared && T_shared) {
return get_product_shared_segment_pos(S, T, R, k1, k2);
}
/* two vertices shared from the same tile */
if (A_shared && B_shared) {
if (parallel_segments(A_3d, B_3d, R_3d, S_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(A_new, B_new, T, k1, k2);
}
else if (parallel_segments(A_3d, B_3d, R_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(A_new, B_new, S, k1, k2);
}
else if (parallel_segments(A_3d, B_3d, S_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(A_new, B_new, R, k1, k2);
}
}
else if (A_shared && C_shared) {
if (parallel_segments(A_3d, C_3d, R_3d, S_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(A_new, C_new, T, k1, k2);
}
else if (parallel_segments(A_3d, C_3d, R_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(A_new, C_new, S, k1, k2);
}
else if (parallel_segments(A_3d, C_3d, S_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(A_new, C_new, R, k1, k2);
}
}
else if (B_shared && C_shared) {
if (parallel_segments(B_3d, C_3d, R_3d, S_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(B_new, C_new, T, k1, k2);
} else if (parallel_segments(B_3d, C_3d, R_3d, T_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(B_new, C_new, S, k1, k2);
} else if (parallel_segments(B_3d, C_3d, S_3d, T_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(B_new, C_new, R, k1, k2);
}
}
/* one vertex shared from each tile */
if (R_shared) {
if (A_shared) {
if (parallel_segments(R_3d, A_3d, R_3d, S_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, R, T, k1, k2);
}
else if (parallel_segments(R_3d, A_3d, R_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, R, S, k1, k2);
}
}
else if (B_shared) {
if (parallel_segments(R_3d, B_3d, R_3d, S_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, R, T, k1, k2);
}
else if (parallel_segments(R_3d, B_3d, R_3d, T_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, R, S, k1, k2);
}
}
else if (C_shared) {
if (parallel_segments(R_3d, C_3d, R_3d, S_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, R, T, k1, k2);
}
else if (parallel_segments(R_3d, C_3d, R_3d, T_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, R, S, k1, k2);
}
}
else {
return get_product_shared_vertex_pos(R, S, T, k1, k2);
}
}
else if (S_shared) {
if (A_shared) {
if (parallel_segments(S_3d, A_3d, S_3d, T_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, S, R, k1, k2);
}
else if (parallel_segments(S_3d, A_3d, S_3d, R_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, S, T, k1, k2);
}
}
else if (B_shared) {
if (parallel_segments(S_3d, B_3d, S_3d, T_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, S, R, k1, k2);
}
else if (parallel_segments(S_3d, B_3d, S_3d, R_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, S, T, k1, k2);
}
}
else if (C_shared) {
if (parallel_segments(S_3d, C_3d, S_3d, T_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, S, R, k1, k2);
}
else if (parallel_segments(S_3d, C_3d, S_3d, R_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, S, T, k1, k2);
}
}
else {
return get_product_shared_vertex_pos(S, R, T, k1, k2);
}
}
else if (T_shared) {
if (A_shared) {
if (parallel_segments(T_3d, A_3d, T_3d, S_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, T, R, k1, k2);
}
else if (parallel_segments(T_3d, A_3d, T_3d, R_3d)) {
A_new = xyz2uv(p, A_3d, wall1);
return get_product_shared_segment_pos(A_new, T, S, k1, k2);
}
}
else if (B_shared) {
if (parallel_segments(T_3d, B_3d, T_3d, S_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, T, R, k1, k2);
}
else if (parallel_segments(T_3d, B_3d, T_3d, R_3d)) {
B_new = xyz2uv(p, B_3d, wall1);
return get_product_shared_segment_pos(B_new, T, S, k1, k2);
}
}
else if (C_shared) {
if (parallel_segments(T_3d, C_3d, T_3d, S_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, T, R, k1, k2);
}
else if (parallel_segments(T_3d, C_3d, T_3d, R_3d)) {
C_new = xyz2uv(p, C_3d, wall1);
return get_product_shared_segment_pos(C_new, T, S, k1, k2);
}
}
else {
return get_product_shared_vertex_pos(T, R, S, k1, k2);
}
}
/* only one vertex is shared */
if (A_shared) {
A_new = xyz2uv(p, A_3d, wall1);
if (intersect_point_segment(A_3d, R_3d, S_3d)) {
return get_product_close_to_segment_endpoint_pos(T, A_new, k1, k2);
}
else if (intersect_point_segment(A_3d, R_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(S, A_new, k1, k2);
}
else if (intersect_point_segment(A_3d, S_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(R, A_new, k1, k2);
}
}
else if (B_shared) {
B_new = xyz2uv(p, B_3d, wall1);
if (intersect_point_segment(B_3d, R_3d, S_3d)) {
return get_product_close_to_segment_endpoint_pos(T, B_new, k1, k2);
}
else if (intersect_point_segment(B_3d, R_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(S, B_new, k1, k2);
}
else if (intersect_point_segment(B_3d, S_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(R, B_new, k1, k2);
}
} else if (C_shared) {
C_new = xyz2uv(p, C_3d, wall1);
if (intersect_point_segment(C_3d, R_3d, S_3d)) {
return get_product_close_to_segment_endpoint_pos(T, C_new, k1, k2);
}
else if (intersect_point_segment(C_3d, R_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(S, C_new, k1, k2);
}
else if (intersect_point_segment(C_3d, S_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(R, C_new, k1, k2);
}
}
} /* end if (num_exact_shared_vertices == 0) */
/* Apparently there are some round-up errors that force
the code to come to this place. Below we will try
again to place the product. */
/* find points on the triangle RST that are closest to A, B, C */
Vec3 A_close_3d, B_close_3d, C_close_3d;
pos_t dist_A_A_close_3d, dist_B_B_close_3d, dist_C_C_close_3d, min_dist;
Vec3 prod_pos_3d;
Vec2 prod_pos;
GeometryUtils::closest_pt_point_triangle(A_3d, R_3d, S_3d, T_3d, A_close_3d);
GeometryUtils::closest_pt_point_triangle(B_3d, R_3d, S_3d, T_3d, B_close_3d);
GeometryUtils::closest_pt_point_triangle(C_3d, R_3d, S_3d, T_3d, C_close_3d);
dist_A_A_close_3d = distance3(A_3d, A_close_3d);
dist_B_B_close_3d = distance3(B_3d, B_close_3d);
dist_C_C_close_3d = distance3(C_3d, C_close_3d);
min_dist = min3_p(dist_A_A_close_3d, dist_B_B_close_3d, dist_C_C_close_3d);
if (!distinguishable_p(min_dist, dist_A_A_close_3d, POS_EPS)) {
prod_pos_3d = A_close_3d;
}
else if (!distinguishable_p(min_dist, dist_B_B_close_3d, POS_EPS)) {
prod_pos_3d = B_close_3d;
}
else {
prod_pos_3d = C_close_3d;
}
prod_pos = xyz2uv(p, prod_pos_3d, wall1);
if (intersect_point_segment(prod_pos_3d, R_3d, S_3d)) {
return get_product_close_to_segment_endpoint_pos(T, prod_pos, k1, k2);
}
else if (intersect_point_segment(prod_pos_3d, R_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(S, prod_pos, k1, k2);
}
else if (intersect_point_segment(prod_pos_3d, S_3d, T_3d)) {
return get_product_close_to_segment_endpoint_pos(R, prod_pos, k1, k2);
}
else {
return prod_pos;
}
/* I should not come here... */
mcell_internal_error("Error in the function 'find_closest_position()'.");
}
} // namespace GridPosition
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/defines.cpp | .cpp | 1,482 | 78 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "defines.h"
#include <iostream>
#include <sstream>
#ifndef _MSC_VER
#include <sys/time.h>
#include <sys/resource.h>
#endif
#ifdef DWITHGPERFTOOLS
// using longer path to avoid collisions
#include "install_gperftools/include/profiler.h"
#endif
using namespace std;
namespace MCell {
string Vec3::to_string() const {
stringstream ss;
ss << *this;
return ss.str();
}
void Vec3::dump(const std::string extra_comment, const std::string ind) const {
cout << ind << extra_comment << *this << "\n";
}
string Vec2::to_string() const {
stringstream ss;
ss << *this;
return ss.str();
}
void Vec2::dump(const std::string extra_comment, const std::string ind) const {
cout << ind << extra_comment << *this << "\n";
}
uint64_t get_mem_usage() {
#ifdef _WIN64
return 0;
#else
int who = RUSAGE_SELF;
struct rusage usage;
int ret;
ret = getrusage(who,&usage);
if (ret == 0) {
return usage.ru_maxrss;
}
else {
// ignoring fail
return 0;
}
#endif
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/mol_order_shuffle_event.h | .h | 922 | 37 |
/******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MOL_ORDER_SHUFFLE_EVENT_H_
#define SRC4_MOL_ORDER_SHUFFLE_EVENT_H_
#include "base_event.h"
namespace MCell {
class MolOrderShuffleEvent: public BaseEvent {
public:
MolOrderShuffleEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_MOL_SHUFFLE),
world(world_) {
}
void step() override;
void dump(const std::string indent) const override;
private:
World* world;
};
} // namespace mcell
#endif // SRC4_MOL_ORDER_SHUFFLE_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/species_cleanup_event.cpp | .cpp | 3,084 | 106 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <fstream>
#include <sstream>
#include "species_cleanup_event.h"
#include "world.h"
using namespace std;
namespace MCell {
void SpeciesCleanupEvent::dump(const string ind) const {
cout << ind << "Species cleanup event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
void SpeciesCleanupEvent::remove_unused_reactant_classes() {
// get a set of used reactant classes
uint_set<BNG::reactant_class_id_t> used_reactant_classes;
for (BNG::Species* sp: world->get_all_species().get_species_vector()) {
release_assert(sp != nullptr);
if (sp->has_valid_reactant_class_id()) {
used_reactant_classes.insert(sp->get_reactant_class_id());
}
}
// go through all reactant classes and select those that are not used
uint_set<BNG::reactant_class_id_t> unused_reactant_classes;
for (const BNG::ReactantClass* rc: world->get_all_rxns().get_reactant_classes()) {
if (rc != nullptr && used_reactant_classes.count(rc->id) == 0) {
unused_reactant_classes.insert(rc->id);
}
}
// remove the unused classes
for (BNG::reactant_class_id_t id: unused_reactant_classes) {
// from rxn container including reacting classes
world->get_all_rxns().remove_reactant_class(id);
// and from partition's reactants map
world->get_partition(PARTITION_ID_INITIAL).remove_reactant_class_usage(id);
}
}
void SpeciesCleanupEvent::step() {
// remove all rxn classes and all caches
world->get_all_rxns().reset_caches();
for (BNG::Species* sp: world->get_all_species().get_species_vector()) {
release_assert(sp != nullptr);
// num_instantiations tells us that there are no molecules of these species
// is_removable - species were created on the fly
if (sp->get_num_instantiations() == 0 && sp->is_removable()) {
// tell partitions that this species is not known anymore
if (sp->is_vol()) {
for (Partition& p: world->get_partitions()) {
p.remove_from_known_vol_species(sp->id);
}
}
if (world->config.rxn_and_species_report) {
stringstream ss;
ss << sp->id << ": " << sp->to_str() << " - removed\n";
BNG::append_to_report(world->config.get_species_report_file_name(), ss.str());
}
// delete this species
world->get_all_species().remove(sp->id);
// and also from caches used by RxnRules
world->get_all_rxns().remove_species_id_references(sp->id);
}
}
// cleanup the species array, we must remove nullptrs from the species array
world->get_all_species().defragment();
// also remove unused reactant classes
remove_unused_reactant_classes();
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/mcell4_iface_for_mcell3.h | .h | 788 | 23 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MCELL4_IFACE_FOR_MCELL3_H_
#define SRC4_MCELL4_IFACE_FOR_MCELL3_H_
#include "mcell_structs_shared.h"
bool mcell4_convert_mcell3_volume(struct volume* s);
bool mcell4_run_simulation(const bool dump_initial_state, const bool dump_with_geometry = false);
void mcell4_convert_to_data_model(const bool only_for_viz);
void mcell4_delete_world();
#endif // SRC4_MCELL4_IFACE_FOR_MCELL3_H_
| Unknown |
3D | mcellteam/mcell | src4/mol_or_rxn_count_event.h | .h | 7,499 | 263 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MOL_OR_RXN_COUNT_EVENT_H_
#define SRC4_MOL_OR_RXN_COUNT_EVENT_H_
#include "bng/bng.h"
#include "base_event.h"
#include "count_buffer.h"
#include "region_expr.h"
namespace BNG {
class SpeciesContainer;
}
namespace MCell {
class Partition;
class Molecule;
class World;
enum class SpeciesPatternType {
Invalid,
SpeciesId, // TODO: remove this variant
SpeciesPattern,
MoleculesPattern
};
enum class CountType {
Invalid,
EnclosedInWorld,
EnclosedInVolumeRegion,
PresentOnSurfaceRegion,
RxnCountInWorld,
RxnCountInVolumeRegion,
RxnCountOnSurfaceRegion,
};
class MolOrRxnCountTerm {
public:
MolOrRxnCountTerm()
: type(CountType::Invalid),
sign_in_expression(0),
orientation(ORIENTATION_NOT_SET),
species_pattern_type(SpeciesPatternType::Invalid),
species_id(SPECIES_ID_INVALID),
species_molecules_pattern(nullptr),
primary_compartment_id(BNG::COMPARTMENT_ID_NONE),
rxn_rule_id(BNG::RXN_RULE_ID_INVALID),
initial_reactions_count(0)
{
}
uint get_num_pattern_matches(const species_id_t species_id) const;
uint get_num_molecule_matches(
const Molecule& m,
const species_id_t all_mol_id, const species_id_t all_vol_id, const species_id_t all_surf_id
) const;
bool is_mol_count() const {
return type == CountType::EnclosedInWorld || type == CountType::EnclosedInVolumeRegion ||
type == CountType::PresentOnSurfaceRegion;
}
bool is_rxn_count() const {
return type == CountType::RxnCountInWorld || type == CountType::RxnCountInVolumeRegion ||
type == CountType::RxnCountOnSurfaceRegion;
}
void dump(const std::string ind = "") const;
std::string to_data_model_string(const World* world, bool print_positive_sign) const;
CountType type;
// if sign_in_expression == +1 -> add to the total count
// if sign_in_expression == -1 -> subtract from the total count
// 0 - invalid
int sign_in_expression;
// valid when type is EnclosedInWorld, EnclosedInObject or PresentOnSurfaceRegion
orientation_t orientation;
SpeciesPatternType species_pattern_type;
// valid when species_pattern_type is SpeciesId, not used in MCell4
// TODO: remove for MCell4 MDL mode and replace with SpeciesPattern/species_molecules_pattern
species_id_t species_id;
// valid when species_pattern_type is SpeciesPattern or MoleculesPattern
BNG::Cplx species_molecules_pattern;
// when primary_compartment_id is COMPARTMENT_ID_NONE, it is ignored
// used only for molecule counting
BNG::compartment_id_t primary_compartment_id;
// set in compute_count_species_info based on species_molecules_pattern
// presence is tested when species_pattern_type is SpeciesPattern
// the value is used when species_pattern_type is MoleculesPattern
std::map<species_id_t, uint> species_ids_matching_pattern_w_multiplier_cache;
// valid when type is RxnCountInWorld, RxnCountInObject or RxnOnSurfaceRegion
BNG::rxn_rule_id_t rxn_rule_id;
// valid when type is EnclosedInObject or RxnCountInObject or
// PresentOnSurfaceRegion or RxnOnSurfaceRegion
// region_expr.root is nullptr otherwise
RegionExpr region_expr;
// holds initial value when resumed from a checkpoint,
// ignored for molecule counts
uint64_t initial_reactions_count;
};
typedef small_vector<MolOrRxnCountTerm> MolOrRxnCountTermVector;
class MolOrRxnCountItem {
public:
MolOrRxnCountItem(
const count_buffer_id_t buffer_id_, const uint buffer_column_index_)
: index(UINT_INVALID), buffer_id(buffer_id_), buffer_column_index(buffer_column_index_), multiplier(1) {
assert(buffer_id != COUNT_BUFFER_ID_INVALID);
assert(buffer_column_index != UINT_INVALID);
}
bool is_world_mol_count() const;
bool counts_mols() const;
bool counts_rxns() const;
void dump(const std::string ind = "") const;
void to_data_model(const World* world, Json::Value& reaction_output) const;
// index of this item in MolOrRxnCountEvent's mol_rxn_count_items
uint index;
// count buffer objects are owned by World
count_buffer_id_t buffer_id;
// index of column in buffer where this value will be stored
// always 0 when the output format is DAT
uint buffer_column_index;
// note: items are shared in MCell3 but so far it seems that
// we can just count them separately
MolOrRxnCountTermVector terms;
// value used to multiply the whole result
double multiplier;
};
typedef small_vector<MolOrRxnCountItem> MolOrRxnCountItemVector;
/**
* Structure used in caching of information on whether the coutn event counts given species.
*/
struct CountSpeciesInfo {
CountSpeciesInfo()
: all_are_world_mol_counts(true) {
}
// when true, all count items that count this species are listed in
// the world_count_item_indices
bool all_are_world_mol_counts;
// indices of count items that count this species in the whole world
uint_set<uint> world_count_item_indices;
};
/**
* Dumps counts of molecules.
*/
class MolOrRxnCountEvent: public BaseEvent {
public:
MolOrRxnCountEvent(World* world_)
: BaseEvent(EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT),
world(world_), count_mols(false), count_rxns(false) {
}
virtual ~MolOrRxnCountEvent() {
}
void step() override;
// used from MCell4 API
double get_single_count_value();
// DiffuseReactEvent must execute only up to this event
bool is_barrier() const override { return true; }
void dump(const std::string ind = "") const override;
void to_data_model(Json::Value& mcell_node) const override;
void add_mol_count_item(const MolOrRxnCountItem& item) {
mol_rxn_count_items.push_back(item);
// set index
mol_rxn_count_items.back().index = mol_rxn_count_items.size() - 1;
// set counting flags
if (item.counts_mols()) {
count_mols = true;
}
if (item.counts_rxns()) {
count_rxns = true;
}
}
MolOrRxnCountItemVector mol_rxn_count_items;
World* world;
private:
void check_countable_species(const species_id_t species_id);
void compute_count_species_info(const species_id_t species_id);
void compute_mol_count_item(
const Partition& p,
const MolOrRxnCountItem& item,
const Molecule& m,
CountValueVector& count_values
);
void compute_rxn_count_item(
Partition& p,
const MolOrRxnCountItem& item,
const BNG::RxnRule* rxn,
CountValueVector& count_values
);
void compute_counts(CountValueVector& count_values);
// indexed by species_id
// mapping all species_ids onto those to be counted (CountSpeciesInfo)
// values: NotSeenYet, NotToBeCounted, >= 0 for indexing count_species_info_vec
std::vector<count_species_info_index_t> countable_species_lut;
// indexed by the values (>= 0) stored in countable_species_lut
// containing CountSpeciesInfo for those to be counted
std::vector<CountSpeciesInfo> count_species_info_vec;
// flags to optimize counting
bool count_mols;
bool count_rxns;
};
} // namespace mcell
#endif // SRC4_MOL_OR_RXN_COUNT_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/world.cpp | .cpp | 38,150 | 1,089 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <fenv.h> // Linux include
#ifndef _MSC_VER
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/resource.h> // Linux include
#endif
#include <signal.h>
#include <fstream>
#include "rng.h" // MCell 3
#include "logging.h"
#include "util.h"
#include "world.h"
#include "viz_output_event.h"
#include "defragmentation_event.h"
#include "rxn_class_cleanup_event.h"
#include "species_cleanup_event.h"
#include "sort_mols_by_subpart_event.h"
#include "release_event.h"
#include "mol_or_rxn_count_event.h"
#include "datamodel_defines.h"
#include "bng_data_to_datamodel_converter.h"
#include "diffuse_react_event.h"
#include "run_n_iterations_end_event.h"
#include "custom_function_call_event.h"
#include "mol_order_shuffle_event.h"
#include "vtk_utils.h"
#include "wall_overlap.h"
#include "api/mol_wall_hit_info.h"
#include "api/geometry_object.h"
#include "api/model.h"
#include "generated/gen_constants.h"
#include "bng/filesystem_utils.h"
using namespace std;
const double USEC_IN_SEC = 1000000.0;
namespace MCell {
static double tousecs(timeval& t) {
return (double)t.tv_sec * USEC_IN_SEC + (double)t.tv_usec;
}
static double tosecs(timeval& t) {
return (double)t.tv_sec + (double)t.tv_usec/USEC_IN_SEC;
}
static void print_periodic_stats_func(double time, World* world) {
release_assert(world != nullptr);
world->print_periodic_stats();
}
World::World(API::Callbacks& callbacks_)
: bng_engine(config),
callbacks(callbacks_),
total_iterations(0),
next_wall_id(0),
next_region_id(0),
next_geometry_object_id(0),
simulation_initialized(false),
run_n_iterations_terminated_with_checkpoint(false),
simulation_ended(false),
buffers_flushed(false),
it1_start_time_set(false),
previous_iteration(0),
signaled_checkpoint_signo(API::SIGNO_NOT_SIGNALED),
signaled_checkpoint_model(nullptr)
{
config.partition_edge_length = FLT_INVALID;
config.num_subparts_per_partition_edge = SUBPARTITIONS_PER_PARTITION_DIMENSION_DEFAULT;
// although the same thing is called in init_simulation, not reseting it causes weird valdrind reports on
// uninitialized variable
reset_rusage(&sim_start_time);
}
World::~World() {
if (!buffers_flushed) {
flush_and_close_buffers();
}
for (MolOrRxnCountEvent* e: unscheduled_count_events) {
delete e;
}
}
void World::init_fpu() {
// default is FE_TONEAREST but let's set it to be sure
fesetround(FE_TONEAREST);
}
uint64_t World::determine_output_frequency(uint64_t iterations) {
uint64_t frequency;
if (iterations < 10)
frequency = 1;
else if (iterations < 1000)
frequency = 10;
else if (iterations < 100000)
frequency = 100;
else if (iterations < 10000000)
frequency = 1000;
else if (iterations < 1000000000)
frequency = 10000;
else
frequency = 100000;
return frequency;
}
void World::create_initial_surface_region_release_event() {
ReleaseEvent* rel_event = new ReleaseEvent(this);
rel_event->event_time = 0;
rel_event->release_site_name = "initial surface releases";
rel_event->release_shape = ReleaseShape::INITIAL_SURF_REGION;
rel_event->update_event_time_for_next_scheduled_time();
scheduler.schedule_event(rel_event);
}
void World::init_counted_volumes() {
assert(partitions.size() == 1);
bool ok = VtkUtils::initialize_counted_volumes(this, config.has_intersecting_counted_objects);
if (!ok) {
mcell_error("Processing of counted volumes failed, terminating.");
}
partitions[PARTITION_ID_INITIAL].initialize_all_waypoints();
}
static double get_event_start_time(const double start_time, const double periodicity) {
if (periodicity == 0) {
return 0;
}
else {
return floor_to_multiple_f(start_time + periodicity, periodicity);
}
}
void World::schedule_checkpoint_event(
const uint64_t iteration, const bool continue_simulation, const API::CheckpointSaveEventContext& ctx) {
CustomFunctionCallEvent<API::CheckpointSaveEventContext>* checkpoint_event =
new CustomFunctionCallEvent<API::CheckpointSaveEventContext>(
API::save_checkpoint_func, ctx, EVENT_TYPE_INDEX_CALL_START_ITERATION_CHECKPOINT);
if (iteration == 0) {
// schedule for the closest iteration while correctly maintaining order of events in the queue
checkpoint_event->event_time = TIME_INVALID;
}
else {
checkpoint_event->event_time = iteration;
}
checkpoint_event->periodicity_interval = 0; // only once
checkpoint_event->return_from_run_n_iterations = !continue_simulation;
// safely schedule
// not really needed to do safely when called due to a signal handler because only a flag
// is set and the handling is done synchronously, but required when schedule_checkpoint is called e.g. from
// a timer
scheduler.schedule_event_asynchronously(checkpoint_event);
}
void World::check_checkpointing_signal() {
if (signaled_checkpoint_signo == API::SIGNO_NOT_SIGNALED) {
return;
}
bool continue_simulation = false;
// printout for each model instance
#ifndef _WIN32
if (signaled_checkpoint_signo == SIGUSR1) {
cout << "User signal SIGUSR1 detected, scheduling a checkpoint and continuing simulation.\n";
continue_simulation = true;
}
else if (signaled_checkpoint_signo == SIGUSR2) {
cout << "User signal SIGUSR2 detected, scheduling a checkpoint and terminating simulation afterwards.\n";
continue_simulation = false;
}
else
#endif
if (signaled_checkpoint_signo == SIGALRM) {
cout << "Signal SIGALRM detected - periodic or time limit elapsed, scheduling a checkpoint ";
if (config.continue_after_sigalrm) {
cout << "and continuing simulation.\n";
continue_simulation = true;
}
else {
cout << "and terminating simulation afterwards.\n";
continue_simulation = false;
}
}
else {
cout << "Unexpected signal " << signaled_checkpoint_signo << " received, fatal error.\n";
release_assert(false);
}
API::CheckpointSaveEventContext ctx;
release_assert(signaled_checkpoint_model != nullptr);
ctx.model = signaled_checkpoint_model;
ctx.dir_prefix = config.get_default_checkpoint_dir_prefix();
ctx.append_it_to_dir = true;
schedule_checkpoint_event(0, continue_simulation, ctx);
// reset flag and pointer to model because we don't need it anymore
signaled_checkpoint_signo = API::SIGNO_NOT_SIGNALED;
signaled_checkpoint_model = nullptr;
}
void World::init_simulation(const double start_time) {
release_assert((int)start_time == start_time && "Iterations start time must be an integer.");
// TODO: check these messages in testsuite
#ifdef MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
mcell_log("!!! WARNING: Event sorting according to time and id was enabled for debugging, testing won't pass.");
#endif
#ifdef MCELL4_DO_NOT_REUSE_REACTANT
mcell_log("!!! WARNING: Reactant reuse is disabled, testing won't pass.");
#endif
#ifdef MCELL4_SORT_RXN_PRODUCTS_BY_NAME
mcell_log("!!! WARNING: Standard product sorting is disabled, testing won't pass.");
#endif
if (DUMP4_PRECISION != DUMP4_PRECISION_DEFAULT) {
cout.precision(DUMP4_PRECISION);
}
assert(!simulation_initialized && "init_simulation must be called just once");
if (get_all_species().get_count() == 0) {
mcell_log("Error: there must be at least one species!");
exit(1);
}
stats.reset(false);
init_fpu();
init_counted_volumes();
cout <<
"Partition contains " << config.num_subparts_per_partition_edge << "^3 subpartitions, " <<
"subpartition size is " << config.subpart_edge_length * config.length_unit << " microns.\n";
assert(partitions.size() == 1 && "Initial partition must have been created, only 1 is allowed for now");
// create event that diffuses molecules
DiffuseReactEvent* event = new DiffuseReactEvent(this);
event->event_time = start_time;
scheduler.schedule_event(event);
// create defragmentation events
DefragmentationEvent* defragmentation_event = new DefragmentationEvent(this);
defragmentation_event->event_time = get_event_start_time(start_time, DEFRAGMENTATION_PERIODICITY);
defragmentation_event->periodicity_interval = DEFRAGMENTATION_PERIODICITY;
scheduler.schedule_event(defragmentation_event);
// create rxn class cleanup events
if (config.rxn_class_cleanup_periodicity >= 1) {
RxnClassCleanupEvent* rxn_class_cleanup_event = new RxnClassCleanupEvent(this);
rxn_class_cleanup_event->event_time = get_event_start_time(start_time, config.rxn_class_cleanup_periodicity);
rxn_class_cleanup_event->periodicity_interval = config.rxn_class_cleanup_periodicity;
scheduler.schedule_event(rxn_class_cleanup_event);
}
if (config.species_cleanup_periodicity >= 1) {
SpeciesCleanupEvent* species_cleanup_event = new SpeciesCleanupEvent(this);
species_cleanup_event->event_time = get_event_start_time(start_time, config.species_cleanup_periodicity);
species_cleanup_event->periodicity_interval = config.species_cleanup_periodicity;
scheduler.schedule_event(species_cleanup_event);
}
if (config.molecules_order_random_shuffle_periodicity >= 1) {
MolOrderShuffleEvent* mol_order_shuffle_event = new MolOrderShuffleEvent(this);
mol_order_shuffle_event->event_time = get_event_start_time(start_time, config.molecules_order_random_shuffle_periodicity);
mol_order_shuffle_event->periodicity_interval = config.molecules_order_random_shuffle_periodicity;
scheduler.schedule_event(mol_order_shuffle_event);
}
// create subpart sorting events
if (config.sort_mols_by_subpart) {
SortMolsBySubpartEvent* sort_event = new SortMolsBySubpartEvent(this);
if (start_time == 0) {
sort_event->event_time = TIME_SIMULATION_START;
}
else {
sort_event->event_time = get_event_start_time(start_time, SORT_MOLS_BY_SUBPART_PERIODICITY);
}
sort_event->periodicity_interval = SORT_MOLS_BY_SUBPART_PERIODICITY;
scheduler.schedule_event(sort_event);
}
// simulation statistics, mostly for development purposes
if (config.simulation_stats_every_n_iterations > 0) {
CustomFunctionCallEvent<World*>* stats_event =
new CustomFunctionCallEvent<World*>(print_periodic_stats_func, this);
stats_event->event_time = start_time;
stats_event->periodicity_interval = config.simulation_stats_every_n_iterations;
scheduler.schedule_event(stats_event);
}
// initialize timing
previous_progress_report_time = chrono::steady_clock::now();
previous_buffer_flush_time = previous_progress_report_time;
reset_rusage(&sim_start_time);
getrusage(RUSAGE_SELF, &sim_start_time);
// iteration counter to report progress
previous_iteration = 0;
if (!config.use_expanded_list) {
cout <<
"Warning: configuration 'use_expanded_list' (ACCURATE_3D_REACTIONS) set to false is compatible "
"with MCell3 only in simple cases without volume reactions and usually MCell4 produces different results. "
"Search for potential reactions in MCell3 is always based on reaction radius, "
"the solution in MCell3 can be highly imprecise because it considers subvolume/subpartition boundaries "
"when computing reaction probability factor in exact-disk.\n";
}
// start memory check timer
memory_limit_checker.start_timed_check(this, config.memory_limit_gb);
if (stats.get_current_iteration() == 0) {
// not starting from a checkpoint
config.initialize_run_report_file();
BNG::append_to_report(config.get_run_report_file_name(), "Simulation started ");
}
else {
cout << "Iterations: " << stats.get_current_iteration() << " of " << total_iterations << " (resuming a checkpoint)\n";
BNG::append_to_report(config.get_run_report_file_name(), "Simulation resumed from a checkpoint ");
}
BNG::append_to_report(config.get_run_report_file_name(),
"at iteration " + to_string(stats.get_current_iteration()) +
" and time " + BNG::get_current_date_time() + ".\n");
simulation_initialized = true;
}
uint64_t World::time_to_iteration(const double time) {
return (uint64_t)(time - config.get_simulation_start_time()) + config.initial_iteration;
}
uint64_t World::run_n_iterations(const uint64_t num_iterations, const bool terminate_last_iteration_after_viz_output) {
release_assert(simulation_initialized);
run_n_iterations_terminated_with_checkpoint = false;
uint64_t output_frequency = determine_output_frequency(total_iterations);
uint64_t this_run_first_iteration = stats.get_current_iteration();
uint64_t& current_iteration = stats.get_current_iteration();
if (current_iteration == 0 && config.iteration_report) {
cout << "Iterations: " << current_iteration << " of " << total_iterations << "\n";
}
// information for scheduling of RunNIterationsEndEvent
bool run_n_iters_end_event_created = false;
uint64_t iteration_to_create_run_n_iters_end_event;
if (num_iterations <= ITERATIONS_BEFORE_RUN_N_ITERATIONS_END_EVENT) {
// schedule right away
iteration_to_create_run_n_iters_end_event = this_run_first_iteration;
}
else {
// schedule later
iteration_to_create_run_n_iters_end_event =
this_run_first_iteration + num_iterations - ITERATIONS_BEFORE_RUN_N_ITERATIONS_END_EVENT;
}
do {
check_checkpointing_signal();
if (!run_n_iters_end_event_created && iteration_to_create_run_n_iters_end_event == current_iteration) {
// create event that is used to check whether simulation should end right after the last viz output,
// also serves as a simulation barrier to not to do diffusion after this point in time
// must not be created right away when run_n_iterations is called because this might require too much memory
RunNIterationsEndEvent* run_n_iterations_end_event = new RunNIterationsEndEvent();
run_n_iterations_end_event->event_time = this_run_first_iteration + num_iterations;
run_n_iterations_end_event->periodicity_interval = 0; // these markers are inserted into every time step
scheduler.schedule_event(run_n_iterations_end_event);
run_n_iters_end_event_created = true;
}
// current_iteration corresponds to the number of executed time steps
double time = scheduler.get_next_event_time();
// convert time to iteration
current_iteration = time_to_iteration(time);
if (current_iteration == 1 && previous_iteration == 0) {
it1_start_time_set = true;
reset_rusage(&it1_start_time);
getrusage(RUSAGE_SELF, &it1_start_time);
}
#ifdef DEBUG_SCHEDULER
cout << "Before it: " << current_iteration << ", time: " << time << "\n";
#endif
// terminate simulation if we executed the right number of iterations
if (current_iteration >= this_run_first_iteration + num_iterations) {
break;
}
if (current_iteration > previous_iteration && current_iteration % output_frequency == 0) {
// only with output frequency - getting clock may be costly
auto current_time = std::chrono::steady_clock::now();
// should we flush count buffers because certain time elapsed?
// this must be done as the first thing in a new iteration because running just one MolOrRxnCountEvent
// may leave incomplete line in a gdat count buffer
// FIXME: this should be rather an event
double time_diff = chrono::duration_cast<chrono::seconds>(current_time - previous_buffer_flush_time).count();
if (time_diff >= COUNT_BUFFER_FLUSH_SECONDS) {
flush_buffers();
previous_buffer_flush_time = current_time;
}
}
// this is where events get executed
EventExecutionInfo event_info = scheduler.handle_next_event();
// report progress
if (current_iteration > previous_iteration) {
if (current_iteration % output_frequency == 0) {
auto current_time = std::chrono::steady_clock::now();
if (config.iteration_report) {
cout << "Iterations: " << current_iteration << " of " << total_iterations;
double iters_per_sec =
1000000.0 /
((chrono::duration_cast<chrono::microseconds>(current_time - previous_progress_report_time).count() /
(double)output_frequency));
cout << " (" << iters_per_sec << " iter/sec)";
previous_progress_report_time = current_time;
cout << " " << bng_engine.get_stats_report();
cout << "\n";
cout.flush(); // flush is required so that CellBlender can display progress
}
}
previous_iteration = current_iteration;
}
#ifdef DEBUG_SCHEDULER
cout << "After it: " << current_iteration << ", time: " << time << "\n";
#endif
// also terminate if this was the last iteration and we hit an event that represents a check for the
// end of the simulation
if (
(terminate_last_iteration_after_viz_output &&
event_info.type_index == EVENT_TYPE_INDEX_SIMULATION_END_CHECK
) ||
event_info.return_from_run_iterations
) {
assert(
event_info.return_from_run_iterations ||
current_iteration == this_run_first_iteration + num_iterations - 1);
if (event_info.type_index == EVENT_TYPE_INDEX_CALL_START_ITERATION_CHECKPOINT) {
run_n_iterations_terminated_with_checkpoint = true;
}
break;
}
} while (true); // terminated when the nr. of iterations is reached
#ifndef NDEBUG
// flush everything, we want the output to be mixed with Python in the right ordering
cout.flush();
cerr.flush();
fflush(stdout);
fflush(stderr);
#endif
return current_iteration - this_run_first_iteration;
}
count_buffer_id_t World::create_dat_count_buffer(
const std::string file_name, const size_t buffer_size, const bool open_for_append) {
count_buffer_id_t id = count_buffers.size();
std::vector<std::string> column_names = { file_name }; // name is not used when .dat format is used
count_buffers.push_back(
CountBuffer(CountOutputFormat::DAT, file_name, column_names, buffer_size, open_for_append));
count_buffers.back().open();
return id;
}
count_buffer_id_t World::create_gdat_count_buffer(
const std::string file_name, const std::vector<std::string>& column_names,
const size_t buffer_size, const bool open_for_append) {
count_buffer_id_t id = count_buffers.size();
count_buffers.push_back(
CountBuffer(CountOutputFormat::GDAT, file_name, column_names, buffer_size, open_for_append));
count_buffers.back().open();
return id;
}
void World::flush_buffers() {
// only flush count buffers
for (CountBuffer& b: count_buffers) {
b.flush();
}
}
void World::flush_and_close_buffers() {
assert(!buffers_flushed && "Buffers can be flushed only once");
// flush and close count buffers
for (CountBuffer& b: count_buffers) {
b.flush_and_close();
}
buffers_flushed = true;
}
// prints message (appends newline), flushes buffers, and terminates
void World::fatal_error(const std::string& msg) {
errs() << msg << "\n";
flush_and_close_buffers();
exit(1);
}
void World::end_simulation(const bool print_final_report) {
// we do not want to check memory anymore
memory_limit_checker.stop_timed_check();
if (simulation_ended) {
// already called, do nothing
return;
}
// - execute all events up to the last viz output
// to produce viz output and counts for the last iteration
// - must not be done if we ended with checkpoint
if (!run_n_iterations_terminated_with_checkpoint) {
run_n_iterations(1, true);
}
flush_and_close_buffers();
if (print_final_report) {
cout << "Iteration " << stats.get_current_iteration() << ", simulation finished successfully";
if (run_n_iterations_terminated_with_checkpoint) {
cout << ", terminated with a checkpoint";
}
cout << "\n";
stats.print_report(config.get_warnings_report_file_name());
// report final time
rusage run_time;
reset_rusage(&run_time);
getrusage(RUSAGE_SELF, &run_time);
cout << "Simulation CPU time = "
<< tosecs(run_time.ru_utime) - tosecs(sim_start_time.ru_utime) << " (user) and "
<< tosecs(run_time.ru_stime) - tosecs(sim_start_time.ru_stime) << " (system)\n";
cout << "Simulation CPU time without iteration 0 = "
<< tosecs(run_time.ru_utime) - tosecs(it1_start_time.ru_utime) << " (user) and "
<< tosecs(run_time.ru_stime) - tosecs(it1_start_time.ru_stime) << " (system)\n";
// and warnings
bng_engine.get_config().print_final_warnings();
}
BNG::append_to_report(config.get_run_report_file_name(),
"Simulation ended at iteration " + to_string(stats.get_current_iteration()) +
" and time " + BNG::get_current_date_time() + ", " +
((run_n_iterations_terminated_with_checkpoint) ?
"terminated due to checkpoint.\n" :
"all iterations were finished.\nFINISHED\n"));
simulation_ended = true;
}
void World::init_and_run_simulation(const bool dump_initial_state, const bool dump_with_geometry) {
// do initialization, also insert
// defragmentation and end simulation event
init_simulation(TIME_SIMULATION_START);
if (dump_initial_state) {
dump(dump_with_geometry);
}
run_n_iterations(total_iterations, true);
// runs one more iteration but only up to the last viz output
end_simulation(true);
}
void World::print_periodic_stats() const {
cout << "--- Periodic Stats ---\n";
cout << "World: stats.current_iteration = " << stats.get_current_iteration() << "\n";
scheduler.print_periodic_stats();
bng_engine.print_periodic_stats();
get_partition(PARTITION_ID_INITIAL).print_periodic_stats();
cout << "Memory: " << get_mem_usage() << " kB\n";
cout << "----------------------\n";
}
void World::dump(const bool with_geometry) {
config.dump();
stats.print_report();
bng_engine.get_data().dump();
get_all_species().dump();
get_all_rxns().dump(true);
// partitions
for (Partition& p: partitions) {
p.dump(with_geometry);
}
scheduler.dump();
}
bool World::check_for_overlapped_walls() {
/* pick up a random vector */
Vec3 rand_vec;
rand_vec.x = rng_dbl(&rng);
rand_vec.y = rng_dbl(&rng);
rand_vec.z = rng_dbl(&rng);
for (Partition& p: partitions) {
bool ok = WallOverlap::check_for_overlapped_walls(p, rand_vec);
if (!ok) {
return false;
}
}
return true;
}
void World::reset_unimol_rxn_times(const BNG::rxn_rule_id_t rxn_rule_id) {
// get all affected species
const BNG::RxnRule* rxn = get_all_rxns().get(rxn_rule_id);
assert(rxn->is_unimol());
// and then reset unimol time for each molecule of that species
for (Partition& p: partitions) {
for (Molecule& m: p.get_molecules()) {
assert((rxn->species_applicable_as_any_reactant.count(m.species_id) != 0 ||
rxn->species_not_applicable_as_any_reactant.count(m.species_id) != 0) &&
"This unimol rxn must have been analyzed for this species because the species are instantiated");
if (rxn->species_applicable_as_any_reactant.count(m.species_id) != 0) {
// new unimol time will be computed when the molecule is diffused
// the next time (we cannot change it right away for molecules that
// have longer timestep anyway because they were already diffused to the future)
// is this a nondiffusible molecule? - these don't have to be scheduled for diffusion,
// therefore their unimol rxn time would not be updated
const BNG::Species& s = get_all_species().get(m.species_id);
if (!s.can_diffuse() && (m.diffusion_time == TIME_FOREVER || m.diffusion_time == m.unimol_rxn_time)) {
// we cannot change the unimol rate if we are currently diffusing, but
// let's update it as soon as possible by running their diffusion
m.diffusion_time = scheduler.get_next_event_time();
}
m.unimol_rxn_time = TIME_INVALID;
m.clear_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE);
m.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
}
}
}
}
void World::export_geometry_to_obj(const std::string& files_prefix) const {
// create directories if needed
FSUtils::make_dir_for_file_w_multiple_attempts(files_prefix);
// only one partition now
const Partition& p = get_partition(PARTITION_ID_INITIAL);
VtkUtils::export_geometry_objects_to_obj(this, p.get_geometry_objects(), files_prefix);
}
void World::export_data_model_to_dir(const std::string& prefix, const bool only_for_viz) const {
// prefix should be the same directory that is used for viz_output,
// e.g. ./viz_data/seed_0001/Scene
stringstream path;
path <<
prefix << ".data_model." <<
VizOutputEvent::iterations_to_string(stats.get_current_iteration(), total_iterations) <<
".json";
// create directories if needed
FSUtils::make_dir_for_file_w_multiple_attempts(path.str());
export_data_model(path.str(), only_for_viz);
}
void World::export_data_model(const std::string& file_name, const bool only_for_viz) const {
Json::Value root;
to_data_model(root, only_for_viz);
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = " ";
wbuilder.settings_["precision"] = 15; // this is the precision that is used by mdl_to_data_model.py script
wbuilder.settings_["precisionType"] = "significant";
std::string document = Json::writeString(wbuilder, root);
// write result into a file
ofstream res_file(file_name);
if (res_file.is_open())
{
res_file << document;
res_file.close();
}
else {
cout << "Unable to open file " << file_name << " for writing.\n";
}
// also, if rxn_output was enabled and in the first iteration, generate data_layout.json file
// in the current directory
if (stats.get_current_iteration() == 0) {
export_data_layout();
}
}
void World::to_data_model(Json::Value& root, const bool only_for_viz) const {
Json::Value& mcell = root[KEY_MCELL];
mcell[KEY_CELLBLENDER_VERSION] = VALUE_CELLBLENDER_VERSION;
DMUtils::add_version(mcell, VER_DM_2017_06_23_1300);
initialization_to_data_model(mcell);
// generate geometry information
// first create empty model_objects section (may be filled-in by
// GeometryObject::to_data_model_as_model_object
Json::Value& model_objects = mcell[KEY_MODEL_OBJECTS];
DMUtils::add_version(model_objects, VER_DM_2018_01_11_1330);
Json::Value& model_object_list = model_objects[KEY_MODEL_OBJECT_LIST];
model_object_list = Json::Value(Json::arrayValue);
// then dump all partition data
set<rgba_t> used_colors;
bool first = true;
for (const Partition& p: partitions) {
p.to_data_model(mcell, used_colors);
}
// base information for reaction_data_output must be set even when there are no such events
Json::Value& reaction_data_output = mcell[KEY_REACTION_DATA_OUTPUT];
DMUtils::add_version(reaction_data_output, VER_DM_2016_03_15_1800);
reaction_data_output[KEY_PLOT_LAYOUT] = " ";
reaction_data_output[KEY_PLOT_LEGEND] = "0";
reaction_data_output[KEY_MOL_COLORS] = false;
reaction_data_output[KEY_ALWAYS_GENERATE] = true;
reaction_data_output[KEY_OUTPUT_BUF_SIZE] = "";
reaction_data_output[KEY_RXN_STEP] = "";
reaction_data_output[KEY_COMBINE_SEEDS] = true;
Json::Value& reaction_output_list = reaction_data_output[KEY_REACTION_OUTPUT_LIST];
reaction_output_list = Json::Value(Json::arrayValue); // empty array
scheduler.to_data_model(mcell, only_for_viz);
// generate species and rxn info
BngDataToDatamodelConverter bng_converter;
bng_converter.to_data_model(this, mcell, only_for_viz);
// add other default values, might need to generate this better
Json::Value& materials = mcell[KEY_MATERIALS];
Json::Value& material_dict = materials[KEY_MATERIAL_DICT];
if (used_colors.empty()) {
// need at least one material (unused)
Json::Value& membrane = material_dict[KEY_VALUE_MEMBRANE];
Json::Value& diffuse_color = membrane[KEY_DIFFUSE_COLOR];
diffuse_color[KEY_R] = DEFAULT_OBJECT_COLOR_COMPONENT;
diffuse_color[KEY_G] = DEFAULT_OBJECT_COLOR_COMPONENT;
diffuse_color[KEY_B] = DEFAULT_OBJECT_COLOR_COMPONENT;
diffuse_color[KEY_A] = DEFAULT_OBJECT_ALPHA;
}
else {
for (rgba_t color: used_colors) {
string name = DMUtils::color_to_mat_name(color);
Json::Value& mat = material_dict[name];
Json::Value& diffuse_color = mat[KEY_DIFFUSE_COLOR];
double r, g, b, a;
Geometry::rgba_to_components(color, r, g, b, a);
diffuse_color[KEY_R] = r;
diffuse_color[KEY_G] = g;
diffuse_color[KEY_B] = b;
diffuse_color[KEY_A] = a;
}
}
// diverse settings not read from the mcell4 state
// --- mol_viz ---
Json::Value& mol_viz = mcell[KEY_MOL_VIZ];
DMUtils::add_version(mol_viz, VER_DM_2015_04_13_1700);
mol_viz[KEY_MANUAL_SELECT_VIZ_DIR] = false;
mol_viz[KEY_FILE_START_INDEX] = 0;
mol_viz[KEY_SEED_LIST] = Json::Value(Json::arrayValue); // empty array
Json::Value& color_list = mol_viz[KEY_COLOR_LIST];
DMUtils::append_triplet(color_list, 0.8, 0.0, 0.0);
DMUtils::append_triplet(color_list, 0.0, 0.8, 0.0);
DMUtils::append_triplet(color_list, 0.0, 0.0, 0.8);
DMUtils::append_triplet(color_list, 0.0, 0.8, 0.8);
DMUtils::append_triplet(color_list, 0.8, 0.0, 0.8);
DMUtils::append_triplet(color_list, 0.8, 0.8, 0.0);
DMUtils::append_triplet(color_list, 1.0, 1.0, 1.0);
DMUtils::append_triplet(color_list, 0.0, 0.0, 0.0);
mol_viz[KEY_ACTIVE_SEED_INDEX] = 0;
mol_viz[KEY_FILE_INDEX] = 959; // don't know what this means
mol_viz[KEY_FILE_NUM] = 1001; // don't know what this means
mol_viz[KEY_VIZ_ENABLE] = true;
mol_viz[KEY_FILE_NAME] = "";
mol_viz[KEY_COLOR_INDEX] = 0;
mol_viz[KEY_RENDER_AND_SAVE] = false;
mol_viz[KEY_FILE_STEP_INDEX] = 1; // don't know what this means
mol_viz[KEY_FILE_STOP_INDEX] = 1000; // don't know what this means
mol_viz[KEY_FILE_DIR] = ""; // does this need to be set?
mol_viz[KEY_VIZ_LIST] = Json::Value(Json::arrayValue); // empty array
// --- parameter_system ---
Json::Value& parameter_system = mcell[KEY_PARAMETER_SYSTEM];
parameter_system[KEY_MODEL_PARAMETERS] = Json::Value(Json::ValueType::objectValue); // empty dict
// --- scripting ---
Json::Value& scripting = mcell[KEY_SCRIPTING];
DMUtils::add_version(scripting, VER_DM_2017_11_30_1830);
scripting[KEY_SCRIPTING_LIST] = Json::Value(Json::arrayValue);
scripting[KEY_SCRIPT_TEXTS] = Json::Value(Json::objectValue);
scripting[KEY_DM_INTERNAL_FILE_NAME] = "";
scripting[KEY_FORCE_PROPERTY_UPDATE] = true;
scripting[KEY_DM_EXTERNAL_FILE_NAME] = "";
scripting[KEY_IGNORE_CELLBLENDER_DATA] = false;
// --- simulation_control ---
Json::Value& simulation_control = mcell[KEY_SIMULATION_CONTROL];
simulation_control[KEY_EXPORT_FORMAT] = VALUE_MCELL_MDL_MODULAR;
mcell[KEY_MODEL_LANGUAGE] = VALUE_MCELL4;
mcell[KEY_USE_BNG_UNITS] = config.use_bng_units;
Json::Value& blender_version = mcell[KEY_BLENDER_VERSION];
blender_version.append(Json::Value(BLENDER_VERSION[0]));
blender_version.append(Json::Value(BLENDER_VERSION[1]));
blender_version.append(Json::Value(BLENDER_VERSION[2]));
}
static std::string bool_warning_level_to_str(const bool v) {
if (v) {
return VALUE_WARNING;
}
else {
return VALUE_IGNORED;
}
}
static std::string warning_level_to_str(const API::WarningLevel v) {
switch (v) {
case API::WarningLevel::ERROR:
return VALUE_ERROR;
case API::WarningLevel::WARNING:
return VALUE_WARNING;
case API::WarningLevel::IGNORE:
return VALUE_IGNORED;
default:
assert(false);
return "invalid";
}
}
void World::initialization_to_data_model(Json::Value& mcell_node) const {
// only setting defaults for now, most of these values are not used in mcell4
// --- initialization ---
Json::Value& initialization = mcell_node[KEY_INITIALIZATION];
DMUtils::add_version(initialization, VER_DM_2017_11_18_0130);
// time step will most probably use rounded values, therefore we don't have to use full precision here
initialization[KEY_TIME_STEP] = f_to_str(config.time_unit, 8);
initialization[KEY_ITERATIONS] = to_string(total_iterations);
if (!cmp_eq(config.rxn_radius_3d, config.get_default_rxn_radius_3d())) {
initialization[KEY_INTERACTION_RADIUS] = f_to_str(config.rxn_radius_3d * config.length_unit);
}
else {
// keep default value
initialization[KEY_INTERACTION_RADIUS] = "";
}
initialization[KEY_ACCURATE_3D_REACTIONS] = true;
initialization[KEY_RADIAL_SUBDIVISIONS] = "";
initialization[KEY_RADIAL_DIRECTIONS] = "";
initialization[KEY_CENTER_MOLECULES_ON_GRID] = !config.randomize_smol_pos;
initialization[KEY_COMMAND_OPTIONS] = "";
initialization[KEY_EXPORT_ALL_ASCII] = true; // for testing, cellblender generates false as default
initialization[KEY_MICROSCOPIC_REVERSIBILITY] = VALUE_OFF;
initialization[KEY_TIME_STEP_MAX] = "";
// reversed computation from mcell3's init_reactions
pos_t vsd = sqrt_p(config.vacancy_search_dist2) * config.length_unit;
initialization[KEY_VACANCY_SEARCH_DISTANCE] = f_to_str(vsd);
initialization[KEY_SPACE_STEP] = "";
initialization[KEY_SURFACE_GRID_DENSITY] = f_to_str(config.grid_density);
// --- warnings ---
Json::Value& warnings = initialization[KEY_WARNINGS];
warnings[KEY_MISSED_REACTION_THRESHOLD] = "0.001";
warnings[KEY_LIFETIME_TOO_SHORT] = VALUE_WARNING;
warnings[KEY_LIFETIME_THRESHOLD] = "50";
warnings[KEY_ALL_WARNINGS] = VALUE_INDIVIDUAL;
warnings[KEY_MISSED_REACTIONS] = VALUE_WARNING;
warnings[KEY_NEGATIVE_DIFFUSION_CONSTANT] = VALUE_WARNING;
warnings[KEY_NEGATIVE_REACTION_RATE] = VALUE_WARNING;
warnings[KEY_HIGH_PROBABILITY_THRESHOLD] = "1";
warnings[KEY_DEGENERATE_POLYGONS] = VALUE_WARNING;
warnings[KEY_USELESS_VOLUME_ORIENTATION] = VALUE_WARNING;
warnings[KEY_HIGH_REACTION_PROBABILITY] =
bool_warning_level_to_str(config.warnings.warn_on_bimol_rxn_probability_over_05_less_1);
warnings[KEY_MOLECULE_PLACEMENT_FAILURE] = warning_level_to_str(config.molecule_placement_failure);
warnings[KEY_LARGE_MOLECULAR_DISPLACEMENT] = VALUE_WARNING;
warnings[KEY_MISSING_SURFACE_ORIENTATION] = VALUE_ERROR;
// --- notifications ---
Json::Value& notifications = initialization[KEY_NOTIFICATIONS];
notifications[KEY_SPECIES_REACTIONS_REPORT] = config.rxn_and_species_report;
notifications[KEY_FILE_OUTPUT_REPORT] = false;
notifications[KEY_ALL_NOTIFICATIONS] = VALUE_INDIVIDUAL;
notifications[KEY_PROBABILITY_REPORT_THRESHOLD] = "0";
notifications[KEY_BOX_TRIANGULATION_REPORT] = false;
notifications[KEY_RELEASE_EVENT_REPORT] = true;
notifications[KEY_PROGRESS_REPORT] = true;
notifications[KEY_MOLECULE_COLLISION_REPORT] = false;
notifications[KEY_ITERATION_REPORT] = true;
notifications[KEY_FINAL_SUMMARY] = true;
notifications[KEY_VARYING_PROBABILITY_REPORT] = config.notifications.rxn_probability_changed;
notifications[KEY_PROBABILITY_REPORT] = VALUE_ON;
notifications[KEY_PARTITION_LOCATION_REPORT] = false;
notifications[KEY_DIFFUSION_CONSTANT_REPORT] = VALUE_BRIEF;
// --- partitions ---
Json::Value& partitions = initialization[KEY_PARTITIONS];
// NOTE: mcell3_world_converter extends the partition info, so the result will be bigger than input
// probably ok because we don't plan long-term MDL support without previous conversion
partitions[KEY_INCLUDE] = true;
partitions[KEY_RECURSION_FLAG] = false;
const Vec3& origin = (config.partition0_llf * config.length_unit);
pos_t length = config.partition_edge_length * config.length_unit;
partitions[KEY_X_START] = f_to_str(origin.x);
partitions[KEY_X_END] = f_to_str(origin.x + length);
partitions[KEY_Y_START] = f_to_str(origin.y);
partitions[KEY_Y_END] = f_to_str(origin.y + length);
partitions[KEY_Z_START] = f_to_str(origin.z);
partitions[KEY_Z_END] = f_to_str(origin.z + length);
pos_t step = config.subpart_edge_length * config.length_unit;
string step_str = f_to_str(step);
partitions[KEY_X_STEP] = step_str;
partitions[KEY_Y_STEP] = step_str;
partitions[KEY_Z_STEP] = step_str;
}
void World::export_data_layout() const {
Json::Value root;
root[KEY_VERSION] = 2;
root[KEY_MCELL4_MODE] = true;
Json::Value& data_layout = root[KEY_DATA_LAYOUT];
Json::Value dir;
dir.append(VALUE_DIR);
Json::Value dir_value;
dir_value.append(".");
dir.append(dir_value);
data_layout.append(dir);
// TODO: to go through viz and rxn outputs to
// figure out what the directories should be, for now using the defaults
Json::Value file_type;
file_type.append(VALUE_FILE_TYPE);
Json::Value file_type_contents;
file_type_contents.append(VALUE_REACT_DATA);
file_type_contents.append(VALUE_VIZ_DATA);
file_type.append(file_type_contents);
data_layout.append(file_type);
Json::Value seed;
seed.append(VALUE_SEED);
Json::Value seed_value;
seed_value.append(to_string(config.initial_seed));
seed.append(seed_value);
data_layout.append(seed);
Json::StreamWriterBuilder wbuilder;
wbuilder["indentation"] = " ";
wbuilder.settings_["precision"] = 15; // this is the precision that is used by mdl_to_data_model.py script
wbuilder.settings_["precisionType"] = "significant";
std::string document = Json::writeString(wbuilder, root);
// write result into a file
ofstream res_file(DEFAULT_DATA_LAYOUT_FILENAME);
if (res_file.is_open())
{
// maybe enable this message only in some verbose mode
cout << "Generated file " << DEFAULT_DATA_LAYOUT_FILENAME << " for plotting in CellBlender.\n";
res_file << document;
res_file.close();
}
else {
cout << "Unable to open file " << DEFAULT_DATA_LAYOUT_FILENAME << " for writing.\n";
}
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/mcell3_world_converter.cpp | .cpp | 72,818 | 1,947 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <stdarg.h>
#include <stdlib.h>
#include <set>
#include "bng/bng.h"
#include "logging.h"
#include "mcell_structs.h" // need all defines
#include "mcell3_world_converter.h"
#include "world.h"
#include "release_event.h"
#include "clamp_release_event.h"
#include "diffuse_react_event.h"
#include "viz_output_event.h"
#include "mol_or_rxn_count_event.h"
#include "count_buffer.h"
#include "datamodel_defines.h"
#include "dump_state.h"
using namespace std;
using namespace BNG;
//#define EXTRA_LOGGING
#ifdef EXTRA_LOGGING
#define LOG(msg) cout << msg << "\n"
#else
#define LOG(msg) do { } while (0)
#endif
// checking major conversion blocks
#define CHECK(cond) do { if(!(cond)) { mcell_log_conv_error("Returning from %s after conversion error.\n", __FUNCTION__); return false; } } while (0)
// checking assumptions
#define CHECK_PROPERTY(cond) do { if(!(cond)) { mcell_log_conv_error("Expected '%s' is false. (%s - %s:%d)\n", #cond, __FUNCTION__, __FILE__, __LINE__); assert(false); return false; } } while (0)
// asserts - things that can never occur and will 'never' be supported
void mcell_log_conv_warning(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
string fmt_w_warning = string ("Conversion warning: ") + fmt;
mcell_logv_raw(fmt_w_warning.c_str(), args);
va_end(args);
}
void mcell_log_conv_error(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
string fmt_w_warning = string ("Conversion error: ") + fmt;
mcell_logv_raw(fmt_w_warning.c_str(), args);
va_end(args);
}
namespace MCell {
static const char* get_sym_name(const sym_entry *s) {
assert(s != nullptr);
assert(s->name != nullptr);
return s->name;
}
static mat4x4 t_matrix_to_mat4x4(const double src[4][4]) {
mat4x4 res;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
res[x][y] = src[x][y];
}
}
return res;
}
void MCell3WorldConverter::reset() {
delete world;
world = nullptr;
mcell3_species_id_map.clear();
}
bool MCell3WorldConverter::convert(volume* s) {
world = new World(callbacks);
CHECK(convert_simulation_setup(s));
CHECK(convert_species(s));
world->create_initial_surface_region_release_event(); // cannot fail
CHECK(convert_rxns(s));
mcell_log("Creating initial partition...");
// at this point, we need to create the first (and for now the only) partition
// create initial partition with center at 0,0,0
partition_id_t index = world->add_partition(world->config.partition0_llf);
assert(index == PARTITION_ID_INITIAL);
mcell_log("Converting geometry...");
// convert geometry already puts geometry objects into partitions
CHECK(convert_geometry_objects(s));
// release events require wall information
CHECK(convert_release_events(s));
CHECK(convert_viz_output_events(s));
CHECK(convert_mol_or_rxn_count_events(s));
update_and_schedule_concentration_clamps();
return true;
}
static double get_largest_abs_value(const vector3& v) {
double max = 0;
if (fabs_f(v.x) > max) {
max = fabs_f(v.x);
}
if (fabs_f(v.y) > max) {
max = fabs_f(v.y);
}
if (fabs_f(v.z) > max) {
max = fabs_f(v.z);
}
return max;
}
static double get_largest_distance_from_center(const vector3& llf, const vector3& urb) {
double max1 = get_largest_abs_value(llf);
double max2 = get_largest_abs_value(urb);
return max1 > max2 ? max1 : max2;
}
static uint get_even_higher_or_same_value(const uint val) {
if (val % 2 == 0) {
return val;
}
else {
return val + 1;
}
}
static double get_partition_edge_length(const World* world, const double largest_mcell3_distance_from_center) {
// some MCell models have their partition boundary set exactly. we need to add a bit of margin
return (largest_mcell3_distance_from_center + (double)PARTITION_EDGE_EXTRA_MARGIN_UM / world->config.length_unit) * 2 ;
}
static API::WarningLevel convert_warning_level(enum warn_level_t l) {
switch (l) {
case WARN_COPE:
return API::WarningLevel::IGNORE;
case WARN_WARN:
return API::WarningLevel::WARNING;
case WARN_ERROR:
return API::WarningLevel::ERROR;
default:
assert(false);
return API::WarningLevel::ERROR;
}
}
/**
* Partition conversion greatly simplifies the variability in MCell3 where the partition can be an arbitrary box.
* Here, it must be a cube and the first partition must be placed the way so that the coordinate origin
* is in its corner.
* The assumption (quite possibly premature) is that there will be big systems that are simulated
* and the whole space will be split into multiple partitions anyway. And we do not care about the
* number of subpartitions, they should only take up memory, not computation time.
*/
bool MCell3WorldConverter::convert_simulation_setup(volume* s) {
// TODO_CONVERSION: many items are not checked
world->total_iterations = s->iterations;
world->config.time_unit = s->time_unit;
world->config.initial_time = TIME_SIMULATION_START;
world->config.initial_iteration = 0;
world->config.length_unit = s->length_unit;
world->config.grid_density = s->grid_density;
world->config.rxn_radius_3d = s->rx_radius_3d;
world->config.vacancy_search_dist2 = s->vacancy_search_dist2; // unit was already recomputed
world->config.initial_seed = s->seed_seq;
world->config.molecule_placement_failure = convert_warning_level(s->notify->mol_placement_failure);
world->rng = *s->rng;
pos_t sp_len;
// use partition settings supplied by user?
if (s->partitions_initialized) {
// using that the mcell's bounding box if it is bigger than the partition
if (
s->partition_llf.x >= s->bb_llf.x || s->bb_urb.x >= s->partition_urb.x ||
s->partition_llf.y >= s->bb_llf.y || s->bb_urb.y >= s->partition_urb.y ||
s->partition_llf.z >= s->bb_llf.z || s->bb_urb.z >= s->partition_urb.z
) {
// just to inform the user
mcell_log(
"Warning: Partitioning was specified, but it is smaller than the automatically determined bounding box. "
"You may need to increase the partition size if get an error later that a vertex does not fit any partition."
);
double lu = s->length_unit;
mcell_log("Bounding box in microns: [ %f, %f, %f ], [ %f, %f, %f ]",
s->bb_llf.x*lu, s->bb_llf.y*lu, s->bb_llf.z*lu, s->bb_urb.x*lu, s->bb_urb.y*lu, s->bb_urb.z*lu);
mcell_log("Partition box in microns: [ %f, %f, %f ], [ %f, %f, %f ]",
s->partition_llf.x*lu, s->partition_llf.y*lu, s->partition_llf.z*lu, s->partition_urb.x*lu, s->partition_urb.y*lu, s->partition_urb.z*lu);
}
CHECK_PROPERTY(s->partition_urb.x > s->partition_llf.x);
CHECK_PROPERTY(s->partition_urb.y > s->partition_llf.y);
CHECK_PROPERTY(s->partition_urb.z > s->partition_llf.z);
// determine partition 0 llf origin
// it must be placed in the way that subpartitions boundaries go through (0, 0, 0)
// and in the same time the partition 0 llf origin is on a multiple of the partition length
// first we need to determine the subpart length - use the value that user specified in the PARTITION_* section
Vec3 margin = Vec3(PARTITION_EDGE_EXTRA_MARGIN_UM/world->config.length_unit);
Vec3 mcell3_llf_w_margin = Vec3(s->partition_llf) - margin;
Vec3 mcell3_urb_w_margin = Vec3(s->partition_urb) + margin;
Vec3 mcell3_box_size = mcell3_urb_w_margin - mcell3_llf_w_margin;
IVec3 num_subparts = IVec3(s->num_subparts);
// the shortest subpart step will be used
// value of world->config.subpartition_edge_length is set in SimulationConfig::init
sp_len = min3(mcell3_box_size / Vec3(num_subparts));
uint tentative_subparts = max3(mcell3_box_size) / sp_len;
if (tentative_subparts > MAX_SUBPARTS_PER_PARTITION) {
cout <<
"Approximate number of subpartitions " << tentative_subparts <<
" is too high, lowering it to a limit of " << MAX_SUBPARTS_PER_PARTITION << ".\n";
sp_len = world->config.partition_edge_length / MAX_SUBPARTS_PER_PARTITION;
}
// origin of the initial partition
world->config.partition0_llf = floor_to_multiple_allow_negative_p(mcell3_llf_w_margin, sp_len);
Vec3 llf_moved = mcell3_llf_w_margin - world->config.partition0_llf;
Vec3 box_size_enlarged = mcell3_box_size + llf_moved;
// size of the partition
Vec3 box_size_ceiled = ceil_to_multiple_p(box_size_enlarged, sp_len);
world->config.partition_edge_length = max3(box_size_ceiled);
mcell_log("Using manually specified partition size (with margin): %f.",
(double)world->config.partition_edge_length * world->config.length_unit);
// and how many subparts per dimension
// the rounding is needed because we can get a result like .99999999 from the division
world->config.num_subparts_per_partition_edge = round_f(world->config.partition_edge_length / sp_len);
}
else {
CHECK_PROPERTY(s->bb_urb.x >= s->bb_llf.x);
CHECK_PROPERTY(s->bb_urb.y >= s->bb_llf.y);
CHECK_PROPERTY(s->bb_urb.z >= s->bb_llf.z);
// use MCell's bounding box, however, we must make a cube out of it
double largest_mcell3_distance_from_center = get_largest_distance_from_center(s->bb_llf, s->bb_urb);
double auto_length = get_partition_edge_length(world, largest_mcell3_distance_from_center);
if (auto_length > PARTITION_EDGE_LENGTH_DEFAULT_UM / world->config.length_unit) {
world->config.partition_edge_length = auto_length;
mcell_log("Automatically determined partition size: %f.",
(double)auto_length * world->config.length_unit);
}
else {
world->config.partition_edge_length = PARTITION_EDGE_LENGTH_DEFAULT_UM / world->config.length_unit;
mcell_log("Automatically determined partition size %f is smaller than default %f, using default.",
(double)auto_length * world->config.length_unit, PARTITION_EDGE_LENGTH_DEFAULT_UM);
}
// nx_parts counts the number of boundaries, not subvolumes, also, there are always 2 extra subvolumes on the sides in mcell3
int max_n_p_parts = max3_i(IVec3(s->nx_parts, s->ny_parts, s->nz_parts));
world->config.num_subparts_per_partition_edge = get_even_higher_or_same_value(max_n_p_parts - 3);
world->config.partition0_llf = Vec3(-world->config.partition_edge_length/2);
// temporary, for the check after init
sp_len = world->config.partition_edge_length / world->config.num_subparts_per_partition_edge;
}
Vec3 partition0_llf_microns = world->config.partition0_llf * Vec3(s->length_unit);
Vec3 partition0_urb_microns = partition0_llf_microns + Vec3(world->config.partition_edge_length * s->length_unit);
mcell_log("MCell4 partition bounding box in microns: [ %f, %f, %f ], [ %f, %f, %f ], with %d subpartitions per dimension",
partition0_llf_microns.x, partition0_llf_microns.y, partition0_llf_microns.z,
partition0_urb_microns.x, partition0_urb_microns.y, partition0_urb_microns.z,
(int)world->config.num_subparts_per_partition_edge
);
world->config.randomize_smol_pos = s->randomize_smol_pos; // set in MDL using negated value of CENTER_MOLECULES_ON_GRID
CHECK_PROPERTY(s->dynamic_geometry_molecule_placement == 0
&& "DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT '=' NEAREST_TRIANGLE is not supported yet"
);
world->config.use_expanded_list = s->use_expanded_list;
// check is done in MCell3 initialization code
world->config.check_overlapped_walls = s->with_checks_flag;
// compute other constants
// may change world->config.subpartition_edge_length
world->config.init();
if (world->config.rxn_radius_3d * 2 * POS_SQRT2 > world->config.subpart_edge_length) {
mcell_error("Reaction radius multiplied by sqrt(2) %f must be less than half of subpartition edge length %f.",
world->config.rxn_radius_3d * world->config.length_unit * POS_SQRT2,
world->config.subpart_edge_length * world->config.length_unit / 2.0
);
}
return true;
}
// "" as expected_name is that the name is not checked
bool check_meta_object(geom_object* o, string expected_name = "") {
assert(o != nullptr);
if (expected_name != "") {
CHECK_PROPERTY(get_sym_name(o->sym) == expected_name);
}
else {
// just try that the name is set in debug mode
get_sym_name(o->sym);
}
// root->last_name - not checked, contains some nonsense anyway
CHECK_PROPERTY(o->object_type == META_OBJ);
CHECK_PROPERTY(o->contents == nullptr);
CHECK_PROPERTY(o->num_regions == 0);
CHECK_PROPERTY(o->regions == nullptr);
CHECK_PROPERTY(o->walls == nullptr);
CHECK_PROPERTY(o->wall_p == nullptr);
CHECK_PROPERTY(o->vertices == nullptr);
CHECK_PROPERTY(o->total_area == 0);
CHECK_PROPERTY(o->n_tiles == 0);
CHECK_PROPERTY(o->n_occupied_tiles == 0);
CHECK_PROPERTY(o->n_occupied_tiles == 0);
CHECK_PROPERTY(t_matrix_to_mat4x4(o->t_matrix) == mat4x4(1) && "only identity matrix for now");
// root->is_closed - not checked
CHECK_PROPERTY(o->periodic_x == false);
CHECK_PROPERTY(o->periodic_y == false);
CHECK_PROPERTY(o->periodic_z == false);
return true;
}
// inst must be a meta object, converts all contained geometrical objects
bool MCell3WorldConverter::convert_geometry_meta_object_recursively(volume* s, geom_object* meta_inst) {
CHECK_PROPERTY(check_meta_object(meta_inst));
// this is the name of the INSTANTIATE section
std::string instantiate_name = get_sym_name(meta_inst->sym);
// walls reference each other, therefore we must first create
// empty wall objects in partitions,
geom_object* curr_obj = meta_inst->first_child;
while (curr_obj != nullptr) {
if (curr_obj->object_type == POLY_OBJ) {
create_uninitialized_walls_for_polygonal_object(curr_obj);
}
curr_obj = curr_obj->next;
}
// once all wall were created and mapping established,
// we can fill-in all objects
curr_obj = meta_inst->first_child;
while (curr_obj != nullptr) {
if (curr_obj->object_type == POLY_OBJ) {
CHECK(convert_polygonal_object(curr_obj, instantiate_name));
}
else if (curr_obj->object_type == META_OBJ) {
convert_geometry_meta_object_recursively(s, curr_obj);
}
else if (curr_obj->object_type == REL_SITE_OBJ) {
// ignored
}
else {
mcell_error(
"Unexpected type of object %d with name %s.",
(int)curr_obj->object_type, get_sym_name(curr_obj->sym)
);
}
curr_obj = curr_obj->next;
}
return true;
}
bool MCell3WorldConverter::convert_geometry_objects(volume* s) {
geom_object* root_instance = s->root_instance;
CHECK_PROPERTY(check_meta_object(root_instance, "WORLD_INSTANCE"));
CHECK_PROPERTY(root_instance->next == nullptr);
for (geom_object* instantiate_obj = root_instance->first_child; instantiate_obj != nullptr; instantiate_obj = instantiate_obj->next) {
CHECK_PROPERTY(check_meta_object(instantiate_obj));
convert_geometry_meta_object_recursively(s, instantiate_obj);
} // for each scene/INSTANTIATE section
// check that our reinit function works correctly
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
#ifdef DEBUG_EXTRA_CHECKS
for (wall_index_t i = 0; i < p.get_wall_count(); i++) {
Wall& w = p.get_wall(i);
for (edge_index_t k = 0; k < EDGES_IN_TRIANGLE; k++) {
Edge& e = w.edges[k];
e.debug_check_values_are_uptodate(p);
}
}
#endif
for (GeometryObject& obj: p.get_geometry_objects()) {
obj.initialize_is_fully_transparent(p);
}
// check overlapped walls
// uses random generator state
if (world->config.check_overlapped_walls) {
bool ok = world->check_for_overlapped_walls();
if (!ok) {
mcell_error("Walls in geometry overlap, more details were printed in the previous message.");
}
}
world->get_partition(PARTITION_ID_INITIAL).finalize_walls();
return true;
}
// we do not check anything that might not be supported from the mcell3 side,
// the actual checks are in convert_polygonal_object
void MCell3WorldConverter::create_uninitialized_walls_for_polygonal_object(const geom_object* o) {
GeometryObject obj;
// create objects for each wall
for (int i = 0; i < o->n_walls; i++) {
wall* w = o->wall_p[i];
// which partition?
partition_id_t partition_id = world->get_partition_index(*w->vert[0]);
if (partition_id == PARTITION_ID_INVALID) {
Vec3 v(*w->vert[0]);
v = v * Vec3(world->config.length_unit);
mcell_error("Vertex %s does not fit any partition.", v.to_string().c_str());
}
// check that the remaining vertices are in the same partition
for (uint k = 1; k < VERTICES_IN_TRIANGLE; k++) {
partition_id_t curr_partition_index = world->get_partition_index(*w->vert[k]);
if (partition_id != curr_partition_index) {
Vec3 pos(*w->vert[k]);
pos = pos * Vec3(world->config.length_unit);
mcell_error("Whole walls must be in a single partition is for now, vertex %s is out of bounds", pos.to_string().c_str());
}
}
// create the wall in that partition but do not set anything else yet
Partition& p = world->get_partition(partition_id);
Wall& new_wall = p.add_uninitialized_wall(world->get_next_wall_id());
// remember mapping
add_mcell4_wall_index_mapping(w, PartitionWallIndexPair(partition_id, new_wall.index));
}
}
bool MCell3WorldConverter::convert_wall_and_update_regions(
const wall* w, GeometryObject& object,
const region_list* rl
) {
PartitionWallIndexPair wall_pindex = get_mcell4_wall_index(w);
Partition& p = world->get_partition(wall_pindex.first);
Wall& wall = p.get_wall(wall_pindex.second);
// bidirectional mapping
wall.object_id = object.id;
wall.object_index = object.index;
object.wall_indices.push_back(wall.index);
wall.side = w->side;
for (uint i = 0; i < VERTICES_IN_TRIANGLE; i++) {
// this vertex was inserted into the same partition as the whole object
PartitionVertexIndexPair vert_pindex = get_mcell4_vertex_index(w->vert[i]);
assert(wall_pindex.first == vert_pindex.first);
wall.vertex_indices[i] = vert_pindex.second;
}
wall.uv_vert1_u = w->uv_vert1_u;
wall.uv_vert2 = w->uv_vert2;
wall.area = w->area;
wall.normal = w->normal;
wall.unit_u = w->unit_u;
wall.unit_v = w->unit_v;
wall.distance_to_origin = w->d;
wall.wall_constants_initialized = true;
for (uint i = 0; i < EDGES_IN_TRIANGLE; i++) {
edge* e = w->edges[i];
assert(e != nullptr);
Edge& edge = wall.edges[i];
if (e->forward != nullptr) {
edge.forward_index = get_mcell4_wall_index(e->forward).second;
}
else {
edge.forward_index = WALL_INDEX_INVALID;
}
if (e->backward != nullptr) {
edge.backward_index = get_mcell4_wall_index(e->backward).second;
}
else {
edge.backward_index = WALL_INDEX_INVALID;
}
edge.set_translate(e->translate);
edge.set_cos_theta(e->cos_theta);
edge.set_sin_theta(e->sin_theta);
// e->edge_num_used_for_init is valid only if both fwd and backw walls are present
if (e->forward != nullptr && e->backward != nullptr) {
edge.edge_num_used_for_init = e->edge_num_used_for_init; // added only for mcell4
}
else {
edge.edge_num_used_for_init = EDGE_INDEX_INVALID;
}
}
for (uint i = 0; i < EDGES_IN_TRIANGLE; i++) {
if (w->nb_walls[i] != nullptr) {
#ifndef NDEBUG
PartitionWallIndexPair pindex = get_mcell4_wall_index(w->nb_walls[i]);
assert(pindex.first == wall_pindex.first && "Neighbors must be in the same partition for now");
#endif
wall.nb_walls[i] = get_mcell4_wall_index(w->nb_walls[i]).second;
}
else {
wall.nb_walls[i] = WALL_INDEX_INVALID;
}
}
// CHECK_PROPERTY(w->grid == nullptr); // don't care, we will create grid if needed
// walls use some of the flags used by species
if (!
(w->flags == COUNT_CONTENTS ||
w->flags == COUNT_RXNS ||
w->flags == (COUNT_CONTENTS | COUNT_RXNS) ||
w->flags == (COUNT_CONTENTS | COUNT_ENCLOSED) ||
w->flags == (COUNT_RXNS | COUNT_ENCLOSED) ||
w->flags == (COUNT_CONTENTS | COUNT_RXNS | COUNT_ENCLOSED))
) {
if ((w->flags | COUNT_TRIGGER) != 0) {
mcell_error("A wall uses a COUNT_TRIGGER flag, this is not supported in MCell4. "
"Use a wall hit or reaction callback in Python MCell4 code instead.", w->flags);
}
else {
mcell_error("Unsupported combination of wall flags 0x%x for MCell4, see MCell code "
"(species flags in mcell_structs.h) for more details.", w->flags);
}
}
// now let's handle regions
std::set<species_id_t> region_species_from_mcell3;
for (const region_list *r = rl; r != NULL; r = r->next) {
region* reg = r->reg;
assert(reg != nullptr);
// are we in this region?
if (get_bit(reg->membership, wall.side)) {
auto pindex = get_mcell4_region_index(reg);
CHECK_PROPERTY(pindex.first == wall_pindex.first);
region_index_t region_index = pindex.second;
wall.regions.insert_unique(region_index);
object.regions.insert(region_index);
// add our wall to the region
Region& mcell4_reg = p.get_region(region_index);
if (mcell4_reg.species_id != SPECIES_ID_INVALID) {
region_species_from_mcell3.insert(mcell4_reg.species_id);
}
// which of our walls are region edges?
set<edge_index_t> edge_indices;
if (reg->boundaries != nullptr) {
for (uint i = 0; i < EDGES_IN_TRIANGLE; i++) {
edge* e = w->edges[i];
uint keyhash = (unsigned int)(intptr_t)(e);
void* key = (void *)(e);
if (pointer_hash_lookup(reg->boundaries, key, keyhash)) {
edge_indices.insert(i);
}
}
}
assert(mcell4_reg.walls_and_edges.count(wall.index) == 0);
mcell4_reg.walls_and_edges[wall.index] = edge_indices;
}
}
// check that associated regions used the same 'surf_classes'/species
std::set<species_id_t> wall_species_from_mcell3;
for (surf_class_list *sl = w->surf_class_head; sl != nullptr; sl = sl->next) {
CHECK_PROPERTY(sl->surf_class != nullptr);
species_id_t surf_class_species_id = get_mcell4_species_id(sl->surf_class->species_id);
wall_species_from_mcell3.insert(surf_class_species_id);
// set concentration clamp walls (note: this might be a bit slow
for (ClampReleaseEvent* clamp: concentration_clamps) {
if (clamp->surf_class_species_id == surf_class_species_id) {
// cummulative area is updated when the clamp events are scheduled at the end of conversion
clamp->cumm_area_and_pwall_index_pairs.push_back(CummAreaPWallIndexPair(0, wall_pindex));
}
}
}
CHECK_PROPERTY(wall_species_from_mcell3 == region_species_from_mcell3);
return true;
}
bool MCell3WorldConverter::convert_region(Partition& p, const region* r, region_index_t& region_index) {
assert(r != nullptr);
Region new_region;
new_region.name = get_sym_name(r->sym);
LOG("Converting region " << new_region.name);
// u_int hashval; // ignored
// char *region_last_name; // ignored
// struct geom_object *parent; // ignored
CHECK_PROPERTY(r->element_list_head == nullptr); // should be used only at parse time
// r->membership - Each bit indicates whether the corresponding wall is in the region */
// and r->boundaries - edges of region are handled in convert_wall_and_update_regions
if (r->surf_class != nullptr) {
new_region.species_id = get_mcell4_species_id(r->surf_class->species_id);
}
else {
new_region.species_id = SPECIES_ID_INVALID;
}
CHECK_PROPERTY(r->region_has_all_elements || r->bbox == nullptr); // so far it can be set only to all-encopasing region
// CHECK_PROPERTY(r->area == 0); // ignored for now
// CHECK_PROPERTY(r->volume == 0); // ignored for now
// CHECK_PROPERTY(r->flags == 0); // ignored for now
// CHECK_PROPERTY(r->manifold_flag == 0); // ignored, do we care?
string parent_name = get_sym_name(r->parent->sym);
const GeometryObject* obj = world->get_partition(0).find_geometry_object_by_name(parent_name);
CHECK_PROPERTY(obj != nullptr);
new_region.geometry_object_id = obj->id;
new_region.id = world->get_next_region_id();
sm_dat* current_sm_dat = r->sm_dat_head;
while (current_sm_dat != nullptr) {
CHECK_PROPERTY(current_sm_dat->sm != nullptr);
species_id_t species_id = get_mcell4_species_id(current_sm_dat->sm->species_id);
if (current_sm_dat->quantity_type == SURFMOLNUM) {
// inserting from front because the order in r->sm_dat_head is reversed
new_region.initial_region_molecules.insert(
new_region.initial_region_molecules.begin(),
InitialSurfaceReleases(
species_id, current_sm_dat->orientation, true, (uint)current_sm_dat->quantity
)
);
}
else if (current_sm_dat->quantity_type == SURFMOLDENS) {
new_region.initial_region_molecules.insert(
new_region.initial_region_molecules.begin(),
InitialSurfaceReleases(
species_id, current_sm_dat->orientation, false, (double)current_sm_dat->quantity
)
);
}
else {
CHECK(false);
}
current_sm_dat = current_sm_dat->next;
}
region_index = p.add_region_and_set_its_index(new_region);
return true;
}
bool MCell3WorldConverter::convert_polygonal_object(const geom_object* o, const std::string& instantiate_name) {
// --- object ---
// we already checked in create_uninitialized_walls_for_polygonal_object
// that the specific walls of this fit into a single partition
// TODO_CONVERSION: improve this check for the whole object
partition_id_t partition_index = world->get_partition_index(*o->vertices[0]);
Partition& p = world->get_partition(partition_index);
GeometryObject& obj = p.add_uninitialized_geometry_object(world->get_next_geometry_object_id());
// o->next - ignored
// o->parent - ignored
CHECK_PROPERTY(o->first_child == nullptr);
CHECK_PROPERTY(o->last_child == nullptr);
obj.name = get_sym_name(o->sym);
obj.parent_name = instantiate_name;
// o->last_name - ignored
CHECK_PROPERTY(o->object_type == POLY_OBJ);
CHECK_PROPERTY(o->contents != nullptr); // ignored for now, not sure what is contained
CHECK_PROPERTY(o->n_walls == o->n_walls_actual); // ignored
CHECK_PROPERTY(o->walls == nullptr); // this is null for some reason
CHECK_PROPERTY(o->wall_p != nullptr);
// --- regions ---
uint reg_cnt = 0;
for (region_list *r = o->regions; r != NULL; r = r->next) {
region* reg = r->reg;
assert(reg != nullptr);
region_index_t region_index;
CHECK(convert_region(p, reg, region_index));
add_mcell4_region_index_mapping(reg, PartitionRegionIndexPair(partition_index, region_index));
reg_cnt++;
}
CHECK_PROPERTY(o->num_regions == reg_cnt);
// --- vertices ---
// to stay identical to mcell3, will use the exact number of vertices as in mcell3, for this to work,
// vector_ptr_to_vertex_index_map is a 'global' map for the whole conversion process
// one of the reasons to not to copy vertex coordinates is that they are shared among triangles of an object
// and when we move one vertex of the object, we transform all the triangles (walls) that use it
for (int i = 0; i < o->n_verts; i++) {
// insert vertex into the right partition and returns partition index and vertex index
vertex_index_t new_vertex_index = p.add_geometry_vertex(*o->vertices[i]);
add_mcell4_vertex_index_mapping(o->vertices[i], PartitionVertexIndexPair(partition_index, new_vertex_index));
}
// --- walls ---
// vertex info contains also partition indices when it is inserted into the
// world geometry
for (int i = 0; i < o->n_walls; i++) {
// uses precomputed map vector_ptr_to_vertex_index_map to transform vertices
// also uses mcell3_region_to_mcell4_index mapping to set that it belongs to a given region
CHECK(convert_wall_and_update_regions(o->wall_p[i], obj, o->regions));
}
// set encompassing region id - the region that has all the walls
for (region_index_t index: obj.regions) {
const Region& reg = p.get_region(index);
string reg_suffix = reg.name.substr(obj.name.size(), reg.name.size() - obj.name.size());
if (reg.walls_and_edges.size() == obj.wall_indices.size() &&
DMUtils::get_region_name(reg.name) == "ALL") {
assert(obj.encompassing_region_id == REGION_ID_INVALID);
obj.encompassing_region_id = reg.id;
}
}
release_assert(obj.encompassing_region_id != REGION_ID_INVALID);
// --- back to object ---
// CHECK_PROPERTY(o->n_tiles == 0); // don't care, we will create grid if needed
// CHECK_PROPERTY(o->n_occupied_tiles == 0);
// CHECK_PROPERTY(t_matrix_to_mat4x4(o->t_matrix) == mat4x4(1) && "only identity matrix for now"); // ignored, this tranformation was already applied
// root->is_closed - not checked
CHECK_PROPERTY(o->periodic_x == false);
CHECK_PROPERTY(o->periodic_y == false);
CHECK_PROPERTY(o->periodic_z == false);
return true;
}
static bool is_species_superclass(volume* s, species* spec) {
return spec == s->all_mols || spec == s->all_volume_mols || spec == s->all_surface_mols;
}
#ifdef SORT_MCELL4_SPECIES_BY_NAME
static bool compare_species_name_less(species* s1, species* s2) {
string n1 = get_sym_name(s1->sym);
string n2 = get_sym_name(s2->sym);
return n1 < n2;
}
#endif
bool MCell3WorldConverter::convert_species(volume* s) {
vector<species*> species_list;
species_list.resize(s->n_species);
for (int i = 0; i < s->n_species; i++) {
species_list[i] = s->species_list[i];
}
#ifdef SORT_MCELL4_SPECIES_BY_NAME
// copy all pointers except for superclasses and then sort
uint std_species_idx = 3;
for (int i = 0; i < s->n_species; i++) {
species* spec = s->species_list[i];
if (is_species_superclass(s, spec)) {
string n = get_sym_name(spec->sym);
if (n == ALL_MOLECULES) {
species_list[0] = spec;
}
else if (n == ALL_VOLUME_MOLECULES) {
species_list[1] = spec;
}
else if (n == ALL_SURFACE_MOLECULES) {
species_list[2] = spec;
}
else {
assert(false);
}
}
else {
assert(std_species_idx < species_list.size());
species_list[std_species_idx] = spec;
std_species_idx++;
}
}
sort(species_list.begin() + 3, species_list.end(), compare_species_name_less);
#endif
// TODO_CONVERSION: many items are not checked
for (int i = 0; i < s->n_species; i++) {
species* spec = species_list[i];
CHECK_PROPERTY(spec->sm_dat_head == nullptr &&
"MOLECULE_DENSITY and MOLECULE_NUMBER are not supported in DEFINE_SURFACE_CLASSES.");
Species new_species(world->bng_engine.get_data());
new_species.name = get_sym_name(spec->sym);
new_species.D = spec->D;
new_species.space_step = spec->space_step;
new_species.time_step = spec->time_step;
// remove some flags for check that are known to work in all cases
uint flags_check = spec->flags & ~REGION_PRESENT;
flags_check = flags_check & ~CANT_INITIATE;
flags_check = flags_check & ~COUNT_ENCLOSED;
flags_check = flags_check & ~COUNT_CONTENTS;
if (!(
is_species_superclass(s, spec)
|| flags_check == 0
|| flags_check == SPECIES_CPLX_MOL_FLAG_SURF
|| flags_check == SPECIES_CPLX_MOL_FLAG_REACTIVE_SURFACE
|| flags_check == SPECIES_FLAG_CAN_VOLVOL
|| flags_check == SPECIES_FLAG_CAN_VOLWALL
|| flags_check == SPECIES_FLAG_CAN_VOLSURF
|| flags_check == (SPECIES_FLAG_CAN_VOLVOL | SPECIES_FLAG_CAN_VOLSURF)
|| flags_check == (SPECIES_FLAG_CAN_VOLVOL | SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_FLAG_CAN_VOLWALL | SPECIES_FLAG_CAN_VOLSURF)
|| flags_check == (SPECIES_FLAG_CAN_VOLVOL | SPECIES_FLAG_CAN_VOLSURF | SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFSURF)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_REGION_BORDER)
|| flags_check == (SPECIES_FLAG_CAN_VOLVOL | SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_FLAG_CAN_VOLSURF)
|| flags_check == (SPECIES_FLAG_CAN_VOLVOL | SPECIES_FLAG_CAN_VOLSURF | SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_REGION_BORDER)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_VOLVOL)
|| flags_check == (SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFSURF)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFSURF | SPECIES_FLAG_CAN_VOLWALL)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFSURF | SPECIES_FLAG_CAN_REGION_BORDER)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFWALL | SPECIES_FLAG_CAN_REGION_BORDER)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFSURF | SPECIES_FLAG_CAN_SURFWALL | SPECIES_FLAG_CAN_REGION_BORDER)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFWALL)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFWALL | SPECIES_FLAG_CAN_SURFSURF)
|| flags_check == (SPECIES_CPLX_MOL_FLAG_SURF | SPECIES_FLAG_CAN_SURFWALL | SPECIES_FLAG_CAN_SURFSURF | SPECIES_FLAG_CAN_REGION_BORDER)
)) {
mcell_log("Warning: possibly unsupported combination of species flag for species %s: %s, it is recommended to check that MCell4 produces result similar to MCell3.\n",
new_species.name.c_str(), get_species_flags_string(spec->flags).c_str());
}
// copy all the flags from mcell3 except for a few one that we really don't need
uint cleaned_flags = spec->flags & ~REGION_PRESENT;
cleaned_flags = cleaned_flags & ~COUNT_CONTENTS;
cleaned_flags = cleaned_flags & ~COUNT_ENCLOSED;
new_species.set_flags(cleaned_flags);
CHECK_PROPERTY(spec->n_deceased == 0);
CHECK_PROPERTY(spec->cum_lifetime_seconds == 0);
if ((spec->flags & IS_SURFACE) != 0) {
if (spec->refl_mols != nullptr) {
// just one type for now
CHECK_PROPERTY(spec->refl_mols == nullptr || spec->refl_mols->next == nullptr);
// reflective surface, seems that this information is transformed into reactions, so we do no need to store anything else
// CHECK_PROPERTY(spec->refl_mols->orient == ORIENTATION_NONE); // ignored
}
}
else {
CHECK_PROPERTY(spec->refl_mols == nullptr);
}
// don't care about these, they will be defined as reactive surface reactions
// CHECK_PROPERTY(spec->transp_mols == nullptr);
// CHECK_PROPERTY(spec->absorb_mols == nullptr);
// CHECK_PROPERTY(spec->clamp_conc_mols == nullptr);
// we must add a complex instance as the single molecule type in the new species
// define a molecule type with no components
ElemMolType mol_type;
mol_type.name = new_species.name; // name of the mol type is the same as for our species
mol_type.D = spec->D;
if (spec->custom_time_step_from_mdl < 0) {
mol_type.custom_space_step = -spec->custom_time_step_from_mdl;
}
else if (spec->custom_time_step_from_mdl > 0) {
mol_type.custom_time_step = spec->custom_time_step_from_mdl;
}
mol_type.set_flag(BNG::SPECIES_MOL_FLAG_TARGET_ONLY, spec->flags & CANT_INITIATE);
if ((spec->flags & ON_GRID) == 0 && (spec->flags & IS_SURFACE) == 0) { //FIXME: ALL_SURF_MOLS have wrong flag
mol_type.set_is_vol();
}
else if ((spec->flags & ON_GRID) != 0) {
mol_type.set_is_surf();
}
else if ((spec->flags & IS_SURFACE) != 0) {
mol_type.set_is_reactive_surface();
}
else {
assert(false);
}
mol_type.compute_space_and_time_step(world->bng_engine.get_config());
elem_mol_type_id_t mol_type_id = world->bng_engine.get_data().find_or_add_elem_mol_type(mol_type);
ElemMol mol_inst;
mol_inst.elem_mol_type_id = mol_type_id;
new_species.elem_mols.push_back(mol_inst);
// and finally let's add our new species
new_species.finalize_species(world->config);
species_id_t new_species_id = world->get_all_species().find_or_add(new_species);
// set all species 'superclasses' ids
// these special species might be used in wall - surf|vol reactions
if (spec == s->all_mols) {
CHECK_PROPERTY(new_species.name == ALL_MOLECULES);
world->get_all_species().set_all_molecules_ids(new_species_id, mol_type_id);
}
else if (spec == s->all_volume_mols) {
CHECK_PROPERTY(new_species.name == ALL_VOLUME_MOLECULES);
world->get_all_species().set_all_volume_molecules_ids(new_species_id, mol_type_id);
}
else if (spec == s->all_surface_mols) {
CHECK_PROPERTY(new_species.name == ALL_SURFACE_MOLECULES);
world->get_all_species().get(new_species_id).set_flag(SPECIES_CPLX_MOL_FLAG_SURF);
world->get_all_species().set_all_surface_molecules_ids(new_species_id, mol_type_id);
}
// map for other conversion steps
mcell3_species_id_map[spec->species_id] = new_species_id;
}
return true;
}
// variable_rates_per_pathway is already resized to the number of pathways
static bool get_variable_rates(const t_func* prob_t, small_vector<small_vector<BNG::RxnRateInfo>>& variable_rates_per_pathway) {
for (const t_func* curr = prob_t; curr != nullptr; curr = curr->next) {
assert(curr->path >= 0 && curr->path < (int)variable_rates_per_pathway.size());
BNG::RxnRateInfo info;
info.time = curr->time;
info.rate_constant = curr->value_from_file;
assert(curr->path < (int)variable_rates_per_pathway.size());
variable_rates_per_pathway[curr->path].push_back(info);
}
// make sure that they are sorted by time
for (small_vector<BNG::RxnRateInfo>& rates: variable_rates_per_pathway) {
sort(variable_rates_per_pathway.begin(), variable_rates_per_pathway.end());
}
return true;
}
void MCell3WorldConverter::create_clamp_release_event(
const pathway* current_pathway, const RxnRule& rxn, const std::vector<species_id_t>& reactant_species_ids) {
ClampReleaseEvent* clamp_event = new ClampReleaseEvent(world);
if ((current_pathway->flags & PATHW_CLAMP_CONC) != 0) {
clamp_event->type = ClampType::CONCENTRATION;
}
else if ((current_pathway->flags & PATHW_CLAMP_FLUX) != 0) {
clamp_event->type = ClampType::FLUX;
}
else {
assert(false);
}
// run each timestep
clamp_event->event_time = 0;
clamp_event->periodicity_interval = 1;
// which species to clamp
assert(!world->bng_engine.get_all_species().get(reactant_species_ids[0]).is_reactive_surface());
clamp_event->species_id = reactant_species_ids[0];
assert(world->bng_engine.get_all_species().get(reactant_species_ids[1]).is_reactive_surface());
clamp_event->surf_class_species_id = reactant_species_ids[1];
// on which side
if (rxn.reactants[0].get_orientation() == 0 || rxn.reactants[1].get_orientation() == 0) {
clamp_event->orientation = 0;
}
else {
clamp_event->orientation =
(rxn.reactants[0].get_orientation() == rxn.reactants[1].get_orientation()) ? ORIENTATION_UP : ORIENTATION_DOWN;
}
// use the rxn rate for concentration and the rxn that destroys molecules will happen always
clamp_event->concentration = current_pathway->clamp_concentration;
concentration_clamps.push_back(clamp_event);
}
bool MCell3WorldConverter::convert_single_reaction(const rxn *mcell3_rx) {
// rx->next - handled in convert_reactions
// rx->sym->name - ignored, name obtained from pathway
CHECK_PROPERTY(
mcell3_rx->n_pathways >= 1
|| mcell3_rx->n_pathways == RX_REFLEC // reflections for surf mols
|| mcell3_rx->n_pathways == RX_TRANSP
|| mcell3_rx->n_pathways == RX_ABSORB_REGION_BORDER
); // limited for now
assert(mcell3_rx->cum_probs != nullptr);
// int *product_idx_aux - ignored, post-processing information
// u_int *product_idx - ignored, post-processing information
// struct species **players - ignored, might check it but will contain the same info as pathways
// NFSIM struct species ***nfsim_players; /* a matrix of the nfsim elements associated with each path */
// NFSIM short *geometries; /* Geometries of reactants/products */
// NFSIM short **nfsim_geometries; /* geometries of the nfsim geometries associated with each path */
CHECK_PROPERTY(mcell3_rx->n_occurred == 0);
CHECK_PROPERTY(mcell3_rx->n_skipped == 0);
small_vector<small_vector<BNG::RxnRateInfo>> variable_rates_per_pathway;
if (mcell3_rx->n_pathways > 0) {
variable_rates_per_pathway.resize(mcell3_rx->n_pathways);
get_variable_rates(mcell3_rx->prob_t, variable_rates_per_pathway);
}
else {
CHECK_PROPERTY(mcell3_rx->prob_t == nullptr);
}
int pathway_index = 0;
for (
pathway* current_pathway = mcell3_rx->pathway_head;
current_pathway != nullptr;
current_pathway = current_pathway->next) {
// --- pathway ---
// there can be a single reaction for absorb, reflect and transparent reactions
assert((pathway_index < mcell3_rx->n_pathways) || (pathway_index == 0 && mcell3_rx->n_pathways < 0));
// pathway is renamed in MCell3 to reaction because pathway has a different meaning
// MCell3 reaction is MCell4 reaction class
RxnRule rxn(&world->bng_engine.get_data());
if (mcell3_rx->prob_t == nullptr) {
rxn.base_rate_constant = current_pathway->km;
}
else {
CHECK_PROPERTY(mcell3_rx->n_pathways > 0);
CHECK_PROPERTY(mcell3_rx->pb_factor != 0);
// with variable rates, we may need to recompute the initial value for iteration 0
double prob = (pathway_index == 0) ?
mcell3_rx->cum_probs[0] : (mcell3_rx->cum_probs[pathway_index] - mcell3_rx->cum_probs[pathway_index-1]);
rxn.base_rate_constant = prob / mcell3_rx->pb_factor;
}
if (!variable_rates_per_pathway.empty()) {
assert(pathway_index < (int)variable_rates_per_pathway.size());
rxn.base_variable_rates = variable_rates_per_pathway[pathway_index];
}
CHECK_PROPERTY(current_pathway->reactant1 != nullptr);
CHECK_PROPERTY(current_pathway->orientation1 == 0 || current_pathway->orientation1 == 1 || current_pathway->orientation1 == -1);
CHECK_PROPERTY(
current_pathway->reactant2 == nullptr ||
(current_pathway->orientation2 == 0 || current_pathway->orientation2 == 1 || current_pathway->orientation2 == -1)
);
CHECK_PROPERTY(
current_pathway->reactant3 == nullptr ||
(current_pathway->orientation3 == 0 || current_pathway->orientation3 == 1 || current_pathway->orientation3 == -1)
);
// reactants
vector<species_id_t> reactant_species_ids;
if (current_pathway->reactant1 != nullptr) {
species_id_t reactant1_id = get_mcell4_species_id(current_pathway->reactant1->species_id);
rxn.append_reactant(
world->bng_engine.create_cplx_from_species(reactant1_id, current_pathway->orientation1, BNG::COMPARTMENT_ID_NONE));
reactant_species_ids.push_back(reactant1_id);
if (current_pathway->reactant2 != nullptr) {
species_id_t reactant2_id = get_mcell4_species_id(current_pathway->reactant2->species_id);
rxn.append_reactant(
world->bng_engine.create_cplx_from_species(reactant2_id, current_pathway->orientation2, BNG::COMPARTMENT_ID_NONE));
reactant_species_ids.push_back(reactant2_id);
if (current_pathway->reactant3 != nullptr) {
mcell_error("TODO_CONVERSION: reactions with 3 reactants are not supported");
}
}
else {
// reactant3 must be null if reactant2 is null
assert(current_pathway->reactant3 == nullptr);
}
}
else {
assert(false && "No reactants?");
}
CHECK_PROPERTY(current_pathway->km_filename == nullptr);
if (mcell3_rx->n_pathways == RX_ABSORB_REGION_BORDER) {
CHECK_PROPERTY(current_pathway->flags == PATHW_ABSORP);
// TODO: check and if really not used, completely remove AbsorbRegionBorder
// CHECK_PROPERTY(false && "Check to see whether PATHW_ABSORP is really produced by MCell, probably not.");
rxn.type = RxnType::AbsorbRegionBorder;
}
else if (mcell3_rx->n_pathways == RX_TRANSP) {
CHECK_PROPERTY(current_pathway->flags == PATHW_TRANSP);
rxn.type = RxnType::Transparent;
}
else if (mcell3_rx->n_pathways == RX_REFLEC) {
CHECK_PROPERTY(current_pathway->flags == PATHW_REFLEC || current_pathway->flags == (PATHW_REFLEC | PATHW_CLAMP_FLUX));
rxn.type = RxnType::Reflect;
if ((current_pathway->flags & PATHW_CLAMP_FLUX) != 0) {
// the rxn is in the form of: a + sc -> null
rxn.set_flag(BNG::RXN_FLAG_CREATED_FOR_FLUX_CLAMP);
create_clamp_release_event(current_pathway, rxn, reactant_species_ids);
rxn.base_rate_constant = DBL_GIGANTIC;
}
}
else {
CHECK_PROPERTY(
current_pathway->flags == 0 ||
current_pathway->flags == PATHW_ABSORP ||
current_pathway->flags == PATHW_CLAMP_CONC ||
current_pathway->flags == PATHW_CLAMP_FLUX);
rxn.type = RxnType::Standard;
// products
product *product_ptr = current_pathway->product_head;
while (product_ptr != nullptr) {
CHECK_PROPERTY(product_ptr->orientation == 0 || product_ptr->orientation == 1 || product_ptr->orientation == -1);
species_id_t product_id = get_mcell4_species_id(product_ptr->prod->species_id);
rxn.append_product(
world->bng_engine.create_cplx_from_species(product_id, product_ptr->orientation, BNG::COMPARTMENT_ID_NONE));
product_ptr = product_ptr->next;
}
// create conc clamp event
assert(current_pathway->flags != PATHW_CLAMP_FLUX);
if (current_pathway->flags == PATHW_CLAMP_CONC) {
assert(rxn.is_bimol());
// the rxn is in the form of: a + sc -> null
rxn.set_flag(BNG::RXN_FLAG_CREATED_FOR_CONCENTRATION_CLAMP);
create_clamp_release_event(current_pathway, rxn, reactant_species_ids);
rxn.base_rate_constant = DBL_GIGANTIC;
}
}
if (current_pathway->pathname != nullptr) {
assert(current_pathway->pathname->sym != nullptr);
rxn.name = get_sym_name(current_pathway->pathname->sym);
}
else if ((rxn.type != RxnType::Standard || rxn.is_absorptive_region_rxn()) && mcell3_rx->sym != nullptr) {
rxn.name = get_sym_name(mcell3_rx->sym);
}
else {
rxn.name = "";
}
pathway_index++;
// add our reaction, reaction classes are created on-the-fly
world->get_all_rxns().add_and_finalize(rxn);
}
return true;
}
bool MCell3WorldConverter::convert_rxns(volume* s) {
rxn** reaction_hash = s->reaction_hash;
int count = s->rx_hashsize;
for (int i = 0; i < count; ++i) {
rxn *rx = reaction_hash[i];
while (rx != nullptr) {
CHECK(convert_single_reaction(rx));
rx = rx->next;
}
}
// we can do this update with conversion from MCell3 here
// because all surface classes were defined when species were converted
world->get_all_rxns().update_all_mols_and_mol_type_compartments();
return true;
}
// returns nullptr if conversion failed
RegionExprNode* MCell3WorldConverter::create_release_region_terms_recursively(
release_evaluator* expr, ReleaseEvent& event_data, const bool is_vol_release
) {
assert(expr != nullptr);
RegionExprOperator new_op = RegionExprOperator::INVALID;
uint op_masked = expr->op & REXP_MASK;
switch (op_masked) {
case REXP_UNION:
new_op = RegionExprOperator::UNION;
break;
case REXP_INTERSECTION:
new_op = RegionExprOperator::INTERSECT;
break;
case REXP_SUBTRACTION:
new_op = RegionExprOperator::DIFFERENCE;
break;
case REXP_NO_OP:
// do nothing, the mcell3 expression tree has no leaves and regions are stored directly
break;
default:
assert(false && "Invalid region release_evaluator operator");
}
RegionExprNode* new_left;
RegionExprNode* new_right;
if ((expr->op & REXP_LEFT_REGION) != 0) {
// left node is a region
const Region* reg = world->find_region_by_name(get_sym_name(((region*)expr->left)->sym));
release_assert(reg != nullptr);
if (is_vol_release) {
// volume regions always cover the whole object
new_left = event_data.region_expr.create_new_expr_node_leaf_geometry_object(reg->geometry_object_id);
}
else {
new_left = event_data.region_expr.create_new_expr_node_leaf_surface_region(reg->id);
}
}
else if (new_op != RegionExprOperator::INVALID){
// there is an operator so we assume that the left node is a subexpr
new_left = create_release_region_terms_recursively((release_evaluator*)expr->left, event_data, is_vol_release);
}
else {
new_left = nullptr;
}
if ((expr->op & REXP_RIGHT_REGION) != 0) {
const Region* reg = world->find_region_by_name(get_sym_name(((region*)expr->right)->sym));
release_assert(reg != nullptr);
if (is_vol_release) {
// volume regions always cover the whole object
new_right = event_data.region_expr.create_new_expr_node_leaf_geometry_object(reg->geometry_object_id);
}
else {
new_right = event_data.region_expr.create_new_expr_node_leaf_surface_region(reg->id);
}
}
else if (new_op != RegionExprOperator::INVALID) {
new_right = create_release_region_terms_recursively((release_evaluator*)expr->right, event_data, is_vol_release);
}
else {
new_right = nullptr;
}
if (new_left != nullptr && new_right != nullptr) {
assert(new_op != RegionExprOperator::INVALID);
return event_data.region_expr.create_new_region_expr_node_op(new_op, new_left, new_right);
}
else if (new_left != nullptr) {
return new_left;
}
else if (new_right != nullptr) {
return new_right;
}
else {
assert(false);
return nullptr;
}
}
bool MCell3WorldConverter::convert_release_events(volume* s) {
// -- schedule_helper -- (as volume.releaser)
for (schedule_helper* releaser = s->releaser; releaser != NULL; releaser = releaser->next_scale) {
// CHECK_PROPERTY(releaser->dt == 1); // it seems that we can safely ignore dt
// CHECK_PROPERTY(releaser->dt_1 == 1);
// CHECK_PROPERTY(releaser->now == 0); // and now as well?
//ok now: CHECK_PROPERTY(releaser->count == 1);
CHECK_PROPERTY(releaser->index == 0);
for (int i = -1; i < releaser->buf_len; i++) {
for (abstract_element *aep = (i < 0) ? releaser->current : releaser->circ_buf_head[i]; aep != NULL; aep = aep->next) {
ReleaseEvent* rel_event = new ReleaseEvent(world); // used only locally to capture the information
// -- release_event_queue --
release_event_queue *req = (release_event_queue *)aep;
// -- release_site --
release_site_obj* rel_site = req->release_site;
CHECK_PROPERTY(
rel_site->release_shape == SHAPE_SPHERICAL || rel_site->release_shape == SHAPE_REGION ||
rel_site->release_shape == SHAPE_LIST
);
if (rel_site->release_shape == SHAPE_SPHERICAL) {
rel_event->release_shape = ReleaseShape::SPHERICAL;
assert(rel_site->location != nullptr);
rel_event->location = Vec3(*rel_site->location);
}
else if (rel_site->release_shape == SHAPE_REGION) {
rel_event->release_shape = ReleaseShape::REGION;
assert(rel_site->region_data != nullptr);
release_region_data* region_data = rel_site->region_data;
rel_event->location = Vec3(POS_INVALID);
species_id_t species_id = get_mcell4_species_id(rel_site->mol_type->species_id);
const Species& species = world->get_all_species().get(species_id);
// CHECK_PROPERTY(region_data->in_release == nullptr); // ignored
if (rel_site->region_data->cum_area_list != nullptr) {
// surface molecules release onto region
release_region_data* region_data = rel_site->region_data;
for (int wall_i = 0; wall_i < region_data->n_walls_included; wall_i++) {
wall* w = region_data->owners[region_data->obj_index[wall_i]]->wall_p[region_data->wall_index[wall_i]];
PartitionWallIndexPair wall_index = get_mcell4_wall_index(w);
rel_event->cumm_area_and_pwall_index_pairs.push_back(
CummAreaPWallIndexPair(region_data->cum_area_list[wall_i], wall_index)
);
}
// also remember the expression, although the cum_area_and_pwall_index_pairs is what is currently used
CHECK_PROPERTY(region_data->expression != nullptr);
rel_event->region_expr.root = create_release_region_terms_recursively(region_data->expression, *rel_event, species.is_vol());
}
else {
// volume or surface molecules release into region
// this is quite limited for now, a single region is allowed
CHECK_PROPERTY(region_data->cum_area_list == nullptr);
CHECK_PROPERTY(region_data->wall_index == nullptr);
CHECK_PROPERTY(region_data->n_objects == -1);
CHECK_PROPERTY(region_data->owners == 0);
// CHECK_PROPERTY(region_data->walls_per_obj == 0); not sure what this does
rel_event->region_llf = region_data->llf;
rel_event->region_urb = region_data->urb;
CHECK_PROPERTY(region_data->expression != nullptr);
rel_event->region_expr.root = create_release_region_terms_recursively(region_data->expression, *rel_event, species.is_vol());
}
}
else if (rel_site->release_shape == SHAPE_LIST) {
rel_event->release_shape = ReleaseShape::LIST;
CHECK_PROPERTY(rel_site->mol_list != nullptr && "There must be at least one molecule to be released with MOLECULE_LIST");
// convert info on single molecule release
for (release_single_molecule* item = rel_site->mol_list; item != nullptr; item = item->next) {
SingleMoleculeReleaseInfo info;
info.species_id = get_mcell4_species_id(item->mol_type->species_id);
info.orientation = item->orient;
info.pos = item->loc;
rel_event->molecule_list.push_back(info);
}
}
else {
assert(false);
}
if (rel_site->release_shape != SHAPE_LIST) {
CHECK_PROPERTY(rel_site->mol_type != nullptr);
rel_event->species_id = get_mcell4_species_id(rel_site->mol_type->species_id);
assert(world->get_all_species().is_valid_id(rel_event->species_id));
}
CHECK_PROPERTY(
rel_site->release_number_method == CONSTNUM ||
rel_site->release_number_method == DENSITYNUM ||
rel_site->release_number_method == CCNNUM
);
switch(rel_site->release_number_method) {
case CONSTNUM:
rel_event->release_number_method = ReleaseNumberMethod::CONST_NUM;
CHECK_PROPERTY(rel_site->concentration == 0);
break;
case DENSITYNUM:
rel_event->release_number_method = ReleaseNumberMethod::DENSITY_NUM;
break;
case CCNNUM:
rel_event->release_number_method = ReleaseNumberMethod::CONCENTRATION_NUM;
break;
default:
assert(false);
}
CHECK_PROPERTY(rel_event->release_shape == ReleaseShape::REGION || rel_site->orientation == 0);
CHECK_PROPERTY(rel_site->mean_diameter == 0); // temporary
CHECK_PROPERTY(rel_site->standard_deviation == 0); // temporary
rel_event->orientation = rel_site->orientation;
rel_event->release_number = rel_site->release_number;
rel_event->concentration = rel_site->concentration;
if (rel_site->diameter != nullptr) {
rel_event->diameter = *rel_site->diameter;
}
else {
rel_event->diameter = Vec3(0); // this is the default needed for example for list release
}
CHECK_PROPERTY(rel_site->release_prob >= 0 && rel_site->release_prob <= 1);
rel_event->release_probability = rel_site->release_prob;
// rel_site->periodic_box - ignored
rel_event->release_site_name = rel_site->name;
// rel_site->graph_pattern - ignored
// -- release_event_queue -- (again)
CHECK_PROPERTY(t_matrix_to_mat4x4(req->t_matrix) == mat4x4(1) && "only identity matrix for now");
CHECK_PROPERTY(req->train_counter == 0);
//release_pattern
assert(rel_site->pattern != nullptr);
release_pattern* rp = rel_site->pattern;
if (rp->sym != nullptr) {
rel_event->release_pattern_name = get_sym_name(rp->sym);
}
else {
rel_event->release_pattern_name = NAME_NOT_SET;
}
assert(rp->delay == req->event_time && "Release pattern must specify the same delay as for which the event is scheduled");
assert(rp->delay == req->train_high_time && "Initial train_high_time must be the same as delay");
// all these variables affect scheduling and are handled internally in the event
rel_event->delay = rp->delay;
rel_event->train_interval = rp->train_interval;
rel_event->number_of_trains = rp->number_of_trains;
rel_event->train_duration = rp->train_duration;
rel_event->release_interval = rp->release_interval;
rel_event->update_event_time_for_next_scheduled_time(); // sets the first event_time according to the setup
world->scheduler.schedule_event(rel_event);
}
}
// -- schedule_helper -- (again)
CHECK_PROPERTY(releaser->current_count == 0);
CHECK_PROPERTY(releaser->current == nullptr);
CHECK_PROPERTY(releaser->current_tail == nullptr);
CHECK_PROPERTY(releaser->defunct_count == 0);
CHECK_PROPERTY(releaser->error == 0);
//CHECK_PROPERTY(releaser->depth == 0); // ignored
}
return true;
}
bool MCell3WorldConverter::convert_viz_output_events(volume* s) {
// -- viz_output_block --
viz_output_block* viz_blocks = s->viz_blocks;
if (viz_blocks == nullptr) {
return true; // no visualization data
}
CHECK_PROPERTY(viz_blocks->next == nullptr);
CHECK_PROPERTY(viz_blocks->viz_mode == NO_VIZ_MODE ||
viz_blocks->viz_mode == ASCII_MODE ||
viz_blocks->viz_mode == CELLBLENDER_MODE_V1); // just checking valid values
viz_mode_t viz_mode = viz_blocks->viz_mode;
// CHECK_PROPERTY(viz_blocks->viz_output_flag == VIZ_ALL_MOLECULES); // ignored (for now?)
uint_set<species_id_t> species_ids_to_visualize;
assert((int)mcell3_species_id_map.size() == s->n_species);
for (int i = 0; i < s->n_species; i++) {
if (viz_blocks->species_viz_states[i] == INCLUDE_OBJ) {
species_ids_to_visualize.insert_unique( get_mcell4_species_id(i) );
}
else if (viz_blocks->species_viz_states[i] == EXCLUDE_OBJ) {
continue; // this species is not counted
}
else {
assert(false);
}
}
// CHECK_PROPERTY(viz_blocks->default_mol_state == INCLUDE_OBJ); // seems to be used only internally
// -- frame_data_head --
frame_data_list* frame_data_head = viz_blocks->frame_data_head;
if (frame_data_head == nullptr) {
// no events to log
return true;
}
CHECK_PROPERTY(frame_data_head->next == nullptr);
CHECK_PROPERTY(frame_data_head->list_type == OUTPUT_BY_ITERATION_LIST); // limited for now
CHECK_PROPERTY(frame_data_head->type == ALL_MOL_DATA); // limited for now
CHECK_PROPERTY(frame_data_head->viz_iteration == 0); // must be zero at sim. start
// determine periodicity
CHECK_PROPERTY(frame_data_head->n_viz_iterations > 0);
double periodicity;
if (frame_data_head->n_viz_iterations > 1) {
num_expr_list* iteration_ptr = frame_data_head->iteration_list;
assert(iteration_ptr->next != nullptr);
periodicity = iteration_ptr->next->value - iteration_ptr->value;
// check that the first different in time is true for everything else
num_expr_list* curr_viz_iteration_ptr = frame_data_head->curr_viz_iteration;
for (long long i = 0; i < frame_data_head->n_viz_iterations; i++) {
assert(iteration_ptr != nullptr);
assert(curr_viz_iteration_ptr != nullptr);
assert(iteration_ptr->value == curr_viz_iteration_ptr->value);
if (iteration_ptr->next != nullptr) {
CHECK_PROPERTY(cmp_eq(periodicity, iteration_ptr->next->value - iteration_ptr->value));
}
iteration_ptr = iteration_ptr->next;
curr_viz_iteration_ptr = curr_viz_iteration_ptr->next;
}
}
else {
periodicity = 0;
}
VizOutputEvent* event = new VizOutputEvent(world);
event->event_time = frame_data_head->iteration_list->value;
event->periodicity_interval = periodicity;
event->viz_mode = viz_mode;
event->file_prefix_name = viz_blocks->file_prefix_name;
event->species_ids_to_visualize = species_ids_to_visualize; // copying the whole map
world->scheduler.schedule_event(event);
return true;
}
static const output_request* find_output_request_by_requester(const volume* s, const output_expression* expr) {
for (
const output_request* req = s->output_request_head;
req != nullptr;
req = req->next) {
// pointer comparison
if (req->requester == expr) {
return req;
}
}
return nullptr;
}
// returns false if conversion failed
static bool find_output_requests_terms_recursively(
const volume* s, const output_expression* expr, const int sign, const bool top_level,
std::vector< pair<const output_request*, int>>& requests_with_sign,
double& multiplier
) {
assert(sign == -1 || sign == 1);
// operator must me one of +, -, #
// # - cast output_request to expr
double ignored;
switch (expr->oper) {
case '#': {
const output_request* req = find_output_request_by_requester(s, expr);
CHECK_PROPERTY(req != nullptr);
requests_with_sign.push_back(make_pair(req, sign));
}
break;
case '(': {
// parentheses are encoded explicitly, we can ignore them
bool left_ok = find_output_requests_terms_recursively(
s, (const output_expression*)expr->left, sign, false, requests_with_sign, ignored);
if (!left_ok) {
return false;
}
}
break;
case '+':
case '-': {
bool left_ok = find_output_requests_terms_recursively(
s, (const output_expression*)expr->left, sign, false, requests_with_sign, ignored);
if (!left_ok) {
return false;
}
int new_sign = sign;
if (expr->oper == '-') {
new_sign = -sign;
}
bool right_ok = find_output_requests_terms_recursively(
s, (const output_expression*)expr->right, new_sign, false, requests_with_sign, ignored);
if (!right_ok) {
return false;
}
}
break;
case '/':
case '*': {
CHECK_PROPERTY(top_level && "In a count term, only the whole count expression can be multiplied");
// which of the operands is the constant multiplier?
const output_expression* left = (const output_expression*)expr->left;
const output_expression* right = (const output_expression*)expr->right;
const output_expression* count_term;
if (left->oper == '#' || left->oper == '+' || left->oper == '-' || left->oper == '(') {
count_term = left;
CHECK_PROPERTY(right->oper == '=' || right->oper == '(');
if (expr->oper == '*') {
multiplier = right->value;
}
else {
multiplier = 1.0 / right->value;
}
}
else if (right->oper == '#' || right->oper == '+' || right->oper == '-' || right->oper == '(') {
count_term = right;
CHECK_PROPERTY(left->oper == '=' || left->oper == '(');
if (expr->oper == '*') {
multiplier = left->value;
}
else {
multiplier = 1.0 / left->value;
}
}
else {
CHECK_PROPERTY(false && "Could not process count expression");
}
assert(sign == +1);
bool right_ok = find_output_requests_terms_recursively(
s, count_term, sign, false, requests_with_sign, ignored);
if (!right_ok) {
return false;
}
}
break;
default:
CHECK_PROPERTY(false && "Invalid output request operator");
}
return true;
}
static bool ends_with(std::string const & value, std::string const & ending)
{
if (ending.size() > value.size()) {
return false;
}
return std::equal(ending.rbegin(), ending.rend(), value.rbegin());
}
bool MCell3WorldConverter::convert_mol_or_rxn_count_events(volume* s) {
output_block* output_blocks = s->output_block_head;
while (output_blocks != nullptr) {
MolOrRxnCountEvent* event = new MolOrRxnCountEvent(world);
CHECK_PROPERTY(output_blocks->timer_type == OUTPUT_BY_STEP);
CHECK_PROPERTY(output_blocks->t == 0);
event->event_time = 0;
event->periodicity_interval = output_blocks->step_time / world->config.time_unit;
size_t buffer_size = output_blocks->buffersize;
// we can check that the time_array contains expected values
for (
output_set* data_set = output_blocks->data_set_head;
data_set != nullptr;
data_set = data_set->next) {
CHECK_PROPERTY(data_set->outfile_name != nullptr);
count_buffer_id_t buffer_id =
world->create_dat_count_buffer(data_set->outfile_name, buffer_size);
// NOTE: FILE_SUBSTITUTE is interpreted in the same way as FILE_OVERWRITE
CHECK_PROPERTY(data_set->file_flags == FILE_OVERWRITE || data_set->file_flags == FILE_SUBSTITUTE);
CHECK_PROPERTY(data_set->chunk_count == 0);
CHECK_PROPERTY(data_set->header_comment == nullptr);
CHECK_PROPERTY(data_set->exact_time_flag == 1);
output_column* column_head = data_set->column_head;
CHECK_PROPERTY(column_head->next == nullptr);
CHECK_PROPERTY(column_head->initial_value == 0);
// TODO: we should better check column_head->expr contents
// this information is split in a weird way in MCell3,
// output request contains more information on what should be counted,
// there is a way how to get to the output_set from the expression
// but not how to the output_request
// we simplify it to a list of terms with their sign
// first is the output request, second is sign (-1 or +1)
std::vector< pair<const output_request*, int>> requests_with_sign;
double multiplier = 1;
CHECK(find_output_requests_terms_recursively(s, column_head->expr, +1, true, requests_with_sign, multiplier));
MolOrRxnCountItem info(buffer_id, 0); // always DAT format
info.multiplier = multiplier;
for (pair<const output_request*, int>& req_w_sign: requests_with_sign) {
MolOrRxnCountTerm term;
term.sign_in_expression = req_w_sign.second;
const output_request* req = req_w_sign.first;
CHECK_PROPERTY(req != 0);
int o = req->count_orientation;
if (o == ORIENT_NOT_SET) {
term.orientation = ORIENTATION_NOT_SET;
}
else {
CHECK_PROPERTY(o == ORIENTATION_UP || o == ORIENTATION_NONE || o == ORIENTATION_DOWN);
term.orientation = o;
}
// report type
CHECK_PROPERTY(
req->report_type == REPORT_CONTENTS ||
req->report_type == REPORT_RXNS ||
req->report_type == (REPORT_CONTENTS | REPORT_ENCLOSED) ||
req->report_type == (REPORT_CONTENTS | REPORT_WORLD) ||
req->report_type == (REPORT_RXNS | REPORT_WORLD) ||
req->report_type == (REPORT_RXNS | REPORT_ENCLOSED)
);
bool count_mols_not_rxns;
if ((req->report_type & REPORT_CONTENTS) != 0) {
count_mols_not_rxns = true;
}
else if ((req->report_type & REPORT_RXNS) != 0) {
count_mols_not_rxns = false;
}
else {
assert(false);
count_mols_not_rxns = true; // silence compilation warning
}
// count location
// only whole geom object for now
if ((req->report_type & REPORT_ENCLOSED) != 0) {
term.type = count_mols_not_rxns ? CountType::EnclosedInVolumeRegion : CountType::RxnCountInVolumeRegion;
string reg_name = get_sym_name(req->count_location);
CHECK_PROPERTY(ends_with(reg_name, ",ALL")); // enclused in object must be whole objects
const Region* reg = world->get_partition(0).find_region_by_name(reg_name);
if (reg == nullptr) {
mcell_error("Could not find a counted region with name %s.", reg_name.c_str());
}
assert(reg->geometry_object_id != GEOMETRY_OBJECT_ID_INVALID);
geometry_object_id_t geometry_object_id = reg->geometry_object_id;
// MDL version does not support region expressions
term.region_expr.root = term.region_expr.create_new_expr_node_leaf_geometry_object(geometry_object_id);
// set flag that we should include this object in counted volumes
GeometryObject& obj = world->get_partition(0).get_geometry_object(geometry_object_id);
obj.set_is_used_in_mol_rxn_counts();
}
else {
if (req->count_location == nullptr) {
term.type = count_mols_not_rxns ? CountType::EnclosedInWorld : CountType::RxnCountInWorld;
}
else {
CHECK_PROPERTY(req->report_type == REPORT_CONTENTS || req->report_type == REPORT_RXNS);
string reg_name = get_sym_name(req->count_location);
const Region* reg = world->get_partition(0).find_region_by_name(reg_name);
// MDL version does not support region expressions
term.region_expr.root = term.region_expr.create_new_expr_node_leaf_surface_region(reg->id);
term.type = count_mols_not_rxns ? CountType::PresentOnSurfaceRegion : CountType::RxnCountOnSurfaceRegion;
}
}
if (count_mols_not_rxns) {
// count target (species)
CHECK_PROPERTY(req->count_target != 0);
string species_name = get_sym_name(req->count_target);
term.species_pattern_type = SpeciesPatternType::SpeciesId;
term.species_id = world->get_all_species().find_by_name(species_name);
CHECK_PROPERTY(term.species_id != SPECIES_ID_INVALID);
}
else {
// set that the reaction must be counted
CHECK_PROPERTY(req->count_target != nullptr);
string rxn_name = get_sym_name(req->count_target);
BNG::RxnRule* rxn_rule = world->get_all_rxns().find_rxn_rule_by_name(rxn_name);
CHECK_PROPERTY(rxn_rule != nullptr && "Rxn rule with name was not found");
// set rxn counting flag
switch (term.type) {
case CountType::RxnCountInWorld:
rxn_rule->set_is_counted_in_world();
break;
case CountType::RxnCountInVolumeRegion:
rxn_rule->set_is_counted_in_volume_regions();
break;
case CountType::RxnCountOnSurfaceRegion:
rxn_rule->set_is_counted_on_surface_regions();
break;
default:
assert(false);
}
term.rxn_rule_id = rxn_rule->id;
}
info.terms.push_back(term);
}
event->add_mol_count_item(info);
}
world->scheduler.schedule_event(event);
// process next output block
output_blocks = output_blocks->next;
}
return true;
}
void MCell3WorldConverter::update_and_schedule_concentration_clamps() {
for (ClampReleaseEvent* clamp: concentration_clamps) {
clamp->update_cumm_areas_and_scaling();
world->scheduler.schedule_event(clamp);
}
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/molecule.cpp | .cpp | 4,263 | 169 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include "bng/species.h"
#include "mcell_structs_shared.h"
#include "molecule.h"
#include "geometry.h"
#include "world.h"
#include "debug_config.h"
using namespace std;
namespace MCell {
void Molecule::set_no_need_to_schedule_flag(
const BNG::SpeciesContainer& all_species) {
clear_flag(MOLECULE_FLAG_NO_NEED_TO_SCHEDULE);
const BNG::Species& s = all_species.get(species_id);
if (s.D != 0 ||
s.has_flag(BNG::SPECIES_FLAG_HAS_UNIMOL_RXN) ||
s.has_flag(BNG::SPECIES_FLAG_CAN_SURFSURF) ||
s.has_flag(BNG::SPECIES_FLAG_CAN_SURFWALL) ||
s.has_flag(BNG::SPECIES_FLAG_CAN_INTERMEMBRANE_SURFSURF)
) {
return;
}
set_flag(MOLECULE_FLAG_NO_NEED_TO_SCHEDULE);
}
string get_molecule_flags_string(uint flags, bool full_dump = true) {
string res;
#define DUMP_FLAG(f, mask) if (((f) & (mask)) != 0) res += string(#mask) + ", ";
DUMP_FLAG(flags, MOLECULE_FLAG_SURF)
DUMP_FLAG(flags, MOLECULE_FLAG_VOL)
if (full_dump) {
if ((flags & MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN) != 0)
res += string("ACT_NEWBIE") + ", ";
if ((flags & MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN) != 0)
res += string("ACT_CHANGE") + ", ";
}
DUMP_FLAG(flags, MOLECULE_FLAG_ACT_CLAMPED)
DUMP_FLAG(flags, MOLECULE_FLAG_DEFUNCT)
#undef DUMP_FLAG
return res;
}
void Molecule::dump(const string ind) const {
if (is_vol()) {
cout << ind << "pos: \t\t" << v.pos << " [vec3_t]\n";
cout << ind << "reactant_subpart_index: \t\t" << v.reactant_subpart_index << " [uint]\n";
cout << ind << "subpartition_index: \t\t" << v.subpart_index << " [uint]\n";
}
else if (is_surf()) {
cout << ind << "pos: \t\t" << s.pos << " [vec2_t]\n";
}
cout << ind << "flags: \t\t" << flags << " [uint]\n";
cout << ind << "species_id: \t\t" << species_id << " [species_id_t]\n";
}
void Molecule::dump(
const Partition& p,
const string extra_comment,
const string ind,
const uint64_t iteration,
const double time,
const bool print_position,
const bool print_flags
) const {
cout
<< ind << extra_comment << "it: " << iteration << ", id: " << id
<< ", species: " << p.get_species(species_id).name;
if (print_position) {
cout << ", pos: ";
if (is_vol()) {
cout << v.pos;
}
else if (is_surf()) {
cout << s.pos;
cout << ", orient: " << s.orientation;
const Wall& w = p.get_wall(s.wall_index);
cout << ", wall side: " << w.side;
cout << ", grid index: " << s.grid_tile_index;
}
}
if (print_flags) {
cout << ", flags: " << get_molecule_flags_string(flags, false);
}
#ifdef DEBUG_SUBPARTITIONS
IVec3 indices;
p.get_subpart_3d_indices_from_index(v.subpart_index, indices);
if (is_vol()) {
cout << ", subpartition: " << v.subpart_index << " " << indices;
}
#endif
#ifdef DEBUG_COUNTED_VOLUMES
if (is_vol()) {
cout << ", counted vols id: " << v.counted_volume_index;
p.get_counted_volume(v.counted_volume_index).dump();
}
#endif
#ifdef DEBUG_COMPARTMENTS
cout << ", compartment id: " << reactant_compartment_id;
#endif
cout
<< ", time: " << time
<< "\n";
}
string Molecule::to_string() const {
stringstream ss;
ss
<< "id: " << id
<< ", species: " << species_id
<< ", pos: ";
if (is_vol()) {
cout << v.pos;
}
else if (is_surf()) {
cout << s.pos;
}
ss << ", flags:" << get_molecule_flags_string(flags, false);
return ss.str();
}
void Molecule::dump_array(const std::vector<Molecule>& vec) {
for (size_t i = 0; i < vec.size(); i++) {
if (vec[i].is_vol()) {
cout << " vm ";
}
else if (vec[i].is_surf()) {
cout << " sm ";
}
cout << i << ": " << vec[i].to_string() << "\n";
}
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/mol_or_rxn_count_event.cpp | .cpp | 27,976 | 863 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "mol_or_rxn_count_event.h"
#include <iostream>
#include "world.h"
#include "partition.h"
#include "datamodel_defines.h"
#include "generated/gen_names.h"
using namespace std;
namespace MCell {
uint MolOrRxnCountTerm::get_num_pattern_matches(const species_id_t species_id) const {
assert(species_pattern_type != SpeciesPatternType::SpeciesId);
auto it = species_ids_matching_pattern_w_multiplier_cache.find(species_id);
if (it == species_ids_matching_pattern_w_multiplier_cache.end()) {
return 0;
}
else if (species_pattern_type == SpeciesPatternType::SpeciesPattern) {
// each molecule is counted only once
return 1;
}
else {
assert(species_pattern_type == SpeciesPatternType::MoleculesPattern);
assert(it->second >= 1);
return it->second;
}
}
uint MolOrRxnCountTerm::get_num_molecule_matches(
const Molecule& m,
const species_id_t all_mol_id, const species_id_t all_vol_id, const species_id_t all_surf_id) const {
assert(is_mol_count());
if (species_pattern_type == SpeciesPatternType::SpeciesId) {
assert(species_id != SPECIES_ID_INVALID);
if (
species_id == m.species_id ||
species_id == all_mol_id ||
(species_id == all_vol_id && m.is_vol()) ||
(species_id == all_surf_id && m.is_surf())
) {
return 1;
}
else {
return 0;
}
}
else {
assert(!species_molecules_pattern.elem_mols.empty());
return get_num_pattern_matches(m.species_id);
}
}
void MolOrRxnCountTerm::dump(const std::string ind) const {
cout << ind << "type: ";
switch(type) {
case CountType::Invalid:
cout << "Invalid";
break;
case CountType::EnclosedInWorld:
cout << "World";
break;
case CountType::EnclosedInVolumeRegion:
cout << "EnclosedInObject";
break;
case CountType::PresentOnSurfaceRegion:
cout << "PresentOnSurfaceRegion";
break;
case CountType::RxnCountInWorld:
cout << "RxnCountInWorld";
break;
case CountType::RxnCountInVolumeRegion:
cout << "RxnCountInObject";
break;
case CountType::RxnCountOnSurfaceRegion:
cout << "RxnCountOnSurfaceRegion";
break;
default:
assert(false);
}
cout << "\n";
cout << ind << "sign_in_expression: " << sign_in_expression << " [int]\n";
cout << ind << "orientation: " << orientation << " [orientation_t]\n";
cout << ind << "type: ";
switch(species_pattern_type) {
case SpeciesPatternType::Invalid:
cout << "Invalid";
break;
case SpeciesPatternType::SpeciesId:
cout << "SpeciesId";
cout << ind << "species_id: " << species_id << " [species_id_t]\n";
break;
case SpeciesPatternType::SpeciesPattern:
cout << "SpeciesPattern";
cout << ind << "species_molecules_pattern: " << species_molecules_pattern.to_str() << " [CplxInstance]\n";
break;
case SpeciesPatternType::MoleculesPattern:
cout << "MoleculesPattern";
cout << ind << "species_molecules_pattern: " << species_molecules_pattern.to_str() << " [CplxInstance]\n";
break;
default:
assert(false);
}
cout << "\n";
cout << ind << "primary_compartment_id: " << primary_compartment_id << " [compartment_id_t]\n";
cout << ind << "rxn_rule_id: " << rxn_rule_id << " [rxn_rule_id_t]\n";
if (region_expr.root != nullptr) {
cout << ind << "region_expr: " << region_expr.root->to_string(nullptr, false) << " [geometry_object_id_t]\n";
}
else {
cout << ind << "region_expr: " << "none\n";
}
}
static std::string get_region_as_mdl_string_recursively(const World* world, const RegionExprNode* node) {
if (node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
string obj_name = world->get_geometry_object(node->geometry_object_id).name;
CONVERSION_CHECK(obj_name != "", "Counted object has no name");
return obj_name;
}
else if (node->op == RegionExprOperator::LEAF_SURFACE_REGION) {
string reg_name = world->get_region(node->region_id).name;
CONVERSION_CHECK(reg_name != "", "Counted region has no name");
// use MCell4 naming - directly the surface region name without the object
return DMUtils::get_object_w_region_name(reg_name, false);
}
else {
release_assert(node->has_binary_op());
string left = get_region_as_mdl_string_recursively(world, node->left);
string right = get_region_as_mdl_string_recursively(world, node->right);
switch (node->op) {
case RegionExprOperator::DIFFERENCE:
return "(" + left + " - " + right + ")";
case RegionExprOperator::INTERSECT:
return "(" + left + " * " + right + ")";
case RegionExprOperator::UNION:
return "(" + left + " + " + right + ")";
default:
assert(false);
return "error";
}
}
}
std::string MolOrRxnCountTerm::to_data_model_string(const World* world, bool print_positive_sign) const {
stringstream res;
assert(sign_in_expression == -1 || sign_in_expression == 1);
res <<
((sign_in_expression == 1) ?
(print_positive_sign) ? "+" : "":
"-"
);
res << "COUNT[";
string pattern;
switch(type) {
case CountType::EnclosedInWorld:
case CountType::EnclosedInVolumeRegion:
case CountType::PresentOnSurfaceRegion:
if (primary_compartment_id != BNG::COMPARTMENT_ID_NONE) {
pattern = "@" + world->bng_engine.get_data().get_compartment(primary_compartment_id).name + ":";
}
switch (species_pattern_type) {
case SpeciesPatternType::SpeciesId:
pattern += world->get_all_species().get(species_id).name;
break;
case SpeciesPatternType::SpeciesPattern:
pattern += species_molecules_pattern.to_str() + MARKER_SPECIES_COMMENT;
break;
case SpeciesPatternType::MoleculesPattern:
pattern += species_molecules_pattern.to_str() + MARKER_MOLECULES_COMMENT;
break;
default:
assert(false);
}
break;
case CountType::RxnCountInWorld:
case CountType::RxnCountInVolumeRegion:
case CountType::RxnCountOnSurfaceRegion: {
string rxn_name = world->get_all_rxns().get(rxn_rule_id)->name;
CONVERSION_CHECK(rxn_name != "", "Counted reaction has no name");
pattern = rxn_name;
}
break;
default:
assert(false);
}
string where;
switch(type) {
case CountType::EnclosedInWorld:
case CountType::RxnCountInWorld:
where = VALUE_WORLD;
break;
case CountType::EnclosedInVolumeRegion:
case CountType::RxnCountInVolumeRegion:
where = get_region_as_mdl_string_recursively(world, region_expr.root);
break;
case CountType::PresentOnSurfaceRegion:
case CountType::RxnCountOnSurfaceRegion:{
if (region_expr.root->op == RegionExprOperator::LEAF_SURFACE_REGION) {
region_id_t region_id = region_expr.root->region_id;
// if possible, we should use 2d compartment name because in MCell
// the encompassing region name is the same as the name of the object,
// this would lead to the same name for A@CP and A@PM
bool surf_compartment_used = false;
const Partition& p = world->get_partition(PARTITION_ID_INITIAL);
for (const auto& geom_obj: p.get_geometry_objects()) {
if (geom_obj.encompassing_region_id == region_id &&
geom_obj.surf_compartment_id != BNG::COMPARTMENT_ID_NONE) {
const BNG::Compartment& comp = world->bng_engine.get_data().get_compartment(geom_obj.surf_compartment_id);
assert(!comp.is_3d);
pattern = "@" + comp.name + ":" + pattern;
where = VALUE_WORLD;
surf_compartment_used = true;
break;
}
}
if (!surf_compartment_used) {
string reg_name = world->get_region(region_id).name;
CONVERSION_CHECK(reg_name != "", "Counted region has no name");
where = DMUtils::get_object_w_region_name(reg_name, false);
}
}
else {
// we don't care about compartments with combined surface regions
// TODO: specific test needed
where = get_region_as_mdl_string_recursively(world, region_expr.root);
}
}
break;
default:
assert(false);
}
res << pattern << "," << where << "]";
return res.str();
}
bool MolOrRxnCountItem::counts_mols() const {
for (auto& t: terms) {
if (t.is_mol_count()) {
return true;
}
}
return false;
}
bool MolOrRxnCountItem::counts_rxns() const {
for (auto& t: terms) {
if (t.is_rxn_count()) {
return true;
}
}
return false;
}
bool MolOrRxnCountItem::is_world_mol_count() const {
// SpeciesId is obsoleted and not handled correctly
return
terms.size() == 1 &&
terms[0].type == CountType::EnclosedInWorld &&
terms[0].species_pattern_type != SpeciesPatternType::SpeciesId;
}
void MolOrRxnCountItem::dump(const std::string ind) const {
cout << ind << "buffer_id: " << buffer_id << " [count_buffer_id_t] \t\t\n";
cout << ind << "terms:\n";
for (uint i = 0; i < terms.size(); i++) {
cout << i << ":\n";
terms[i].dump(ind + " ");
}
}
static string basename(const string& s) {
char sep = '/'; // / is used on Windows as well in the rxn_output file path
size_t i = s.rfind(sep, s.length());
if (i != string::npos) {
return(s.substr(i+1, s.length() - i));
}
else {
return s;
}
}
static string noext(const string& s) {
char sep = '.'; // / is used on Windows as well in the rxn_output file path
size_t i = s.rfind(sep, s.length());
if (i != string::npos) {
return(s.substr(0, i));
}
else {
return s;
}
}
void MolOrRxnCountItem::to_data_model(const World* world, Json::Value& reaction_output) const {
DMUtils::add_version(reaction_output, VER_DM_2018_01_11_1330);
// MDLString is a general way how to capture the output
reaction_output[KEY_RXN_OR_MOL] = VALUE_MDLSTRING;
reaction_output[KEY_DESCRIPTION] = "";
reaction_output[KEY_PLOTTING_ENABLED] = true;
// file prefix
const CountBuffer& buff = world->get_count_buffer(buffer_id);
string prefix;
string filename = basename(buff.get_filename());
prefix = noext(filename);
if (buff.get_output_format() == CountOutputFormat::DAT) {
reaction_output[KEY_MDL_FILE_PREFIX] = prefix;
}
else if (buff.get_output_format() == CountOutputFormat::GDAT) {
reaction_output[KEY_MDL_FILE_PREFIX] = buff.get_column_name(buffer_column_index);
reaction_output[KEY_OUTPUT_FILE_OVERRIDE] = filename;
}
// species or rxn name & location is in mdl_string
reaction_output[KEY_NAME] = "";
reaction_output[KEY_MOLECULE_NAME] = "";
reaction_output[KEY_REACTION_NAME] = "";
reaction_output[KEY_OBJECT_NAME] = "";
reaction_output[KEY_REGION_NAME] = "";
if (terms.size() == 1) {
string val;
switch (terms[0].type) {
case CountType::EnclosedInWorld:
case CountType::RxnCountInWorld:
val = VALUE_COUNT_LOCATION_WORLD;
break;
case CountType::EnclosedInVolumeRegion:
case CountType::RxnCountInVolumeRegion:
val = VALUE_COUNT_LOCATION_OBJECT;
break;
case CountType::PresentOnSurfaceRegion:
case CountType::RxnCountOnSurfaceRegion:
val = VALUE_COUNT_LOCATION_REGION;
break;
default:
assert(false);
}
reaction_output[KEY_COUNT_LOCATION] = val;
}
else {
#ifndef NDEBUG
cerr <<
"Warning: conversion of count expression with multiple terms to data model's " << KEY_COUNT_LOCATION <<
" is not fully supported, defaulting to " << VALUE_COUNT_LOCATION_REGION << ".\n";
#endif
reaction_output[KEY_COUNT_LOCATION] = VALUE_COUNT_LOCATION_REGION;
}
// handled by prefix
reaction_output[KEY_DATA_FILE_NAME] = "";
string mdl_string = "";
for (size_t i = 0; i < terms.size(); i++) {
mdl_string += terms[i].to_data_model_string(world, i != 0);
}
if (multiplier != 1) {
mdl_string = "(" + mdl_string + ")*" + f_to_str(multiplier);
}
reaction_output[KEY_MDL_STRING] = mdl_string;
}
template<class T>
static uint sum_all_map_items(const T& map) {
uint res = 0;
for (const auto& it: map) {
res += it.second;
}
return res;
}
static bool wall_is_part_of_region(
const Partition& p, const wall_index_t wall_index, const region_id_t region_id) {
assert(wall_index != WALL_INDEX_INVALID);
assert(region_id != REGION_ID_INVALID);
// for all the regions of the current molecule
const Wall& w = p.get_wall(wall_index);
for (region_index_t ri: w.regions) {
if (p.get_region(ri).id == region_id) {
return true;
}
}
return false;
}
static bool get_binary_region_expr_result(
const RegionExprOperator op, const bool left, const bool right) {
switch (op) {
case RegionExprOperator::DIFFERENCE:
return left && !right;
case RegionExprOperator::INTERSECT:
return left && right;
case RegionExprOperator::UNION:
return left || right;
default:
assert(false);
return false;
}
}
static bool counted_volume_matches_region_expr_recursively(
const CountedVolume& enclosing_volumes,
const RegionExprNode* node
) {
assert(node != nullptr);
if (node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
// returns true if the current geometry object is one of the enclosing volumes
return enclosing_volumes.contained_in_objects.count(node->geometry_object_id) != 0;
}
else if (node->has_binary_op()) {
bool left = counted_volume_matches_region_expr_recursively(enclosing_volumes, node->left);
bool right = counted_volume_matches_region_expr_recursively(enclosing_volumes, node->right);
return get_binary_region_expr_result(node->op, left, right);
}
else {
assert(false);
return false;
}
}
static bool wall_matches_region_expr_recursively(
const Partition& p,
const wall_index_t wall_index,
const RegionExprNode* node
) {
assert(node != nullptr);
if (node->op == RegionExprOperator::LEAF_SURFACE_REGION) {
// returns true if the current geometry object is one of the enclosing volumes
return wall_is_part_of_region(p, wall_index, node->region_id);
}
else if (node->has_binary_op()) {
bool left = wall_matches_region_expr_recursively(p, wall_index, node->left);
bool right = wall_matches_region_expr_recursively(p, wall_index, node->right);
return get_binary_region_expr_result(node->op, left, right);
}
else {
assert(false);
return false;
}
}
void MolOrRxnCountEvent::compute_mol_count_item(
const Partition& p,
const MolOrRxnCountItem& item,
const Molecule& m,
CountValueVector& count_values
) {
species_id_t all_mol_id = world->get_all_species().get_all_molecules_species_id();
species_id_t all_vol_id = world->get_all_species().get_all_volume_molecules_species_id();
species_id_t all_surf_id = world->get_all_species().get_all_surface_molecules_species_id();
for (const MolOrRxnCountTerm& term: item.terms) {
// does the current molecule match?
if (term.is_mol_count()) {
// num_matches may be > 1 when molecules pattern is used for matching
uint num_matches = term.get_num_molecule_matches(m, all_mol_id, all_vol_id, all_surf_id);
if (num_matches == 0) {
continue;
}
if (term.type == CountType::EnclosedInWorld) {
// count the molecule
count_values[item.index].inc_or_dec(term.sign_in_expression, num_matches);
}
else if (m.is_vol() && term.type == CountType::EnclosedInVolumeRegion) {
// is the molecule inside of the object/volume region expression that we are checking?
const CountedVolume& enclosing_volumes = p.get_counted_volume(m.v.counted_volume_index);
if (counted_volume_matches_region_expr_recursively(enclosing_volumes, term.region_expr.root)) {
count_values[item.index].inc_or_dec(term.sign_in_expression, num_matches);
}
}
else if (m.is_surf() && term.type == CountType::PresentOnSurfaceRegion) {
// does the molecule's wall match the region expression?
if (wall_matches_region_expr_recursively(p, m.s.wall_index, term.region_expr.root)) {
count_values[item.index].inc_or_dec(term.sign_in_expression, num_matches);
}
}
}
} // for terms
}
void MolOrRxnCountEvent::compute_rxn_count_item(
Partition& p,
const MolOrRxnCountItem& item,
const BNG::RxnRule* rxn,
CountValueVector& count_values
) {
for (const MolOrRxnCountTerm& term: item.terms) {
assert(!term.is_rxn_count() || term.rxn_rule_id != BNG::RXN_RULE_ID_INVALID);
// does the current reaction match?
if (term.is_rxn_count() && term.rxn_rule_id == rxn->id) {
// use initial_reactions_count (from previous checkpoint)
count_values[item.index].value += term.initial_reactions_count;
// get counts from partition
const CountInGeomObjectMap& counts_in_objects = p.get_rxn_in_volume_count_map(term.rxn_rule_id);
const CountOnWallMap& counts_on_walls = p.get_rxn_on_surface_count_map(term.rxn_rule_id);
if (term.type == CountType::RxnCountInWorld) {
// count all the occurrences
count_values[item.index].inc_or_dec(
term.sign_in_expression,
sum_all_map_items(counts_in_objects)
);
count_values[item.index].inc_or_dec(
term.sign_in_expression,
sum_all_map_items(counts_on_walls)
);
}
else if (term.type == CountType::RxnCountInVolumeRegion) {
for (const auto& it: counts_in_objects) {
if (it.second != 0) {
counted_volume_index_t counted_volume_index_for_this_count = it.first;
// volumes that enclose the location where reaction occurred
// might be nullptr if not found
const CountedVolume& enclosing_volumes = p.get_counted_volume(counted_volume_index_for_this_count);
if (counted_volume_matches_region_expr_recursively(enclosing_volumes, term.region_expr.root)) {
count_values[item.index].inc_or_dec(term.sign_in_expression, it.second);
}
}
}
}
else if (term.type == CountType::RxnCountOnSurfaceRegion) {
for (const auto& it: counts_on_walls) {
if (it.second != 0) {
wall_index_t wall_index_for_this_count = it.first;
// does the reaction's wall match the region expression?
if (wall_matches_region_expr_recursively(p, wall_index_for_this_count, term.region_expr.root)) {
count_values[item.index].inc_or_dec(term.sign_in_expression, it.second);
}
}
}
}
}
} // for terms
}
void MolOrRxnCountEvent::compute_counts(CountValueVector& count_values) {
// go through all molecules and count them
PartitionVector& partitions = world->get_partitions();
count_values.resize(mol_rxn_count_items.size());
// initialize new count items
for (uint i = 0; i < mol_rxn_count_items.size(); i++) {
count_values[i].column_index = mol_rxn_count_items[i].buffer_column_index;
count_values[i].time = event_time * world->config.time_unit;
count_values[i].value = 0;
}
uint_set<uint> processed_item_indices;
// to improve performance, first process the species that we are counting in the whole world,
// but only if there is less species than molecules (very crude heuristics)
if (world->get_all_species().get_species_vector().size() <
world->get_partition(PARTITION_ID_INITIAL).get_molecules().size()) {
for (const BNG::Species* species: world->get_all_species().get_species_vector()) {
if (species->is_defunct() || species->get_num_instantiations() == 0) {
continue;
}
check_countable_species(species->id);
count_species_info_index_t countable_species_index = countable_species_lut[species->id];
if (countable_species_index == NotToBeCounted) {
continue;
}
const CountSpeciesInfo& species_info {count_species_info_vec[countable_species_index]};
for (uint index: species_info.world_count_item_indices) {
const MolOrRxnCountItem& item = mol_rxn_count_items[index];
assert(item.is_world_mol_count());
const MolOrRxnCountTerm& term = item.terms[0];
uint multiplier = term.get_num_pattern_matches(species->id);
assert(multiplier != 0);
// use the count of this species as tracked in the BNG library
count_values[item.index].inc_or_dec(
term.sign_in_expression, species->get_num_instantiations() * multiplier);
processed_item_indices.insert(index);
}
}
}
// for each partition
for (Partition& p: partitions) {
// for each molecule (if we are counting them and we did not process all of them already)
if (count_mols && processed_item_indices.size() != mol_rxn_count_items.size()) {
for (const Molecule& m: p.get_molecules()) {
if (m.is_defunct()) {
continue;
}
// check whether we are counting these species at all
check_countable_species(m.species_id);
if (countable_species_lut[m.species_id] == NotToBeCounted) {
continue;
}
// for each counting info
for (uint i = 0; i < mol_rxn_count_items.size(); i++) {
// skip already processed count items
if (processed_item_indices.count(i) != 0) {
continue;
}
compute_mol_count_item(p, mol_rxn_count_items[i], m, count_values);
}
} // for molecules
}
if (count_rxns) {
for (const BNG::RxnRule* rxn: world->get_all_rxns().get_rxn_rules_vector()) {
if (!rxn->is_counted()) {
continue;
}
// for each counting info
for (uint i = 0; i < mol_rxn_count_items.size(); i++) {
compute_rxn_count_item(p, mol_rxn_count_items[i], rxn, count_values);
}
} // for rxns
}
} // for partition
for (uint i = 0; i < mol_rxn_count_items.size(); i++) {
// multiply the results by a constant
// (value is different from 1 when the count expression in MDL had a top level multiplication)
count_values[i].value *= mol_rxn_count_items[i].multiplier;
}
}
void MolOrRxnCountEvent::step() {
CountValueVector count_values;
compute_counts(count_values);
// store the counts to buffers
for (uint i = 0; i < mol_rxn_count_items.size(); i++) {
world->get_count_buffer(mol_rxn_count_items[i].buffer_id).add(count_values[i]);
}
}
double MolOrRxnCountEvent::get_single_count_value() {
CountValueVector count_values;
compute_counts(count_values);
assert(count_values.size() == 1);
return count_values[0].value;
}
void MolOrRxnCountEvent::compute_count_species_info(const species_id_t species_id) {
assert(countable_species_lut[species_id] == NotSeenYet);
// we saw this species, might be overwritten
countable_species_lut[species_id] = NotToBeCounted;
CountSpeciesInfo info;
bool matches = false;
// for each counting info
for (MolOrRxnCountItem& count_item: mol_rxn_count_items) {
// and each term
for (MolOrRxnCountTerm& term: count_item.terms) {
if (term.is_rxn_count()) {
// reactions are analyzed in separately in Species::update_rxn_and_custom_flags
// to determine whether species should have SPECIES_FLAG_NEEDS_COUNTED_VOLUME flag
continue;
}
assert(term.is_mol_count());
bool term_matches = false;
if (term.species_pattern_type == SpeciesPatternType::SpeciesId) {
if (term.species_id == species_id) {
term_matches = true;
}
}
else {
assert(term.species_pattern_type == SpeciesPatternType::SpeciesPattern ||
term.species_pattern_type == SpeciesPatternType::MoleculesPattern);
const BNG::Species& species = world->get_all_species().get(species_id);
uint num_term_matches = species.get_pattern_num_matches(term.species_molecules_pattern);
// also the primary compartment id must match
if (term.primary_compartment_id != BNG::COMPARTMENT_ID_NONE &&
term.primary_compartment_id != species.get_primary_compartment_id()) {
num_term_matches = 0;
}
if (num_term_matches > 0) {
// we must also remember that this species id matches the term's pattern
term.species_ids_matching_pattern_w_multiplier_cache[species_id] = num_term_matches;
term_matches = true;
}
}
if (term_matches) {
matches = true;
if (count_item.is_world_mol_count()) {
// optimization for faster counting
info.world_count_item_indices.insert(count_item.index);
}
else {
// there are also other count items besides those in the world_count_item_indices set
info.all_are_world_mol_counts = false;
}
}
} // for count_item.terms
} // for mol_count_items
if (matches) {
count_species_info_vec.push_back(info);
countable_species_lut[species_id] = count_species_info_vec.size() - 1; // ToBeCounted;
}
// Otherwise, CountSpeciesInfo will be destructed automatically.
}
inline void MolOrRxnCountEvent::check_countable_species(const species_id_t species_id) {
assert(species_id != SPECIES_ID_INVALID);
if (species_id >= countable_species_lut.size()) {
// extend the array if we did not see these species yet
countable_species_lut.resize(species_id + 1, NotSeenYet);
}
if (countable_species_lut[species_id] == NotSeenYet) {
// update the info
compute_count_species_info(species_id);
}
assert(countable_species_lut[species_id] != NotSeenYet); // Seen
}
void MolOrRxnCountEvent::dump(const std::string ind) const {
cout << ind << "MolOrRxnCountEvent:\n";
std::string ind2 = ind + " ";
std::string ind4 = ind2 + " ";
BaseEvent::dump(ind2);
cout << ind << " mol_count_infos:\n";
for(uint i = 0; i < mol_rxn_count_items.size(); i++) {
cout << ind2 << i << "\n";
mol_rxn_count_items[i].dump(ind4);
}
}
void MolOrRxnCountEvent::to_data_model(Json::Value& mcell_node) const {
// set global reaction_data_output settings if this is the first
// counting event that we are converting
if (mol_rxn_count_items.empty()) {
return;
}
Json::Value& reaction_data_output = mcell_node[KEY_REACTION_DATA_OUTPUT];
// assuming that there is a single rxn_step value for all
// (period in second on how often to dump the counted data)
// at least this is the only supported option in data model right now
const string& orig_rxn_step = reaction_data_output[KEY_RXN_STEP].asString();
string new_rxn_step = f_to_str(periodicity_interval * world->config.time_unit);
if (orig_rxn_step != "" && orig_rxn_step != new_rxn_step) {
mcell_log(
"Warning: count events use multiple different time steps, this is not supported "
"by data model, keeping only value %s (seconds).\n", orig_rxn_step.c_str()
);
}
else {
reaction_data_output[KEY_RXN_STEP] = new_rxn_step;
}
Json::Value& reaction_output_list = reaction_data_output[KEY_REACTION_OUTPUT_LIST];
for (const MolOrRxnCountItem& info: mol_rxn_count_items) {
Json::Value reaction_output;
info.to_data_model(world, reaction_output);
reaction_output_list.append(reaction_output);
}
}
}
| C++ |
3D | mcellteam/mcell | src4/release_event.h | .h | 9,650 | 303 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_RELEASE_EVENT_H_
#define SRC4_RELEASE_EVENT_H_
#include <vector>
#include "base_event.h"
#include "region_expr.h"
namespace Json {
class Value;
}
namespace MCell {
class Partition;
class Region;
class Wall;
class Grid;
class InitialSurfaceReleases;
class DiffuseReactEvent;
// TODO: replace with defines from API
enum class ReleaseShape {
UNDEFINED = -1, /* Not specified */
SPHERICAL, /* Volume enclosed by a sphere */
// CUBIC, /* Volume enclosed by a cube */ (might be supported, needs to be tested)
// ELLIPTIC, /* Volume enclosed by an ellipsoid */ (might be supported, needs to be tested)
// RECTANGULAR, /* Volume enclosed by a rect. solid */ (might be supported, needs to be tested)
SPHERICAL_SHELL, /* Surface of a sphere */ // not tested yet
REGION, /* Inside/on the surface of an arbitrary region */
// Individual mol. placement by list
LIST,
// Special case for MCell3 compatibility, supports handling of MOLECULE_NUMBER and MOLECULE_DENSITY
// Same functionality as REGION, however implemented slightly differently
INITIAL_SURF_REGION,
};
enum class ReleaseNumberMethod {
INVALID,
CONST_NUM, // used also for ReleaseShape::LIST
GAUSS_NUM, // not supported yet
VOL_NUM,
CONCENTRATION_NUM,
DENSITY_NUM
};
const int NUMBER_OF_TRAINS_UNLIMITED = -1;
// Data structure used to store LIST releases
class SingleMoleculeReleaseInfo {
public:
SingleMoleculeReleaseInfo()
: species_id(SPECIES_ID_INVALID), orientation(ORIENTATION_NONE),
pos(POS_INVALID) {
}
species_id_t species_id;
orientation_t orientation;
Vec3 pos;
};
/**
* Release molecules according to the settings.
*/
class ReleaseEvent: public BaseEvent {
public:
ReleaseEvent(World* world_) :
BaseEvent(EVENT_TYPE_INDEX_RELEASE),
release_site_name(NAME_INVALID),
species_id(SPECIES_ID_INVALID),
release_number_method(ReleaseNumberMethod::INVALID),
release_number(UINT_INVALID),
concentration(FLT_INVALID),
orientation(ORIENTATION_NONE),
release_shape(ReleaseShape::UNDEFINED),
location(FLT_INVALID),
diameter(FLT_INVALID),
region_llf(FLT_INVALID),
region_urb(FLT_INVALID),
// the default values for release pattern are such that there is
// just one release
delay(0),
number_of_trains(1),
train_interval(EPS),
train_duration(EPS),
release_interval(DBL_GIGANTIC),
release_probability(1),
actual_release_time(TIME_INVALID),
current_train_from_0(0),
current_release_in_train_from_0(0),
world(world_),
running_diffuse_event_to_update(nullptr) {
}
void step() override;
// argument may be nullptr
// NOTE: will need extra care for parallel diffusion
void release_immediatelly(DiffuseReactEvent* running_diffuse_event_to_update_) {
update_event_time_for_next_scheduled_time();
running_diffuse_event_to_update = running_diffuse_event_to_update_;
step();
}
// release events must be sorted by the actual release time as well
bool needs_secondary_ordering() override {
return true;
}
double get_secondary_ordering_value() override {
assert(actual_release_time != TIME_INVALID);
return actual_release_time;
}
// handles release patterns,
// WARNING: must be called before the first insertion into the scheduler,
// when no release pattern is set, simply sets event_time to 0
// and on the second call it returns false
bool update_event_time_for_next_scheduled_time() override;
// DiffuseReactEvent must execute only up to this event
// for MCell3 compatibility but otherwise not sure why this is necessary
bool is_barrier() const override { return true; }
void dump(const std::string indent) const override;
void to_data_model(Json::Value& mcell_node) const override;
bool needs_release_pattern() const {
bool single_release_at_t0 = delay == 0 && number_of_trains == 1 && get_num_releases_per_train() == 1;
return !single_release_at_t0;
}
public:
std::string release_site_name; // name of releaser site from which was this event created
species_id_t species_id;
ReleaseNumberMethod release_number_method; // specifies what does the release_number mean
uint release_number; // number of molecules to release
double concentration; // or density for surface releases
orientation_t orientation;
ReleaseShape release_shape; /* Release Shape Flags: controls shape over which to release (enum release_shape_t) */
// SHAPE_SPHERICAL - only volume molecules
Vec3 location;
Vec3 diameter; /* x,y,z diameter for geometrical release shapes */
// SHAPE_REGION
// for surface molecule releases
// limited initialization for pymcell4
// return true if initialization passed
bool initialize_walls_for_release();
// initialized from mcell3 state or in initialize_walls_for_release()
// defines walls of a region for surface release
// TODO: replace with some a better structure
std::vector<CummAreaPWallIndexPair> cumm_area_and_pwall_index_pairs;
RegionExpr region_expr;
// for volume molecule releases into a region
Vec3 region_llf; // note: this is fully specified by the region above, maybe remove in the future
Vec3 region_urb; // note: this is fully specified by the region above as well
// used when release_shape is ReleaseShape::List
std::vector<SingleMoleculeReleaseInfo> molecule_list;
std::string release_pattern_name;
// --- release pattern information ---
double delay;
int number_of_trains; // -1 means that the number of trains is unlimited
double train_interval;
double train_duration;
double release_interval;
// This release does not occur every time, but rather with probability p.
// Either the whole release occurs or none of it does; the probability does not
// apply molecule-by-molecule. release_probability must be in the interval [0, 1].
double release_probability;
private:
double actual_release_time;
// both values are initialized to 0 and counted from 0
int current_train_from_0;
int current_release_in_train_from_0;
World* world;
// if not nullptr, we need to inform this event that there are new
// molecules to be released
DiffuseReactEvent* running_diffuse_event_to_update;
private:
bool skip_due_to_release_probability();
// may end with error
void report_release_failure(const std::string& msg);
uint calculate_number_to_release();
int randomly_remove_molecules(
Partition& p, const MoleculeIdsVector& mol_ids_in_region, int number_to_remove);
// for surface molecule releases
int vacuum_from_regions(int number_to_remove);
void release_onto_regions(int& computed_release_number);
// for volume molecule releases into a region
bool is_point_inside_region_expr_recursively(
Partition& p, const Vec3& pos, const RegionExprNode* region_expr_node
);
uint num_vol_mols_from_conc(bool &exact_number);
int vacuum_inside_regions(int number_to_remove);
void release_inside_regions(int& computed_release_number);
// for volume molecule releases
void release_ellipsoid_or_rectcuboid(int computed_release_number);
// for list releases
void release_list();
// for releases specified by MODIFY_SURFACE_REGIONS -> MOLECULE_NUMBER or MOLECULE_DENSITY
void init_surf_mols_by_number(
Partition& p, const Region& reg, const InitialSurfaceReleases& info);
void init_surf_mols_by_density(
Partition& p, Wall& w, std::map<species_id_t, uint>& num_released_per_species);
void release_initial_molecules_onto_surf_regions();
void schedule_for_immediate_diffusion_if_needed(
const molecule_id_t id, const WallTileIndexPair& where_released = WallTileIndexPair());
double get_release_delay_time() const {
if (cmp_eq(actual_release_time, event_time)) {
return 0; // same as event time
}
else {
return actual_release_time - event_time;
}
}
int get_num_releases_per_train() const {
assert(release_interval != 0);
if (train_duration > EPS) {
// -EPS is needed to deal with precision issues even when we
// are strictly (<) comparing current and end time
return ceil_f((train_duration - EPS) / release_interval);
}
else {
// however, there must be at least one release
return ceil_f(train_duration / release_interval);
}
}
std::string release_pattern_to_data_model(Json::Value& mcell_node) const;
void to_data_model_as_one_release_site(
Json::Value& mcell_node,
const species_id_t species_id_override,
const orientation_t orientation_override,
// points_list indices are set only when
// release_shape == ReleaseShape::LIST
const std::string& name_override,
const uint points_list_begin_index,
const uint points_list_end_index
) const;
};
// utilities used also from ConcentrationClampReleaseEvent
size_t cum_area_bisect_high(const std::vector<CummAreaPWallIndexPair>& array, double val);
void dump_cumm_area_and_pwall_index_pairs(
const std::vector<CummAreaPWallIndexPair>& cumm_area_and_pwall_index_pairs, const std::string ind);
} // namespace mcell
#endif // SRC4_RELEASE_EVENT_H_
| Unknown |
3D | mcellteam/mcell | src4/diffuse_react_event.cpp | .cpp | 114,555 | 3,151 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
// TODO: make this file shorter
#include <iostream>
#include <sstream>
#include <algorithm>
#include <boost/container/flat_set.hpp>
#include "api/mol_wall_hit_info.h"
#include "api/reaction_info.h"
#include "api/callbacks.h"
#include "rng.h"
#include "mcell_structs_shared.h"
#include "logging.h"
#include "diffuse_react_event.h"
#include "defines.h"
#include "world.h"
#include "partition.h"
#include "geometry.h"
#include "grid_position.h"
#include "region_utils.h"
#include "debug_config.h"
#include "debug.h"
// include implementations of utility functions
#include "geometry_utils.h"
#include "geometry_utils.inl"
#include "collision_utils.inl"
#include "exact_disk_utils.inl"
#include "diffusion_utils.inl"
#include "rxn_utils.inl"
#include "grid_utils.inl"
#include "wall_utils.inl"
using namespace std;
using namespace BNG;
namespace MCell {
void DiffuseReactEvent::step() {
assert(world->get_partitions().size() == 1 && "Must extend cache to handle multiple partitions");
assert(cmp_eq(event_time, (double)world->stats.get_current_iteration()) &&
"DiffuseReactEvent is expected to be run exactly at iteration starts");
// for each partition
for (Partition& p: world->get_partitions()) {
// diffuse molecules that are scheduled for this iteration
p.get_molecules_ready_for_diffusion(molecules_ready_array);
diffuse_molecules(p, molecules_ready_array);
}
}
void DiffuseReactEvent::diffuse_molecules(Partition& p, const MoleculeIdsVector& molecule_ids) {
// we need to strictly follow the ordering in mcell3, therefore steps 2) and 3) do not use the time
// for which they were scheduled but rather simply the order in which these "microevents" were created
std::vector<DiffuseAction> delayed_diffusions;
#ifndef MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
// 1) first diffuse already existing molecules
uint existing_mols_count = molecule_ids.size();
for (size_t i = 0; i < existing_mols_count; i++) {
molecule_id_t id = molecule_ids[i];
// here we compute both release delay and also partially sort molecules to be diffused
// so that molecules not scheduled for he beginning of the event are diffused later
// (but according to their id, not time)
double diffusion_delay = p.get_m(id).diffusion_time - event_time;
if (cmp_eq(diffusion_delay, 0.0)) { // NOTE: this can be optimized
// existing molecules or created at the beginning of this timestep
// - simulate whole time step for this molecule
diffuse_single_molecule(p, id, WallTileIndexPair());
}
else {
// released during this iteration but not at the beginning, postpone its diffusion
assert(diffusion_delay > 0 && diffusion_delay < time_up_to_next_barrier);
delayed_diffusions.push_back(DiffuseAction(id));
}
}
#else
for (molecule_id_t id: molecule_ids) {
// merge with actions
new_diffuse_actions.push_back(DiffuseAction(id));
}
#endif
// 2) mcell3 first handles diffusions of existing molecules, then the delayed diffusions
// actions created by the diffusion of all these molecules are handled later
for (size_t i = 0; i < delayed_diffusions.size(); i++) {
const DiffuseAction& action = delayed_diffusions[i];
Molecule& m = p.get_m(action.id);
diffuse_single_molecule(
p, action.id,
action.where_created_this_iteration
);
}
// 3) simulate remaining time of molecules created with reactions or
// scheduled unimolecular reactions
// need to call .size() each iteration because the size can increase,
// again, we are using it as a queue and we do not follow the time when
// they were created
#ifndef MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
for (size_t i = 0; i < new_diffuse_actions.size(); i++) {
DiffuseAction& action = new_diffuse_actions[i];
diffuse_single_molecule(
p, action.id,
action.where_created_this_iteration // making a copy of this pair
);
}
#else
for (size_t i = 0; i < new_diffuse_actions.size(); i++) {
// find the closest event that we did not process yet
uint best_index = UINT_INVALID;
double best_time = TIME_FOREVER;
for (size_t k = 0; k < new_diffuse_actions.size(); k++) {
molecule_id_t id = new_diffuse_actions[k].id;
if (id == MOLECULE_ID_INVALID) {
continue;
}
const Molecule& m = p.get_m(id);
if (m.diffusion_time < best_time) {
best_index = k;
best_time = m.diffusion_time;
}
}
assert(best_index != UINT_INVALID);
DiffuseAction& action = new_diffuse_actions[best_index];
diffuse_single_molecule(
p, action.id,
action.where_created_this_iteration // making a copy of this pair
);
// invalidate this action
new_diffuse_actions[best_index].id = MOLECULE_ID_INVALID;
}
#endif
new_diffuse_actions.clear();
}
inline double DiffuseReactEvent::get_max_time(Partition& p, Molecule& m) {
const Species& species = p.get_species(m.species_id);
double diffusion_time = m.diffusion_time;
double unimol_rxn_time = m.unimol_rxn_time;
double time_from_event_start = m.diffusion_time - event_time;
// clamp to barrier time
double max_time = time_up_to_next_barrier - time_from_event_start;
// clamp to unimol_rx time
if (unimol_rxn_time != TIME_INVALID &&
unimol_rxn_time < diffusion_time + max_time) {
assert(unimol_rxn_time >= diffusion_time);
max_time = unimol_rxn_time - diffusion_time;
}
if (!m.has_flag(MOLECULE_FLAG_MATURE) &&
species.time_step > DIFFUSE_REACT_EVENT_PERIODICITY) {
// - newly created particles that have long time steps gradually increase
// their timestep to the full value,
// - this behavior is here due to unbinding events so that the molecule
// does not diffuse so far when in reality it could re-bind
double age_dependent_max_time = 1.0 + 0.2 * (diffusion_time - m.birthday);
if (max_time > age_dependent_max_time) {
max_time = age_dependent_max_time;
}
if (age_dependent_max_time > species.time_step) {
// we are alive for long enough, no need to increase the time_step gradually anymore
m.set_flag(MOLECULE_FLAG_MATURE);
}
}
return max_time;
}
void DiffuseReactEvent::diffuse_single_molecule(
Partition& p,
const molecule_id_t m_id,
WallTileIndexPair wall_tile_pair_where_created_this_iteration // set only for newly created molecules
) {
Molecule& m_initial = p.get_m(m_id);
double diffusion_start_time = m_initial.diffusion_time;
assert(cmp_ge(diffusion_start_time, event_time, EPS) && cmp_le(diffusion_start_time, event_time + periodicity_interval, EPS));
assert(m_initial.birthday != TIME_INVALID && m_initial.birthday <= diffusion_start_time);
if (m_initial.is_defunct()) {
return;
}
if (m_initial.unimol_rxn_time != TIME_INVALID && m_initial.unimol_rxn_time <= diffusion_start_time) {
// call to this diffuse_single_molecule was scheduled for time of an unimol rxn
// (the <= is to handle floating point imprecisions)
// may invalidate molecule references
bool molecule_survived = react_unimol_single_molecule(p, m_id);
if (!molecule_survived) {
return;
}
}
Molecule& m = p.get_m(m_id);
// if the molecule is a "newbie", its unimolecular reaction was not yet scheduled,
assert(
!(m.has_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN) && m.has_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE)) &&
"Only one of these flags may be set"
);
if ((m.flags & (MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN | MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE)) != 0) {
if (m.has_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN)) {
m.clear_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
pick_unimol_rxn_class_and_set_rxn_time(p, diffusion_start_time, m);
}
// we might need to change the reaction rate right now
if (m.has_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE) && cmp_eq(m.unimol_rxn_time, diffusion_start_time)) {
assert(m.unimol_rxn_time != TIME_INVALID);
m.clear_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE);
pick_unimol_rxn_class_and_set_rxn_time(p, diffusion_start_time, m);
}
}
#ifdef DEBUG_DIFFUSION
const BNG::Species& debug_species = p.get_species(m.species_id);
DUMP_CONDITION4(
m.id,
#ifdef DUMP_NONDIFFUSING_VMS
const char* title =
(debug_species.can_diffuse()) ?
(m.is_vol() ? "Diffusing vm:" : "Diffusing sm:") :
(m.is_vol() ? "Not diffusing vm:" : "Not diffusing sm:");
m.dump(p, "", title, world->get_current_iteration(), diffusion_start_time);
#else
if (debug_species.can_diffuse()) {
const char* title = (m.is_vol() ? "Diffusing vm:" : "Diffusing sm:");
m.dump(p, "", title, world->get_current_iteration(), diffusion_start_time);
}
#endif
);
#endif
// max_time is the time for which we should simulate the diffusion
double max_time = get_max_time(p, m);
if (m.is_vol()) {
diffuse_vol_molecule(
p, m,
max_time,
diffusion_start_time,
wall_tile_pair_where_created_this_iteration
);
}
else {
diffuse_surf_molecule(
p, m, max_time, diffusion_start_time
);
}
// update time for which the molecule should be scheduled next
Molecule& m_for_sched_update = p.get_m(m_id);
if (!m_for_sched_update.is_defunct()) {
double event_end_time = p.stats.get_current_iteration() + 1;
const Species& species = world->get_all_species().get(m_for_sched_update.species_id);
// TODO: for some reason, MCell3 calls diffusion of non-diffusible surface molecules,
// this is not needed since they cannot react but for compatibility we must keep this behavior
if (species.can_diffuse() || species.has_flag(SPECIES_FLAG_CAN_SURFSURF)) {
m_for_sched_update.diffusion_time += max_time;
// - for MCell3 compatibility purposes, we must not keep any unimol rxn for the next iteration
// so we use precise comparison here
// - on the other hand, we do not want to simulate diffusion for a tiny amount of time,
// so we use tolerance when checking whether we should keep diffusion itself for
// the next time, the error accumulation can be quite big, therefore we are using SQRT_EPS
if (
( m_for_sched_update.unimol_rxn_time != TIME_INVALID &&
m_for_sched_update.unimol_rxn_time < event_end_time
) ||
before_this_iterations_end(m_for_sched_update.diffusion_time)
) {
// reschedule molecule for this iteration because we did not use up all its time
DiffuseAction diffuse_action(m_for_sched_update.id);
new_diffuse_actions.push_back(diffuse_action);
}
else {
// round diffusion_time to a whole number if it is close to it,
// this did not give any error for the test that were available when this
// code was implemented
double rounded_dt = round_f(m_for_sched_update.diffusion_time);
if (cmp_eq(m_for_sched_update.diffusion_time, rounded_dt, SQRT_EPS)) {
m_for_sched_update.diffusion_time = rounded_dt;
}
}
}
else {
// cannot diffuse
if (m_for_sched_update.unimol_rxn_time != TIME_INVALID) {
// schedule for its unimol rxn
m_for_sched_update.diffusion_time = m_for_sched_update.unimol_rxn_time;
// reschedule molecule for unimol rxn this iteration
if (m_for_sched_update.unimol_rxn_time < event_end_time) {
DiffuseAction diffuse_action(m_for_sched_update.id);
new_diffuse_actions.push_back(diffuse_action);
}
}
else {
// no need to schedule at all
m_for_sched_update.diffusion_time = TIME_FOREVER;
}
}
}
}
// ---------------------------------- volume diffusion ----------------------------------
void sort_collisions_by_time(CollisionsVector& molecule_collisions) {
sort( molecule_collisions.begin(), molecule_collisions.end(),
[ ]( const Collision& lhs, const Collision& rhs )
{
assert((lhs.type != CollisionType::VOLMOL_SURFMOL && lhs.type != CollisionType::SURFMOL_SURFMOL) &&
"Ray trace can return only vol-wall or vol-vol collisions");
if (lhs.time < rhs.time) {
return true;
}
else if (lhs.time > rhs.time) {
return false;
}
else if (lhs.type == CollisionType::VOLMOL_VOLMOL && rhs.type == CollisionType::VOLMOL_VOLMOL) {
// mcell3 returns collisions with molecules ordered descending by the molecule index
// we need to maintain this behavior (needed only for identical results)
return lhs.colliding_molecule_id > rhs.colliding_molecule_id;
}
else {
return false;
}
}
);
}
void DiffuseReactEvent::diffuse_vol_molecule(
Partition& p,
Molecule& vm,
double& max_time,
const double diffusion_start_time,
WallTileIndexPair& wall_tile_pair_where_created_this_iteration
) {
molecule_id_t vm_id = vm.id;
const BNG::Species& species = p.get_species(vm.species_id);
if (!species.can_diffuse()) {
return;
}
p.stats.inc_diffuse_3d_calls();
// diffuse each molecule - get information on position change
Vec3 remaining_displacement;
double steps = 1.0;
double t_steps = 1.0;
double rate_factor = 1.0;
double r_rate_factor = 1.0;
DiffusionUtils::compute_vol_displacement(
p, species, vm, max_time, world->rng,
remaining_displacement, rate_factor, r_rate_factor, steps, t_steps
);
#ifdef DEBUG_TIMING
DUMP_CONDITION4(
vm_id,
dump_vol_mol_timing(
"- Timing vm", p.stats.get_current_iteration(), vm_id,
diffusion_start_time, max_time, vm.unimol_rxn_time,
rate_factor, r_rate_factor, steps, t_steps
);
);
#endif
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION4(
vm_id,
if (species.can_diffuse()) {
remaining_displacement.dump(" displacement:", "");
cout << "t_steps: " << t_steps << "\n";
}
);
#endif
RayTraceState state;
CollisionsVector molecule_collisions;
bool was_defunct = false;
wall_index_t last_hit_wall_index = WALL_INDEX_INVALID;
double elapsed_molecule_time = diffusion_start_time; // == vm->t
bool can_vol_react = species.can_vol_react();
do {
state =
ray_trace_vol(
p, world->rng,
vm_id /* changes position */,
can_vol_react,
last_hit_wall_index,
remaining_displacement,
molecule_collisions
);
if (molecule_collisions.size() > 1) {
sort_collisions_by_time(molecule_collisions);
}
#ifdef DEBUG_COLLISIONS
DUMP_CONDITION4(
vm_id,
Collision::dump_array(p, molecule_collisions);
);
#endif
// evaluate and possible execute collisions and reactions
for (Collision& collision: molecule_collisions) {
#if POS_T_BYTES == 8
assert(collision.time >= 0 && collision.time <= 1);
#else
assert(collision.time >= 0 && cmp_le(collision.time, 1, (double)POS_SQRT_EPS));
#endif
if (collision.is_vol_mol_vol_mol_collision()) {
p.stats.inc_vol_mol_vol_mol_collisions();
// ignoring immediate collisions
if (CollisionUtils::is_immediate_collision(collision.time)) {
continue;
}
// evaluate reaction associated with this collision
// for now, do the change right away, but we might need to cache these changes and
// do them after all diffusions were finished
// warning: might invalidate references to p.volume_molecules array! returns true in that case
// also, if this is a reaction where this diffused product is kept, we simply continue with diffusion
if (collide_and_react_with_vol_mol(
p, collision, remaining_displacement,
t_steps, r_rate_factor, elapsed_molecule_time)
) {
// molecule was destroyed
was_defunct = true;
break;
}
}
else if (collision.is_wall_collision()) {
Molecule& vm_new_ref = p.get_m(vm_id);
Wall& colliding_wall = p.get_wall(collision.colliding_wall_index);
// call callback if the user registered one
if (world->get_callbacks().needs_callback_for_mol_wall_hit(colliding_wall.object_id, vm_new_ref.species_id)) {
// prepare part of information
shared_ptr<API::MolWallHitInfo> info = make_shared<API::MolWallHitInfo>();
info->molecule_id = vm_new_ref.id;
info->geometry_object_id = colliding_wall.object_id; // I would need Model to be accessible here
info->partition_wall_index = colliding_wall.index; // here as well
info->time = elapsed_molecule_time + t_steps * collision.time;
info->pos3d = collision.pos.to_vec();
info->time_before_hit = elapsed_molecule_time;
info->pos3d_before_hit = vm_new_ref.v.pos.to_vec();
world->get_callbacks().do_mol_wall_hit_callbacks(info);
}
#ifdef DEBUG_WALL_COLLISIONS
cout << "Wall collision: \n";
const GeometryObject* geom_obj = p.get_geometry_object_if_exists(colliding_wall.object_id);
assert(geom_obj != nullptr);
cout << " mol id: " << vm_new_ref.id << ", species: " << p.all_species.get(vm_new_ref.species_id).name << "\n";
cout << " obj: " << geom_obj->name << ", id: " << geom_obj->id << "\n";
cout << " wall id: " << colliding_wall.id << "\n";
cout << " time: " << double(world->get_current_iteration()) + collision.time << "\n";
cout << " pos: " << collision.pos << "\n";
#endif
// check possible reaction with surface molecules
if (p.get_species(vm_new_ref.species_id).has_flag(SPECIES_FLAG_CAN_VOLSURF) && colliding_wall.has_initialized_grid()) {
int collide_res = collide_and_react_with_surf_mol(
p, collision, r_rate_factor,
wall_tile_pair_where_created_this_iteration,
last_hit_wall_index,
remaining_displacement,
t_steps,
elapsed_molecule_time
);
if (collide_res == 1) { // FIXME: use enum
was_defunct = true;
break;
}
else if (collide_res == 0) {
// flip, position and counted vol change was already handled in outcome_products_random
// continue with diffusion
break;
}
}
// check possible reaction with walls
if (p.get_species(vm_new_ref.species_id).has_flag(SPECIES_FLAG_CAN_VOLWALL)) {
WallRxnResult collide_res = collide_and_react_with_walls(p, collision, r_rate_factor, elapsed_molecule_time, t_steps);
if (collide_res == WallRxnResult::TRANSPARENT) {
// update molecules' counted volume, time and displacement and continue
was_defunct = !cross_transparent_wall(
p, collision, vm_new_ref, remaining_displacement,
t_steps, elapsed_molecule_time, last_hit_wall_index
);
// continue with diffusion
break;
}
else if (collide_res == WallRxnResult::DESTROYED) {
was_defunct = true;
}
else if (collide_res == WallRxnResult::REFLECT) {
// reflect in reflect_or_periodic_bc and continue with diffusion
}
else {
assert(false);
}
}
if (!was_defunct) {
elapsed_molecule_time += t_steps * collision.time;
// if a molecule was reflected, changes its position to the reflection point
int res = CollisionUtils::reflect_from_wall(
p, collision,
vm_new_ref, remaining_displacement, t_steps, last_hit_wall_index
);
p.stats.inc_mol_wall_reflections();
assert(res == 0 && "Periodic box BCs are not supported yet");
}
break; // we reflected and did not react, do ray_trace again
}
}
assert(p.get_m(vm_id).v.subpart_index == p.get_subpart_index(p.get_m(vm_id).v.pos));
} while (unlikely(state != RayTraceState::FINISHED && !was_defunct));
if (!was_defunct) {
// need to get a new reference
Molecule& m_new_ref = p.get_m(vm_id);
if (m_new_ref.is_vol()) {
// change molecules' subpartition
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION4(
vm_id,
// the subtraction of diffusion_time_step doesn't make much sense but is needed to make the dump the same as in mcell3
// need to check it further
m_new_ref.dump(p, "", "- Final vm position:", world->get_current_iteration(), 0);
);
#endif
// are we still in the same partition or do we need to move?
bool move_to_another_partition = !p.in_this_partition(m_new_ref.v.pos);
if (move_to_another_partition) {
Vec3 pos_um = m_new_ref.v.pos * p.config.length_unit;
Vec3 origin_um = p.get_origin_corner() * p.config.length_unit;
Vec3 opposite_um = p.get_opposite_corner() * p.config.length_unit;
const BNG::Species& s = p.get_species(m_new_ref.species_id);
world->fatal_error(
"Molecule with species " + s.name + " (id: " + to_string(m_new_ref.id) + ") "
"escaped the simulation area defined by partition size.\n"
"Diffused molecule reached position (" +
to_string(pos_um.x) + ", " + to_string(pos_um.y) + ", " + to_string(pos_um.z) + "). "
"MCell4 requires a fixed-size simulation 3D space compared to MCell3 that allows unlimited space.\n"
"One can create a geometry object box that keeps all molecules within a given area.\n"
"This box can either reflect molecules (by default) or destroy the molecules with an absorptive surface class.\n"
"Another option is to increase the partition size through CellBlender settings Partitions or "
"through Model.config.partition_dimension.\n"
"Partition is a cube with these corner points: "
"(" + to_string(origin_um.x) + ", " + to_string(origin_um.y) + ", " + to_string(origin_um.z) + ") and " +
"(" + to_string(opposite_um.x) + ", " + to_string(opposite_um.z) + ", " + to_string(opposite_um.z) + ")."
);
}
// change subpartition
p.update_molecule_reactants_map(m_new_ref);
}
}
}
// collect possible collisions for molecule vm that has to displace by remaining_displacement,
// returns possible collisions in molecule_collisions, new position in new_pos and
// index of the new subparition in new_subpart_index
// later, this will check collisions until a wall is hit
// we assume that wall collisions do not occur so often
// inlining of this function does not help with performance
RayTraceState ray_trace_vol(
Partition& p,
rng_state& rng,
const molecule_id_t vm_id, // molecule that we are diffusing, we are changing its pos and possibly also subvolume
const bool can_vol_react,
const wall_index_t last_hit_wall_index, // is WALL_INDEX_INVALID when our molecule did not reflect from anything this diffusion step yet
Vec3& remaining_displacement, // in/out - recomputed if there was a reflection
CollisionsVector& collisions // both mol mol and wall collisions
) {
Molecule& vm = p.get_m(vm_id);
p.stats.inc_ray_voxel_tests();
RayTraceState res_state = RayTraceState::FINISHED;
collisions.clear();
pos_t radius = p.config.rxn_radius_3d;
// if we would get out of this partition, cut off the displacement
// so we check collisions just here
Vec3 partition_displacement;
if (!p.in_this_partition(vm.v.pos + remaining_displacement)) {
partition_displacement = CollisionUtils::get_displacement_up_to_partition_boundary(p, vm.v.pos, remaining_displacement);
}
else {
partition_displacement = remaining_displacement;
}
// first get what subpartitions might be relevant
SubpartIndicesVector crossed_subparts_for_walls;
SubpartIndicesSet crossed_subparts_for_molecules;
#ifdef NDEBUG
crossed_subparts_for_molecules.resize(16);
#endif
subpart_index_t last_subpart_index = CollisionUtils::collect_crossed_subparts(
p, vm, partition_displacement,
radius, p.config.subpart_edge_length,
can_vol_react, true,
crossed_subparts_for_walls, crossed_subparts_for_molecules
);
#ifndef NDEBUG
if (can_vol_react) {
// crossed subparts must contain our own subpart
assert(crossed_subparts_for_molecules.count(vm.v.subpart_index) == 1);
bool debug_found = false;
for (subpart_index_t debug_index: crossed_subparts_for_walls) {
if (debug_index == vm.v.subpart_index) {
debug_found = true;
break;
}
}
assert(debug_found && "Did not find the starting subpartition in crossed subparts for walls");
// also, each subpart from a wall must be present when checking molecules
for (subpart_index_t debug_index: crossed_subparts_for_walls) {
assert(crossed_subparts_for_molecules.count(debug_index) == 1);
}
}
#endif
// changed when wall was hit
Vec3 displacement_up_to_wall_collision = remaining_displacement;
// check wall collisions in the crossed subparitions
bool wall_hit_in_last_subpart = false;
if (!crossed_subparts_for_walls.empty()) {
Collision closest_collision;
#if POS_T_BYTES == 4
CollisionsVector tentative_collisions;
#endif
for (subpart_index_t subpart_w_walls_index: crossed_subparts_for_walls) {
bool collision_found =
CollisionUtils::get_closest_wall_collision( // mcell3 does this only for the current subvol
p,
vm,
subpart_w_walls_index,
last_hit_wall_index,
rng,
remaining_displacement,
displacement_up_to_wall_collision, // may be update in case we need to 'redo' the collision detection
closest_collision
#if POS_T_BYTES == 4
, tentative_collisions
#endif
);
// stop at first crossing because crossed_subparts_for_walls are ordered
// and we are sure that if we hit a wall in the actual subpartition, we cannot
// possibly hit another wall in a subpartition that follows
if (collision_found) {
collisions.push_back(closest_collision);
res_state = RayTraceState::RAY_TRACE_HIT_WALL;
wall_hit_in_last_subpart = last_subpart_index == subpart_w_walls_index;
break;
}
}
// float32 implementation may find collisions but in unexpected subpartitions,
// we must not ignore them - select the closes one
#if POS_T_BYTES == 4
if (res_state != RayTraceState::RAY_TRACE_HIT_WALL && !tentative_collisions.empty()) {
sort_collisions_by_time(tentative_collisions);
collisions.push_back(tentative_collisions[0]);
res_state = RayTraceState::RAY_TRACE_HIT_WALL;
}
#endif
}
if (can_vol_react) {
if (res_state == RayTraceState::RAY_TRACE_HIT_WALL && !wall_hit_in_last_subpart) {
// recompute collect_crossed_subparts if there was a wall collision
// however, do not recompute if we would get practically the same result because we hit a wall in the last subpart
// NOTE: this can be in theory done more efficiently if we knew the order of subpartitions that we hit in the previous call
#ifdef NDEBUG
crossed_subparts_for_molecules.clear_no_resize();
#else
crossed_subparts_for_molecules.clear();
#endif
crossed_subparts_for_walls.clear();
CollisionUtils::collect_crossed_subparts(
p, vm, displacement_up_to_wall_collision,
radius, p.config.subpart_edge_length,
true, false,
crossed_subparts_for_walls, crossed_subparts_for_molecules
);
}
// check molecule collisions for each SP
for (subpart_index_t subpart_index: crossed_subparts_for_molecules) {
// get cached reacting molecules for this SP
const MoleculeIdsSet& sp_reactants = p.get_volume_molecule_reactants(subpart_index, vm.species_id);
// for each molecule in this SP
for (molecule_id_t colliding_vm_id: sp_reactants) {
CollisionUtils::collide_mol_loop_body(
p,
vm,
colliding_vm_id,
remaining_displacement,// needs the full displacement to compute reaction time displacement_up_to_wall_collision,
radius,
collisions
);
}
}
}
if (res_state == RayTraceState::FINISHED) {
vm.v.pos = vm.v.pos + remaining_displacement;
vm.v.subpart_index = p.get_subpart_index(vm.v.pos);
}
return res_state; // no wall was hit
}
// handle collision of two volume molecules: checks probability of reaction,
// executes this reaction, removes reactants and creates products
// returns true if the first reactant was destroyed
bool DiffuseReactEvent::collide_and_react_with_vol_mol(
Partition& p,
Collision& collision,
Vec3& displacement,
const double t_steps,
const double r_rate_factor,
const double elapsed_molecule_time
) {
Molecule& colliding_molecule = p.get_m(collision.colliding_molecule_id); // am
Molecule& diffused_molecule = p.get_m(collision.diffused_molecule_id); // m
// returns 1 when there are no walls at all
double factor = ExactDiskUtils::exact_disk(
p, collision.pos, displacement, p.config.rxn_radius_3d,
diffused_molecule, colliding_molecule,
p.config.use_expanded_list
);
// Negative value of factor has two meanings:
// factor == -2 (i.e. == TARGET_OCCLUDED_RES) means reaction is blocked by a wall
// (factor < 0 && factor >= -1) means target is near reflective boundary so
// we need to place the product at the location of target
// if exact_disk() returned with TARGET_OCCLUDED_RES
if (factor == -2) {
return false; // reaction blocked by a wall
}
// NOTE TEST: force collision.pos to position of target
// collision.pos = colliding_molecule.v.pos;
if (factor < 0 && factor >= -1) {
// target and loc are near wall reflective to target
// place product at location of target molecule
factor *= -1; // set factor back to positive value for this case only
// NOTE TEST: do not set collision.pos to position of target
collision.pos = colliding_molecule.v.pos;
}
RxnClass* rxn_class = collision.rxn_class;
assert(rxn_class != nullptr);
double absolute_collision_time = elapsed_molecule_time + t_steps * collision.time;
// rx->prob_t is always NULL in out case update_probs(world, rx, m->t);
// returns which reaction pathway to take
double scaling = factor * r_rate_factor;
int i = RxnUtils::test_bimolecular(
p, rxn_class, world->rng, colliding_molecule, diffused_molecule, scaling, 0, absolute_collision_time);
if (i < RX_LEAST_VALID_PATHWAY) {
return false;
}
else {
// might invalidate references
int j = outcome_bimolecular(p, collision, i, absolute_collision_time);
assert(j == RX_DESTROY || j == RX_A_OK);
return j == RX_DESTROY;
}
}
/******************************************************************************
*
* collide_and_react_with_surf_mol is a helper function used in diffuse_3D to
* handle collision of a diffusing 3D molecule with a surface molecule
*
* Return values:
*
* -1 : nothing happened - continue on with next smash targets
* 0 : reaction happened and we still exist but are done with the current smash
* 1 : reaction happened and we are destroyed
* target
*
******************************************************************************/
// TODO: return enum
int DiffuseReactEvent::collide_and_react_with_surf_mol(
Partition& p,
const Collision& collision,
const double r_rate_factor,
WallTileIndexPair& where_created_this_iteration,
wall_index_t& last_hit_wall_index,
Vec3& remaining_displacement,
double& t_steps,
double& elapsed_molecule_time
) {
Wall& wall = p.get_wall(collision.colliding_wall_index);
Grid& grid = wall.grid;
tile_index_t j = GridUtils::xyz2grid_tile_index(p, collision.pos, wall);
assert(j != TILE_INDEX_INVALID);
molecule_id_t colliding_mol_id = grid.get_molecule_on_tile(j);
if (colliding_mol_id == MOLECULE_ID_INVALID) {
return -1;
}
orientation_t collision_orientation = ORIENTATION_DOWN;
if (collision.type == CollisionType::WALL_FRONT) {
collision_orientation = ORIENTATION_UP;
}
Molecule& colliding_molecule = p.get_m(colliding_mol_id);
assert(colliding_molecule.is_surf());
Molecule& diffused_molecule = p.get_m(collision.diffused_molecule_id); // m
assert(diffused_molecule.is_vol());
// Avoid rebinding - i.e. when we created a volume molecule from a surf+vol->surf+vol
// reaction, we do not want the molecule to react again
if (where_created_this_iteration.wall_index == wall.index &&
where_created_this_iteration.tile_index == j) {
// However, let this occur next time
where_created_this_iteration.wall_index = WALL_INDEX_INVALID;
where_created_this_iteration.tile_index = TILE_INDEX_INVALID;
return -1;
}
RxnClassesVector matching_rxn_classes;
RxnUtils::trigger_bimolecular(
p.bng_engine,
diffused_molecule, colliding_molecule,
collision_orientation, colliding_molecule.s.orientation,
matching_rxn_classes
);
if (matching_rxn_classes.empty()) {
return -1;
}
assert(matching_rxn_classes.size() == 1 && "There should be max 1 rxn class");
// FIXME: this code is very similar to code in react_2D_all_neighbors
small_vector<double> scaling_coefs;
for (size_t i = 0; i < matching_rxn_classes.size(); i++) {
const RxnClass* rxn = matching_rxn_classes[i];
assert(rxn != nullptr);
scaling_coefs.push_back(r_rate_factor / grid.binding_factor);
}
double collision_time = elapsed_molecule_time + t_steps * collision.time;
int selected_rxn_pathway;
if (matching_rxn_classes.size() == 1) {
selected_rxn_pathway = RxnUtils::test_bimolecular(
p, matching_rxn_classes[0], world->rng,
diffused_molecule, colliding_molecule,
scaling_coefs[0], 0, collision_time);
}
else {
mcell_error("Internal error: multiple rxn classes should not be needed for surf mol rxn.");
}
if (selected_rxn_pathway < RX_LEAST_VALID_PATHWAY) {
return -1; /* No reaction */
}
/* run the reaction */
Collision rxn_collision = Collision(
CollisionType::VOLMOL_SURFMOL,
&p,
collision.diffused_molecule_id,
collision_time, // unused? FIXME: find places where the collision time is not used and remove
collision.pos,
colliding_molecule.id,
matching_rxn_classes[0]
);
int outcome_bimol_result = outcome_bimolecular(
p, rxn_collision, selected_rxn_pathway, collision_time
);
if (outcome_bimol_result == RX_DESTROY) {
return 1;
}
else if (outcome_bimol_result == RX_FLIP) {
// update position and timing for flipped molecule
double t_smash = collision.time;
Molecule& vm = p.get_m(collision.diffused_molecule_id);
// update position and subpart if needed
vm.v.pos = collision.pos;
vm.v.subpart_index = p.get_subpart_index(vm.v.pos);
CollisionUtils::update_counted_volume_id_when_crossing_wall(
p, wall, collision.get_orientation_against_wall(), vm);
// TODO: same code is on multiple places, e.g. in cross_transparent_wall,
// make a function for it
remaining_displacement = remaining_displacement * Vec3(1.0 - t_smash);
elapsed_molecule_time += t_steps * t_smash;
t_steps *= (1.0 - t_smash);
if (t_steps < EPS) {
t_steps = EPS;
}
last_hit_wall_index = wall.index;
return 0;
}
else {
last_hit_wall_index = wall.index;
return -1;
}
}
/******************************************************************************
*
* check_collisions_with_walls is a helper function used in diffuse_3D to handle
* collision of a diffusing molecule with a wall
*
* Return values:
*
* -1 : nothing happened - continue on with next smash targets
* 0 : reaction happened and we still exist but are done with the current smash
* target
* 1 : reaction happened and we are destroyed
*
******************************************************************************/
inline WallRxnResult DiffuseReactEvent::collide_and_react_with_walls(
Partition& p,
Collision& collision,
const double r_rate_factor,
const double elapsed_molecule_time,
const double t_steps
) {
assert(collision.type == CollisionType::WALL_FRONT || collision.type == CollisionType::WALL_BACK);
Molecule& diffused_molecule = p.get_m(collision.diffused_molecule_id); // m
assert(diffused_molecule.is_vol());
Wall& wall = p.get_wall(collision.colliding_wall_index);
RxnClassesVector matching_rxn_classes;
orientation_t orient = (collision.type == CollisionType::WALL_FRONT) ? ORIENTATION_UP : ORIENTATION_DOWN;
RxnUtils::trigger_intersect(p, diffused_molecule, orient, wall, true, matching_rxn_classes);
if (matching_rxn_classes.empty() ||
(matching_rxn_classes.size() == 1 && matching_rxn_classes[0]->type == BNG::RxnType::Reflect)) {
return WallRxnResult::REFLECT;
}
const BNG::RxnClass* transp_rxn_class = nullptr;
for (const BNG::RxnClass* rxn: matching_rxn_classes) {
if (rxn->is_transparent_type()) {
transp_rxn_class = rxn;
break;
}
}
if (transp_rxn_class != nullptr) {
// we are crossing this wall
assert(matching_rxn_classes.size() == 1 && "Expected only a single transparent rxn for transparent walls");
return WallRxnResult::TRANSPARENT;
}
/* Collisions with the surfaces declared REFLECTIVE are treated similar to
* the default surfaces after this loop. */
BNG::rxn_class_index_t rxn_class_index = BNG::RNX_CLASS_INDEX_INVALID;
BNG::rxn_class_pathway_index_t pathway_index;
double current_time = elapsed_molecule_time + t_steps * collision.time;
if (matching_rxn_classes.size() == 1) {
rxn_class_index = 0;
pathway_index = RxnUtils::test_intersect(matching_rxn_classes[0], r_rate_factor, current_time, world->rng);
} else {
pathway_index = RxnUtils::test_many_intersect(
matching_rxn_classes, r_rate_factor, current_time, rxn_class_index, world->rng);
}
if (rxn_class_index != BNG::RNX_CLASS_INDEX_INVALID && pathway_index >= BNG::PATHWAY_INDEX_LEAST_VALID) {
BNG::RxnClass* rxn_class = matching_rxn_classes[rxn_class_index];
assert(collision.type == CollisionType::WALL_FRONT || collision.type == CollisionType::WALL_BACK);
int j = outcome_intersect(
p, rxn_class, pathway_index, collision, current_time);
if (j == RX_FLIP) {
return WallRxnResult::TRANSPARENT;
}
else if (j == RX_A_OK) {
return WallRxnResult::REFLECT;
}
else if (j == RX_DESTROY) {
return WallRxnResult::DESTROYED;
}
else {
assert(false);
return WallRxnResult::INVALID;
}
}
return WallRxnResult::REFLECT;
}
// ---------------------------------- surface diffusion ----------------------------------
inline void DiffuseReactEvent::diffuse_surf_molecule(
Partition& p,
Molecule& sm,
double& max_time,
const double diffusion_start_time
) {
const molecule_id_t sm_id = sm.id;
const BNG::Species& species = p.get_species(sm.species_id);
double steps = 0.0;
double t_steps = 0.0;
wall_index_t original_wall_index = sm.s.wall_index;
/* Where are we going? */
if (species.get_time_step() > max_time) {
t_steps = max_time;
}
else {
t_steps = species.get_time_step();
}
bool diffusible = species.can_diffuse();
if (diffusible) {
if (species.get_time_step() > max_time) {
steps = max_time / species.get_time_step() ;
if (steps < EPS) {
t_steps = EPS * species.get_time_step();
steps = EPS;
}
}
else {
steps = 1.0;
}
double space_factor = 0.0;
if (steps == 1.0) {
space_factor = species.get_space_step();
}
else {
space_factor = species.get_space_step() * sqrt_f(steps);
}
#ifdef DEBUG_TIMING
DUMP_CONDITION4(
sm_id,
dump_surf_mol_timing(
"- Timing sm", p.stats.get_current_iteration(), sm_id,
diffusion_start_time, max_time, sm.unimol_rxn_time,
space_factor, steps, t_steps
);
);
#endif
for (int find_new_position = (SURFACE_DIFFUSION_RETRIES + 1);
find_new_position > 0; find_new_position--) {
Vec2 displacement;
DiffusionUtils::compute_surf_displacement(species, space_factor, world->rng, displacement);
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION4(
sm_id,
if (species.can_diffuse()) {
displacement.dump(" displacement:", "");
}
);
#endif
assert(!species.has_flag(SPECIES_FLAG_SET_MAX_STEP_LENGTH) && "not supported yet");
// ray_trace does the movement and all other stuff
Vec2 new_loc;
BNG::RxnClass* absorb_now_rxn_class;
wall_index_t new_wall_index =
ray_trace_surf(p, species, sm_id, displacement, new_loc, absorb_now_rxn_class);
// Either something ambiguous happened or we hit absorptive border
if (new_wall_index == WALL_INDEX_INVALID) {
if (absorb_now_rxn_class != nullptr) {
absorb_now_rxn_class->init_rxn_pathways_and_rates();
assert(absorb_now_rxn_class->get_num_pathways() == 1);
bool kept = outcome_unimolecular(
p, p.get_m(sm_id), diffusion_start_time, absorb_now_rxn_class, 0, nullptr);
assert(!kept);
return;
}
continue; /* Something went wrong--try again */
}
assert(absorb_now_rxn_class == nullptr);
// After diffusing, are we still on the SAME triangle?
if (new_wall_index == sm.s.wall_index) {
if (!DiffusionUtils::move_sm_on_same_triangle(p, sm, new_loc)) {
// we must try a different position
continue;
}
}
// After diffusing, we ended up on a NEW triangle.
else {
if (!DiffusionUtils::move_sm_to_new_triangle(p, sm, new_loc, new_wall_index)) {
// we must try a different position
continue;
}
// Check if we shouldn't reschedule the unimol rxn defined by
// a surf mol + surf class rxn
// Do this only if the current unimol rxn is not scheduled
// for this timestep (t_steps is set to end at the unimol rx time)
double time_until_unimol = sm.unimol_rxn_time - t_steps - sm.diffusion_time;
time_until_unimol = (time_until_unimol < 0) ? 0 : time_until_unimol;
// for MCell3 compatibility, we must reschedule even if the molecule can just diffuse,
// not only when it can react with walls
if ((species.has_flag(SPECIES_FLAG_CAN_SURFWALL) || species.can_diffuse()) &&
(sm.unimol_rxn_time == TIME_INVALID ||
// using this overly complex condition because of MCell3 compatibility
(time_until_unimol > EPS || time_until_unimol > EPS * (sm.diffusion_time + t_steps))
)
) {
sm.unimol_rxn_time = TIME_INVALID;
sm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
}
}
find_new_position = 0;
}
} // if (species.space_step != 0)
// TODO: what about molecules that cannot diffuse? they should not react,
// but in MCell3 they do
bool sm_still_exists = true;
assert(!species.has_flag(SPECIES_FLAG_CAN_SURFSURFSURF) && "Not supported");
bool can_surf_surf_react = species.has_flag(SPECIES_FLAG_CAN_SURFSURF);
if (can_surf_surf_react && !species.is_target_only()) {
assert(!species.has_flag(SPECIES_MOL_FLAG_TARGET_ONLY) && "Not sure what to do here");
// the time t_steps should tell when the reaction occurred and it is quite weird because
// it has nothing to do with the time spent diffusing
sm_still_exists = react_2D_all_neighbors(p, sm, t_steps, diffusion_start_time);
}
// NOTE: surf-surf reactions on the same wall have higher priority,
// this must be randomized once intermembrane rxns will be more used
if (sm_still_exists && species.has_flag(SPECIES_FLAG_CAN_INTERMEMBRANE_SURFSURF) && !species.is_target_only()) {
sm_still_exists = react_2D_intermembrane(p, sm, t_steps, diffusion_start_time);
}
if (sm_still_exists) {
// reactions in react_2D_all_neighbors could have invalidated the molecules array
Molecule& new_m_ref = p.get_m(sm_id);
// for some reason, mcell3 defines a new unimol time if the molecule has moved
bool changed_wall = new_m_ref.s.wall_index != original_wall_index;
// we don't have to remove the molecule from the schedule, we can just change its unimol_rx_time,
// this time is checked and against the scheduled time
// mcell3 compatibility: we might change the schedule only if it is not already scheduled for this time step
// NOTE: this condition looks a bit weird, some explanation would be useful
if ((diffusible || can_surf_surf_react) &&
((!diffusible || changed_wall) &&
new_m_ref.unimol_rxn_time >= event_time + time_up_to_next_barrier)) { // ?? is usage or barrier_time_from_event_time correct?
new_m_ref.unimol_rxn_time = TIME_INVALID;
new_m_ref.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
}
}
// update max_time - for how long the molecule diffused
max_time = t_steps;
// and log stats
p.stats.inc_diffusion_cummtime(steps);
}
// returns true if molecule survived
bool DiffuseReactEvent::react_2D_all_neighbors(
Partition& p,
Molecule& sm,
const double time, // same argument as t passed in mcell3 (come up with a better name)
const double diffusion_start_time // diffusion_start_time + elapsed_molecule_time should be the time when reaction occurred
) {
#ifdef DEBUG_TIMING
DUMP_CONDITION4(
sm.id,
dump_react_2D_all_neighbors_timing(
time, diffusion_start_time + elapsed_molecule_time
);
);
#endif
const Wall& wall = p.get_wall(sm.s.wall_index);
TileNeighborVector neighbors;
GridUtils::find_neighbor_tiles(p, &sm, wall, sm.s.grid_tile_index, false, true, neighbors);
if (neighbors.empty()) {
return true;
}
const BNG::Species& sm_species = p.get_species(sm.species_id);
// each item in array corresponds to one potential reaction
small_vector<double> correction_factors;
small_vector<molecule_id_t> reactant_molecule_ids;
RxnClassesVector matching_rxn_classes;
/* step through the neighbors */
for (const WallTileIndexPair& neighbor: neighbors) {
Wall& nwall = p.get_wall(neighbor.wall_index);
Grid& ngrid = nwall.grid;
// is there something on the tile?
// TODO_LATER: this filtering should be done already while looking for neighbors
molecule_id_t nid = ngrid.get_molecule_on_tile(neighbor.tile_index);
if (nid == MOLECULE_ID_INVALID) {
continue;
}
Molecule& nsm = p.get_m(nid);
const BNG::Species& nsm_species = p.get_species(nsm.species_id);
#ifdef DEBUG_RXNS
DUMP_CONDITION4(
sm.id,
// the subtraction of diffusion_time_step doesn't make much sense but is needed to make the dump the same as in mcell3
// need to check it further
nsm.dump(p, "", " checking in react_2D_all_neighbors: ", world->get_current_iteration(), 0.0);
);
#endif
/* check whether the neighbor molecule is behind
the restrictive region boundary */
if ((sm_species.has_flag(SPECIES_FLAG_CAN_REGION_BORDER) || nsm_species.has_flag(SPECIES_FLAG_CAN_REGION_BORDER)) &&
sm.s.wall_index != nsm.s.wall_index
) {
/* INSIDE-OUT check */
if (WallUtils::walls_belong_to_at_least_one_different_restricted_region(p, wall, sm, nwall, nsm)) {
continue;
}
/* OUTSIDE-IN check */
if (WallUtils::walls_belong_to_at_least_one_different_restricted_region(p, wall, nsm, nwall, sm)) {
continue;
}
}
// returns value >=1 if there can be a reaction
size_t orig_num_rxsn = matching_rxn_classes.size();
RxnUtils::trigger_bimolecular_orientation_from_mols(
p.bng_engine,
sm, nsm,
matching_rxn_classes
);
// extend arrays holding additional information
// FIXME: the same code is in collide_and_react_with_surf_mol
for (size_t i = orig_num_rxsn; i < matching_rxn_classes.size(); i++) {
const RxnClass* rxn = matching_rxn_classes[i];
assert(rxn != nullptr);
correction_factors.push_back(time / ngrid.binding_factor);
reactant_molecule_ids.push_back(nsm.id);
}
}
size_t num_matching_rxn_classes = matching_rxn_classes.size();
if (num_matching_rxn_classes == 0) {
return true;
}
BNG::rxn_class_pathway_index_t selected_pathway_index;
Collision collision;
double collision_time = diffusion_start_time;
/* Calculate local_prob_factor for the reaction probability.
Here we convert from 3 neighbor tiles (upper probability
limit) to the real "num_nbrs" neighbor tiles. */
double local_prob_factor = 3.0 / neighbors.size();
int rxn_class_index;
if (num_matching_rxn_classes == 1) {
// figure out what should happen
selected_pathway_index = RxnUtils::test_bimolecular(
p, matching_rxn_classes[0], world->rng,
sm, p.get_m(reactant_molecule_ids[0]),
correction_factors[0], local_prob_factor, collision_time);
// there is just one possible class == one pair of reactants
rxn_class_index = 0;
}
else {
bool all_neighbors_flag = true;
rxn_class_index =
RxnUtils::test_many_bimolecular(
p, matching_rxn_classes, correction_factors, local_prob_factor,
world->rng, all_neighbors_flag, collision_time, selected_pathway_index);
selected_pathway_index = 0; // TODO_PATHWAYS: use value from test_many_bimolecular
}
if (rxn_class_index == BNG::PATHWAY_INDEX_NO_RXN || selected_pathway_index < BNG::PATHWAY_INDEX_LEAST_VALID) {
return true; /* No reaction */
}
collision = Collision(
CollisionType::SURFMOL_SURFMOL,
&p, sm.id, collision_time,
reactant_molecule_ids[rxn_class_index],
matching_rxn_classes[rxn_class_index]
);
/* run the reaction */
int outcome_bimol_result = outcome_bimolecular(
p, collision, selected_pathway_index, collision_time
);
return outcome_bimol_result != RX_DESTROY;
}
bool DiffuseReactEvent::react_2D_intermembrane(
Partition& p, Molecule& sm,
const double t_steps, const double diffusion_start_time
) {
const Wall& w1 = p.get_wall(sm.s.wall_index);
const Vec3& w1_vert0 = p.get_wall_vertex(w1, 0);
// get 3d position
Vec3 reac1_pos3d = GeometryUtils::uv2xyz(sm.s.pos, w1, w1_vert0);
// which subpart are we in?
// we check walls whose part is in the current subpartition, not the neighbors
IVec3 subpart_indices;
p.get_subpart_3d_indices(reac1_pos3d, subpart_indices);
subpart_index_t subpart_index = p.get_subpart_index_from_3d_indices(subpart_indices);
// with what species we may react? (this should be cached)
const BNG::SpeciesRxnClassesMap* rxns_classes_map =
p.get_all_rxns().get_bimol_rxns_for_reactant(sm.species_id);
if (rxns_classes_map == nullptr || rxns_classes_map->empty()) {
assert(false && "No rxns");
return true;
}
uint_set<species_id_t> reacting_species;
for (const auto& second_reactant_info: *rxns_classes_map) {
const BNG::RxnClass* rxn_class = second_reactant_info.second;
if (!rxn_class->is_intermembrane_surf_surf_rxn_class()) {
continue;
}
species_id_t second_species_id = second_reactant_info.first;
reacting_species.insert(second_species_id);
}
pos_t rxn_radius2 = p.config.intermembrane_rxn_radius_3d * p.config.intermembrane_rxn_radius_3d;
typedef pair<molecule_id_t, pos_t> IdDist2Pair;
small_vector<IdDist2Pair> reactants_dist2;
// get neighboring subparts - this is necessary because
// subpartitioning can put a boundary right between membranes
SubpartIndicesSet subpart_indices_set;
CollisionUtils::collect_neighboring_subparts(
p, reac1_pos3d, subpart_indices, p.config.intermembrane_rxn_radius_3d, p.config.subpart_edge_length,
subpart_indices_set
);
// and include current subpart
subpart_indices_set.insert(subpart_index);
// collect walls (this can be also somehow pre-computed)
uint_set<wall_index_t> wall_indices;
for (subpart_index_t si: subpart_indices_set) {
// for each wall in this subpart that belongs to a different object
const WallsInSubpart& subpart_wall_indices = p.get_subpart_wall_indices(subpart_index);
wall_indices.insert(subpart_wall_indices.begin(), subpart_wall_indices.end());
}
for (wall_index_t wi: wall_indices) {
const Wall& w2 = p.get_wall(wi);
if (w2.object_id == w1.object_id) {
continue;
}
const Grid& g = w2.grid;
if (!g.is_initialized() || g.get_num_occupied_tiles() == 0) {
continue;
}
const Vec3& w2_vert0 = p.get_wall_vertex(w2, 0);
// not really efficient, goes through all tiles
small_vector<molecule_id_t> molecule_ids;
g.get_contained_molecules(molecule_ids);
assert(molecule_ids.size() == g.get_num_occupied_tiles());
for (molecule_id_t reac2_id: molecule_ids) {
const Molecule& reac2 = p.get_m(reac2_id);
assert(reac2.is_surf());
if (reacting_species.count(reac2.species_id) == 0) {
continue;
}
// compute distance
Vec3 reac2_pos3d = GeometryUtils::uv2xyz(reac2.s.pos, w2, w2_vert0);
pos_t dist2 = len3_squared(reac1_pos3d - reac2_pos3d);
if (dist2 > rxn_radius2) {
continue;
}
reactants_dist2.push_back(make_pair(reac2_id, dist2));
}
}
if (reactants_dist2.empty()) {
return true;
}
// sort potential reactants by distance
sort(reactants_dist2.begin(), reactants_dist2.end(),
[ ]( const IdDist2Pair& lhs, const IdDist2Pair& rhs ) {
return lhs.second < rhs.second;
}
);
// and similarly as in diffuse_volume_molecule, evaluate each potential collision
// collision_time is the same as for surf mols,
// TODO: not sure if correct, this molecule has already diffused and newly created
// molecules birthdays will be this one
double collision_time = diffusion_start_time;
bool was_defunct = false;
for (const IdDist2Pair& id_dist2_pair: reactants_dist2) {
Molecule& sm2 = p.get_m(id_dist2_pair.first);
// get what reaction should happen, the default orientation of molecules is UP and
// also the rxn rule's pattern expects UP
RxnClassesVector matching_rxn_classes;
RxnUtils::trigger_bimolecular(
p.bng_engine, sm, sm2, sm.s.orientation, sm2.s.orientation, matching_rxn_classes);
if (matching_rxn_classes.empty()) {
assert(false && "We already filtered-out molecules that can react");
continue;
}
int selected_pathway_index = RX_NO_RX;
int rxn_class_index;
if (matching_rxn_classes.size() == 1) {
selected_pathway_index = RxnUtils::test_bimolecular(
p, matching_rxn_classes[0], world->rng,
sm, sm2,
// TODO: not sure what to put as scaling coeff
1,
0, // local prob factor
collision_time);
// there is just one possible class == one pair of reactants
rxn_class_index = 0;
}
else {
release_assert(false && "Multiple rxn classes for intermembrane rxns are not supported yet");
}
if (selected_pathway_index < RX_LEAST_VALID_PATHWAY) {
continue; // No reaction
}
Collision collision = Collision(
CollisionType::INTERMEMBRANE_SURFMOL_SURFMOL,
&p, sm.id, collision_time,
sm2.id,
matching_rxn_classes[rxn_class_index]
);
/* run the reaction */
int outcome_bimol_result = outcome_bimolecular(
p, collision, selected_pathway_index, collision_time
);
}
return !was_defunct;
}
/*************************************************************************
ray_trace_2D:
In: world: simulation state
sm: molecule that is moving
disp: displacement vector from current to new location
pos: place to store new coordinate (in coord system of new wall)
kill_me: flag that tells that molecule hits ABSORPTIVE region border
(value = 1)
rxp: reaction object (valid only in case of hitting ABSORPTIVE region
border)
hit_data_info: region border hit data information
Out: Return wall at endpoint of movement vector. Otherwise NULL if we hit
ambiguous location or if SM was absorbed.
pos: location of that endpoint in the coordinate system of the new wall.
kill_me, rxp, and hit_data_info will all be updated if we hit absorptive
boundary.
*************************************************************************/
wall_index_t DiffuseReactEvent::ray_trace_surf(
Partition& p,
const BNG::Species& species,
const molecule_id_t sm_id,
Vec2& remaining_displacement,
Vec2& new_pos,
BNG::RxnClass*& absorb_now_rxn_class // set to non-null is molecule has to be absorbed
) {
absorb_now_rxn_class = nullptr;
Molecule& sm = p.get_m(sm_id);
const Wall* this_wall = &p.get_wall(sm.s.wall_index);
Vec2 orig_pos = sm.s.pos;
Vec2 this_pos = sm.s.pos;
Vec2 this_disp = remaining_displacement;
/* Will break out with return or break when we're done traversing walls */
while (1) {
int this_wall_edge_region_border = 0;
//bool absorb_now = 0;
/* Index of the wall edge that the SM hits */
Vec2 boundary_pos;
edge_index_t edge_index_that_was_hit =
GeometryUtils::find_edge_point(*this_wall, this_pos, this_disp, boundary_pos);
// Ambiguous edge collision. Give up and try again from diffuse_2D.
if (edge_index_that_was_hit == EDGE_INDEX_CANNOT_TELL) {
sm.s.pos = orig_pos;
return WALL_INDEX_INVALID;
}
// We didn't hit the edge. Stay inside this wall. We're done!
else if (edge_index_that_was_hit == EDGE_INDEX_WITHIN_WALL) {
new_pos = this_pos + this_disp;
sm.s.pos = orig_pos;
return this_wall->index;
}
// Neither ambiguous (EDGE_INDEX_CANNOT_TELL) nor inside wall (EDGE_INDEX_WITHIN_WALL),
// must have hit edge (0, 1, 2)
Vec2 old_pos = this_pos;
/* We hit the edge - check for the reflection/absorption from the
edges of the wall if they are region borders
Note - here we test for potential collisions with the region
border while moving INSIDE OUT */
bool reflect_now = false;
if (species.can_interact_with_border()) {
DiffusionUtils::reflect_absorb_inside_out(
p, sm, *this_wall, edge_index_that_was_hit,
reflect_now, absorb_now_rxn_class
);
if (absorb_now_rxn_class != nullptr) {
return WALL_INDEX_INVALID;
}
}
/* no reflection - keep going */
if (!reflect_now) {
wall_index_t target_wall_index =
GeometryUtils::traverse_surface(*this_wall, old_pos, edge_index_that_was_hit, this_pos);
if (target_wall_index != WALL_INDEX_INVALID) {
/* We hit the edge - check for the reflection/absorption from the
edges of the wall if they are region borders
Note - here we test for potential collisions with the region
border while moving OUTSIDE IN */
if (species.can_interact_with_border()) {
const Wall& target_wall = p.get_wall(target_wall_index);
DiffusionUtils::reflect_absorb_outside_in(
p, sm, target_wall, *this_wall,
reflect_now, absorb_now_rxn_class
);
if (absorb_now_rxn_class != nullptr) {
return WALL_INDEX_INVALID;
}
}
if (!reflect_now) {
this_disp = old_pos + this_disp;
#ifndef NDEBUG
Edge& e = const_cast<Edge&>(this_wall->edges[edge_index_that_was_hit]);
assert(e.is_initialized());
e.debug_check_values_are_uptodate(p);
#endif
Vec2 tmp_disp;
GeometryUtils::traverse_surface(*this_wall, this_disp, edge_index_that_was_hit, tmp_disp);
this_disp = tmp_disp - this_pos;
this_wall = &p.get_wall(target_wall_index);
continue;
}
}
}
/* If we reach this point, assume we reflect off the edge since there is no
* neighboring wall
*
* NOTE: this_pos has been corrupted by traverse_surface; use old_pos to find
* out whether the present wall edge is a region border
*/
Vec2 new_disp = this_disp - (boundary_pos - old_pos);
switch (edge_index_that_was_hit) {
case EDGE_INDEX_0:
new_disp.v *= -1.0;
break;
case EDGE_INDEX_1: {
pos_t f;
Vec2 reflector;
reflector.u = -this_wall->uv_vert2.v;
reflector.v = this_wall->uv_vert2.u - this_wall->uv_vert1_u;
f = 1.0 / sqrt_p( len2_squared(reflector) );
reflector *= f;
f = 2.0 * dot2(new_disp, reflector);
new_disp -= Vec2(f) * reflector;
break;
}
case EDGE_INDEX_2: {
pos_t f;
Vec2 reflector;
reflector.u = this_wall->uv_vert2.v;
reflector.v = -this_wall->uv_vert2.u;
f = 1.0 / sqrt_p( len2_squared(reflector) );
reflector *= f;
f = 2.0 * dot2(new_disp, reflector);
new_disp -= Vec2(f) * reflector;
break;
}
default:
UNHANDLED_CASE(edge_index_that_was_hit);
}
this_pos.u = boundary_pos.u;
this_pos.v = boundary_pos.v;
this_disp.u = new_disp.u;
this_disp.v = new_disp.v;
} // while
sm.s.pos = orig_pos;
}
// ---------------------------------- other ----------------------------------
void DiffuseReactEvent::pick_unimol_rxn_class_and_set_rxn_time(
Partition& p,
const double current_time,
Molecule& m
) {
assert(current_time >= 0);
BNG::RxnClassesVector rxn_classes;
RxnUtils::pick_unimol_rxn_classes(p, m, current_time, rxn_classes);
if (rxn_classes.empty()) {
m.unimol_rxn_time = TIME_INVALID;
return;
}
uint idx = 0;
if (rxn_classes.size() > 1) {
idx = RxnUtils::test_many_unimol(rxn_classes, world->rng);
}
// there is a check when computing the reaction rate to make sure that the time is reasonably higher than 0
double time_from_now = RxnUtils::compute_unimol_lifetime(p, world->rng, rxn_classes[idx], current_time, m);
double scheduled_time = current_time + time_from_now;
// we need to store the end time to the molecule because it is needed in diffusion to
// figure out whether we should do the whole time step
m.unimol_rxn_time = scheduled_time;
}
// based on mcell3's check_for_unimolecular_reaction
// might invalidate vm references
// returns true if molecule survived and should be diffused right away
bool DiffuseReactEvent::react_unimol_single_molecule(
Partition& p,
const molecule_id_t m_id
) {
// the unimolecular reaction class was already selected
Molecule& m = p.get_m(m_id);
if (m.is_defunct()) {
return false;
}
double scheduled_time = m.unimol_rxn_time;
assert(!m.has_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN));
assert(cmp_ge(scheduled_time, event_time, EPS) && cmp_le(scheduled_time, event_time + time_up_to_next_barrier, EPS));
if (m.has_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE)) {
// this time event does not mean to execute the unimol action, but instead to
// update the scheduled time for the updated reaction rate
m.clear_flag(MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE);
pick_unimol_rxn_class_and_set_rxn_time(p, scheduled_time, m);
return true;
}
else {
BNG::RxnClassesVector rxn_classes;
RxnUtils::pick_unimol_rxn_classes(p, m, scheduled_time, rxn_classes);
for (RxnClass* rxn_class: rxn_classes) {
rxn_class->update_rxn_rates_if_needed(scheduled_time);
}
if (rxn_classes.empty()) {
// there is no unimol rxn, this can happen for instance when
// a surface molecule moved out of a regions with a surface class,
// we must recompute the unimol lifetime
pick_unimol_rxn_class_and_set_rxn_time(p, scheduled_time, m);
return true;
}
uint idx = 0;
if (rxn_classes.size() > 1) {
idx = RxnUtils::test_many_unimol(rxn_classes, world->rng);
}
BNG::rxn_class_pathway_index_t pi = RxnUtils::which_unimolecular(m, rxn_classes[idx], world->rng);
if (rxn_classes[idx]->is_unimol()) {
// standard unimolecular rxn
return outcome_unimolecular(p, m, scheduled_time, rxn_classes[idx], pi);
}
else {
// surf mol + surf class rxn
release_assert(m.is_surf() && "Only for surf mol + surf class rxns");
const Wall& w = p.get_wall(m.s.wall_index);
const Vec3& v0 = p.get_wall_vertex(w, 0);
// orientation front or back is not important
Vec3 pos = GeometryUtils::uv2xyz(m.s.pos, w, v0);
Collision collision(CollisionType::WALL_FRONT, &p, m.id, scheduled_time, pos, w.index);
return outcome_intersect(p, rxn_classes[idx], pi, collision, scheduled_time);
}
}
}
// checks if reaction should probabilistically occur and if so,
// destroys reactants
// returns RX_DESTROY when the primary reactant was destroyed, RX_A_OK if the reactant A was kept
// TODO: change return type for enum
int DiffuseReactEvent::outcome_bimolecular(
Partition& p,
const Collision& collision,
const int path,
const double time
) {
#ifdef DEBUG_TIMING
DUMP_CONDITION4(
collision.diffused_molecule_id,
dump_outcome_bimolecular_timing(time);
);
#endif
// might invalidate references
bool keep_reacA, keep_reacB;
int result =
outcome_products_random(
p,
collision,
time,
path,
keep_reacA, keep_reacB
);
p.stats.inc_rxn_occurred(p.get_all_rxns(), collision.rxn_class);
if (result == RX_A_OK || result == RX_FLIP) {
Molecule& reacA = p.get_m(collision.diffused_molecule_id);
Molecule& reacB = p.get_m(collision.colliding_molecule_id);
#ifdef DEBUG_RXNS
// reference printout first destroys B then A
DUMP_CONDITION4(
collision.diffused_molecule_id,
if (!keep_reacB) {
reacB.dump(p, "", " defunct m:", world->get_current_iteration(), 0, false);
}
if (!keep_reacA) {
reacA.dump(p, "", " defunct m:", world->get_current_iteration(), 0, false);
}
);
#endif
// always for now
// we used the reactants - remove them
if (!keep_reacA) {
p.set_molecule_as_defunct(reacA);
}
if (!keep_reacB) {
p.set_molecule_as_defunct(reacB);
}
if (keep_reacA) {
return result;
}
else {
return RX_DESTROY;
}
}
return result;
}
/*************************************************************************
outcome_intersect:
In: world: simulation state
rx: reaction that's taking place
path: path the reaction's taking
surface: wall that is being struck
reac: molecule that is hitting the wall
orient: orientation of the molecule
t: time that the reaction is occurring
hitpt: location of collision with wall
loc_okay:
Out: Value depending on outcome:
RX_A_OK if the molecule reflects
RX_FLIP if the molecule passes through
RX_DESTROY if the molecule stops, is destroyed, etc.
Additionally, products are created as needed.
Note: Can assume molecule is always first in the reaction.
*************************************************************************/
int DiffuseReactEvent::outcome_intersect(
Partition& p,
RxnClass* rxn_class,
const BNG::rxn_class_pathway_index_t pathway_index,
Collision& collision, // rxn_class can be set
const double time
) {
if (!rxn_class->is_standard()) {
// no need to count these reactions in p.stats
if (rxn_class->is_reflect_type()) {
return RX_A_OK; /* just reflect */
}
else {
assert(rxn_class->is_transparent_type()); // already dealt with before for better performance, but let's keep this general
return RX_FLIP; /* Flip = transparent is default special case */
}
}
/* If reaction object has ALL_MOLECULES or ALL_VOLUME_MOLECULES as the
* first reactant it means that reaction is of the type ABSORPTIVE =
* ALL_MOLECULES or ABSORPTIVE = ALL_VOLUME_MOLECULES since other cases
* (REFLECTIVE/TRANSPARENT) are taken care above. But there are no products
* for this reaction, so we do no need to go into "outcome_products()"
* function. */
assert(rxn_class->is_bimol());
species_id_t all_molecules_id = p.get_all_species().get_all_molecules_species_id();
species_id_t all_volume_molecules_id = p.get_all_species().get_all_volume_molecules_species_id();
int result;
bool keep_reacA = true, keep_reacB = true;
// expecting that the surface is always the second reactant
assert(p.get_species(rxn_class->reactant_ids[1]).is_reactive_surface());
if (rxn_class->reactant_ids[0] == all_molecules_id ||
rxn_class->reactant_ids[0] == all_volume_molecules_id) {
assert(rxn_class->get_num_reactions() == 1);
keep_reacA = false;
result = RX_DESTROY;
}
else {
// might return RX_BLOCKED
collision.rxn_class = rxn_class;
result = outcome_products_random(p, collision, time, pathway_index, keep_reacA, keep_reacB);
assert(keep_reacB && "We are keeping the surface");
}
p.stats.inc_rxn_occurred(p.get_all_rxns(), rxn_class);
if (result == RX_BLOCKED) {
return RX_A_OK; /* reflect the molecule */
}
if (!keep_reacA) {
#ifdef DEBUG_RXNS
const Molecule& reacA = p.get_m(collision.diffused_molecule_id);
DUMP_CONDITION4(
collision.diffused_molecule_id,
if (!keep_reacA) {
reacA.dump(p, "", " defunct m:", world->get_current_iteration(), 0, false);
}
);
#endif
Molecule& m = p.get_m(collision.diffused_molecule_id);
p.set_molecule_as_defunct(m);
return RX_DESTROY;
}
else {
return result; /* RX_A_OK or RX_FLIP */
}
}
// might return RX_BLOCKED if reaction cannot occur,
// returns 0 if positions were found
int DiffuseReactEvent::find_surf_product_positions(
Partition& p,
const Collision& collision,
const BNG::RxnRule* rxn,
const Molecule* reacA, const bool keep_reacA,
const Molecule* reacB, const bool keep_reacB,
const Molecule* surf_reac,
const RxnProductsVector& actual_products,
GridPosVector& assigned_surf_product_positions,
uint& num_surface_products,
bool& surf_pos_reacA_is_used
) {
assigned_surf_product_positions.clear();
surf_pos_reacA_is_used = keep_reacA;
uint needed_surface_positions = 0;
for (const ProductSpeciesIdWIndices& prod: actual_products) {
if (p.get_species(prod.product_species_id).is_surf()) {
needed_surface_positions++;
}
}
num_surface_products = needed_surface_positions;
assert(reacA != nullptr);
uint num_reactants = (reacB == nullptr) ? 1 : 2;
small_vector<GridPos> recycled_surf_prod_positions; // this array contains information on where to place the surface products
uint initiator_recycled_index = INDEX_INVALID;
/* list of the restricted regions for the reactants by wall */
RegionIndicesSet rlp_wall_1, rlp_wall_2;
/* list of the restricted regions for the reactants by object */
RegionIndicesSet rlp_obj_1, rlp_obj_2;
int sm_bitmask = RegionUtils::determine_molecule_region_topology(
p, reacA, reacB, rxn->is_unimol(),
rlp_wall_1, rlp_wall_2, rlp_obj_1, rlp_obj_2);
// find which tiles can be recycled
if (reacA->is_surf()) {
if (!keep_reacA) {
recycled_surf_prod_positions.push_back( GridPos::make_with_mol_pos(*reacA) );
if (reacA->id == surf_reac->id) {
initiator_recycled_index = 0;
}
}
else if (keep_reacA) {
// reacA is kept
needed_surface_positions--;
}
}
if (reacB != nullptr && reacB->is_surf()) {
if (!keep_reacB) {
recycled_surf_prod_positions.push_back( GridPos::make_with_mol_pos(*reacB) );
if (reacB->id == surf_reac->id) {
initiator_recycled_index = recycled_surf_prod_positions.size() - 1;
}
}
else if (reacB->is_surf() && keep_reacB) {
// reacB is kept
needed_surface_positions--;
}
}
if (needed_surface_positions == 0) {
return 0;
}
assigned_surf_product_positions.resize(actual_products.size());
// do we need more tiles?
TileNeighborVector vacant_neighbor_tiles;
// these locations are set only for rxns with surface classes
Vec2 hit_wall_pos2d;
tile_index_t hit_wall_tile_index = UINT_INVALID;
if (needed_surface_positions > recycled_surf_prod_positions.size()) {
// find neighbors for the first surface reactant or the point where we hit the wall
TileNeighborVector neighbor_tiles;
if (surf_reac != nullptr) {
// rxn with surface molecule
Wall& wall = p.get_wall(surf_reac->s.wall_index);
GridUtils::find_neighbor_tiles(p, surf_reac, wall, surf_reac->s.grid_tile_index, true, false, neighbor_tiles);
}
else {
// rxn with surface class
assert(collision.is_wall_collision());
Wall& wall = p.get_wall(collision.colliding_wall_index);
if (!wall.grid.is_initialized()) {
wall.grid.initialize(p, wall);
}
hit_wall_pos2d = GeometryUtils::xyz2uv(p, collision.pos, wall);
hit_wall_tile_index = GridUtils::uv2grid_tile_index(hit_wall_pos2d, wall);
GridUtils::find_neighbor_tiles(p, nullptr, wall, hit_wall_tile_index, true, false, neighbor_tiles);
}
// we care only about the vacant ones (NOTE: this filtering out might be done in find_neighbor_tiles)
// mcell3 reverses the ordering here
for (int i = neighbor_tiles.size() - 1; i >=0; i--) {
WallTileIndexPair& tile_info = neighbor_tiles[i];
Grid& neighbor_grid = p.get_wall(tile_info.wall_index).grid;
if (neighbor_grid.get_molecule_on_tile(tile_info.tile_index) == MOLECULE_ID_INVALID) {
vacant_neighbor_tiles.push_back(tile_info);
}
}
/* Can this reaction happen at all? */
if (vacant_neighbor_tiles.size() + recycled_surf_prod_positions.size() < needed_surface_positions) {
return RX_BLOCKED;
}
}
// assignment of positions
uint num_tiles_to_recycle = min(actual_products.size(), recycled_surf_prod_positions.size());
if (rxn->is_intermembrane_surf_rxn()) {
// special case limited to A@C1 + B@C2 -> C@C1 + D@C2
release_assert(needed_surface_positions == 2 && num_tiles_to_recycle == 2);
release_assert(rxn->products.size() == 2);
BNG::compartment_id_t compartment_prod0 = rxn->products[0].get_primary_compartment_id();
BNG::compartment_id_t compartment_reacA = p.get_species(reacA->species_id).get_primary_compartment_id();
// use compartment to determine location (
if (compartment_reacA == compartment_prod0) {
// in the same order
assigned_surf_product_positions[0] = recycled_surf_prod_positions[0];
assigned_surf_product_positions[0].set_reac_type(GridPosType::REACA_UV);
assigned_surf_product_positions[1] = recycled_surf_prod_positions[1];
assigned_surf_product_positions[1].set_reac_type(GridPosType::REACB_UV);
}
else {
#ifndef NDEBUG
BNG::compartment_id_t compartment_prod1 = rxn->products[1].get_primary_compartment_id();
assert(compartment_reacA == compartment_prod1);
#endif
// switched order
assigned_surf_product_positions[0] = recycled_surf_prod_positions[1];
assigned_surf_product_positions[0].set_reac_type(GridPosType::REACB_UV);
assigned_surf_product_positions[1] = recycled_surf_prod_positions[0];
assigned_surf_product_positions[1].set_reac_type(GridPosType::REACA_UV);
}
}
else if (needed_surface_positions == 1 && num_tiles_to_recycle == 1 && recycled_surf_prod_positions.size() >= 1) {
if (initiator_recycled_index == INDEX_INVALID) {
assert(recycled_surf_prod_positions.size() == 1);
assigned_surf_product_positions[0] = recycled_surf_prod_positions[0];
}
else {
assigned_surf_product_positions[0] = recycled_surf_prod_positions[initiator_recycled_index];
}
assigned_surf_product_positions[0].set_reac_type(GridPosType::REACA_UV);
surf_pos_reacA_is_used = true;
}
else {
uint next_available_index = 0;
uint num_players = actual_products.size() + num_reactants;
// assign recycled positions to products
while (next_available_index < num_tiles_to_recycle) {
// we must have the same number of random calls as in mcell3...
uint rnd_num = rng_uint(&world->rng) % num_players;
// continue until we got an index of a product
if (rnd_num < num_reactants) {
continue;
}
uint product_index = rnd_num - num_reactants;
assert(product_index < actual_products.size());
// we care only about surface molecules
if (p.get_species(actual_products[product_index].product_species_id).is_vol()) {
continue;
}
// skip products that we already set
if (assigned_surf_product_positions[product_index].is_assigned()) {
continue;
}
// set position for product with product_index
assigned_surf_product_positions[product_index] = recycled_surf_prod_positions[next_available_index];
if (assigned_surf_product_positions[product_index].has_same_wall_and_grid(*reacA)) {
assigned_surf_product_positions[product_index].set_reac_type(GridPosType::REACA_UV);
surf_pos_reacA_is_used = true;
}
else if (assigned_surf_product_positions[product_index].has_same_wall_and_grid(*reacB)) {
assigned_surf_product_positions[product_index].set_reac_type(GridPosType::REACB_UV);
}
else {
assert(false);
}
next_available_index++;
}
small_vector<bool> used_vacant_tiles;
used_vacant_tiles.resize(vacant_neighbor_tiles.size(), false);
// assign the first surface product of vol+wall rxn to the position where we hit the wall
// MCell3 calls RNG and also allows to have multiple molecules to be placed on the same location,
// MCell4 allows only a single location
if (rxn->is_reactive_surface_rxn()) {
// get the first unassigned surface product
uint unassigned_product_index;
bool found_product_index = false;
for (unassigned_product_index = 0; unassigned_product_index < actual_products.size(); unassigned_product_index++) {
if (rxn->products[unassigned_product_index].is_surf() &&
!assigned_surf_product_positions[unassigned_product_index].is_assigned()) {
found_product_index = true;
break;
}
}
release_assert(found_product_index);
WallTileIndexPair wall_tile_indices = WallTileIndexPair(collision.colliding_wall_index, hit_wall_tile_index);
#ifndef NDEBUG
// hit location must not be in vacant_neighbor_tiles
uint vacant_tile_index;
bool found_vacant_tile = false;
for (vacant_tile_index = 0; vacant_tile_index < vacant_neighbor_tiles.size(); vacant_tile_index++) {
if (vacant_neighbor_tiles[vacant_tile_index] == wall_tile_indices) {
found_vacant_tile = true;
break;
}
}
assert(!found_vacant_tile);
#endif
// call rng to have the same output as MCell3
rng_uint(&world->rng);
// assign position if the location is available
const Wall& w = p.get_wall(wall_tile_indices.wall_index);
if (w.grid.get_molecule_on_tile(hit_wall_tile_index) == MOLECULE_ID_INVALID) {
// position was previously computed from wall and tile index
assigned_surf_product_positions[unassigned_product_index] =
GridPos::make_with_pos(hit_wall_pos2d, wall_tile_indices);
assigned_surf_product_positions[unassigned_product_index].set_reac_type(GridPosType::POS_UV);
}
}
// all other products are placed on one of the randomly chosen vacant tiles
uint num_vacant_tiles = vacant_neighbor_tiles.size();
for (uint product_index = 0; product_index < actual_products.size(); product_index++) {
if (assigned_surf_product_positions[product_index].is_assigned()) {
continue;
}
uint num_attempts = 0;
bool found = false;
while (!found && num_attempts < SURFACE_DIFFUSION_RETRIES) {
assert(num_vacant_tiles != 0);
uint rnd_num = rng_uint(&world->rng) % num_vacant_tiles;
// is this vacant tile already used?
if (used_vacant_tiles[rnd_num]) {
num_attempts++;
continue;
}
WallTileIndexPair grid_tile_index_pair = vacant_neighbor_tiles[rnd_num];
// make sure we can get to the tile given the surface regions defined in the model
if (!RegionUtils::product_tile_can_be_reached(p, grid_tile_index_pair.wall_index,
rxn->is_unimol(), sm_bitmask, rlp_wall_1, rlp_wall_2, rlp_obj_1, rlp_obj_2)) {
// we do not want to be checking this tile anymore
used_vacant_tiles[rnd_num] = true;
num_attempts++;
continue;
}
assigned_surf_product_positions[product_index] = GridPos::make_without_pos(grid_tile_index_pair);
assigned_surf_product_positions[product_index].set_reac_type(GridPosType::RANDOM);
used_vacant_tiles[rnd_num] = true;
found = true;
}
if (num_attempts >= SURFACE_DIFFUSION_RETRIES) {
return RX_BLOCKED;
}
}
}
return 0;
}
static void update_vol_mol_after_rxn_with_surf_mol(
Partition& p,
const Wall& wall,
const orientation_t product_orientation,
const Collision& collision,
Molecule& vm
) {
#ifndef MCELL4_VOL_PROD_BUMP_FROM_SURFACE_ONLY_ONE_EPS
// larger 'bump' is needed to really avoid a molecule going through the wall
// on which it was created
const int mult = 16;
#else
// value used in MCell3, although results seemed correct, MCell3 does not
// detect an escaped molecule so it is possible that the same
// issue was present there as well
const int mult = 1;
#endif
pos_t bump = (product_orientation > 0) ? mult*POS_EPS : -mult*POS_EPS;
Vec3 displacement = Vec3(2 * bump) * wall.normal;
Vec3 new_pos_after_diffuse;
DiffusionUtils::tiny_diffuse_3D(p, vm, displacement, wall.index, new_pos_after_diffuse);
// update position and subpart if needed
vm.v.pos = new_pos_after_diffuse;
vm.v.subpart_index = p.get_subpart_index(vm.v.pos);
p.update_molecule_reactants_map(vm);
}
void DiffuseReactEvent::handle_rxn_callback(
Partition& p,
const Collision& collision,
const double time,
const BNG::RxnRule* rxn,
// reac1 is the diffused molecule and reac2 is the optional second reactant
const Molecule* reacA,
const Molecule* reacB,
const MoleculeIdsVector& product_ids,
bool& cancel_reaction
) {
cancel_reaction = false;
// check callback
if (world->get_callbacks().needs_rxn_callback(rxn->id)) {
shared_ptr<API::ReactionInfo> info = make_shared<API::ReactionInfo>();
const Molecule* reac1;
const Molecule* reac2;
// first reactant id that we are sending back must be always the diffusing molecule
if (reacA->id == collision.diffused_molecule_id) {
reac1 = reacA;
reac2 = reacB;
}
else {
assert(reacB != nullptr);
reac1 = reacB;
reac2 = reacA;
}
assert(reac2 == nullptr || reac2->id == collision.colliding_molecule_id);
// determine type
if (reac2 == nullptr) {
info->type = reac1->is_vol() ?
API::ReactionType::UNIMOL_VOLUME :
API::ReactionType::UNIMOL_SURFACE;
}
else {
if (reac1->is_vol()) {
info->type = reac2->is_vol() ?
API::ReactionType::VOLUME_VOLUME :
API::ReactionType::VOLUME_SURFACE;
}
else {
// surface-volume ordering or reactants is not allowed
assert(reac2->is_surf());
info->type = API::ReactionType::SURFACE_SURFACE;
}
}
info->reactant_ids.push_back(reac1->id);
if (reac2 != nullptr) {
info->reactant_ids.push_back(reac2->id);
}
info->product_ids.insert(info->product_ids.begin(), product_ids.begin(), product_ids.end());
info->time = time;
info->rxn_rule_id = rxn->id;
// pos3d
if (reac1->is_vol()) {
info->pos3d = collision.pos.to_vec();
}
else {
// collision.pos is not valid for unimol surf or surf-surf reactions
const Wall& w = p.get_wall(reac1->s.wall_index);
const Vec3& v0 = p.get_wall_vertex(w, 0);
info->pos3d = GeometryUtils::uv2xyz(reac1->s.pos, w, v0).to_vec();
}
if (rxn->is_surf_rxn()) {
const Molecule* first_surf_reac = reac1->is_surf() ? reac1 : reac2;
// use the first surface reactant for the first surface location
info->pos2d = first_surf_reac->s.pos.to_vec();
info->geometry_object_id = p.get_wall(first_surf_reac->s.wall_index).object_id;
info->partition_wall_index = first_surf_reac->s.wall_index;
}
else if (rxn->is_reactive_surface_rxn()) {
const Wall& w = p.get_wall(collision.colliding_wall_index);
info->pos2d = GeometryUtils::xyz2uv(p, collision.pos, w).to_vec();
info->geometry_object_id = w.object_id;
info->partition_wall_index = collision.colliding_wall_index;
}
cancel_reaction = world->get_callbacks().do_rxn_callback(info);
}
}
orientation_t DiffuseReactEvent::determine_orientation_depending_on_surf_comp(
const species_id_t prod_species_id, const Molecule* surf_reac) {
assert(surf_reac != nullptr);
// get compartment of the surface molecule
const Species& surf_species = world->get_all_species().get(surf_reac->species_id);
BNG::compartment_id_t surf_comp_id = surf_species.get_primary_compartment_id();
release_assert(surf_comp_id != BNG::COMPARTMENT_ID_NONE && "Invalid compartments used in rxn in form V(s!1).S(v!1) -> V(s) + S(v)");
const BNG::Compartment& surf_comp = world->bng_engine.get_data().get_compartment(surf_comp_id);
// get compartment of the product
const Species& prod_species = world->get_all_species().get(prod_species_id);
BNG::compartment_id_t prod_comp_id = prod_species.get_primary_compartment_id();
release_assert(prod_comp_id != BNG::COMPARTMENT_ID_NONE && "Invalid compartments used in rxn in form V(s!1).S(v!1) -> V(s) + S(v)");
// is the product's compartment a child or parent?
if (surf_comp.parent_compartment_id == prod_comp_id) {
return ORIENTATION_UP;
}
else if (surf_comp.children_compartments.count(prod_comp_id) != 0) {
return ORIENTATION_DOWN;
}
else {
release_assert(false && "Invalid compartments used in rxn in form V(s!1).S(v!1) -> V(s) + S(v)");
return ORIENTATION_NOT_SET;
}
}
// WARNING: might invalidate references
// might return RX_BLOCKED
// TODO: refactor, split into multiple functions
int DiffuseReactEvent::outcome_products_random(
Partition& p,
const Collision& collision,
const double time,
const BNG::rxn_class_pathway_index_t pathway_index,
bool& keep_reacA,
bool& keep_reacB,
MoleculeIdsVector* optional_product_ids
) {
assert(collision.is_mol_mol_reaction() ||
collision.is_unimol_reaction() ||
collision.is_wall_collision()
);
#ifdef DEBUG_RXNS
DUMP_CONDITION4(
collision.diffused_molecule_id,
collision.dump(p, "Processing reaction:", p.stats.get_current_iteration(), time);
cout << p.get_species(p.get_m(collision.diffused_molecule_id).species_id).name;
if (collision.is_mol_mol_reaction()) {
cout << " + " <<
p.get_species(p.get_m(collision.colliding_molecule_id).species_id).name;
}
cout << "\nreaction_index: " << pathway_index << "\n";
if (collision.rxn_class != nullptr) {
collision.rxn_class->dump();
}
else {
cout << "rxn_class is nullptr\n";
}
);
#endif
Molecule* reacA = &p.get_m(collision.diffused_molecule_id);
assert(reacA->is_vol() || reacA->is_surf());
keep_reacA = false; // one product is the same as reacA
assert(reacA != nullptr);
Molecule* reacB = nullptr;
keep_reacB = false; // one product is the same as reacB
RxnClass* rxn_class = collision.rxn_class;
assert(rxn_class != nullptr);
const RxnRule* rxn = rxn_class->get_rxn_for_pathway(pathway_index);
assert(rxn->reactants.size() == 1 || rxn->reactants.size() == 2);
if (collision.is_wall_collision()) {
keep_reacB = true;
#ifndef NDEBUG
// check that the second reactant is a reactive surface
assert(rxn->reactants[1].is_simple());
BNG::elem_mol_type_id_t mol_type_id = rxn->reactants[1].get_simple_species_mol_type_id();
const BNG::ElemMolType& mt = p.bng_engine.get_data().get_elem_mol_type(mol_type_id);
assert(mt.is_reactive_surface());
#endif
}
assert(rxn != nullptr);
#ifdef DEBUG_CPLX_MATCHING
cout << "Reaction to be executed:\n";
rxn->dump(false); cout << "\n";
rxn->dump(true); cout << "\n";
#endif
// count this reaction if needed
if (rxn->is_counted()) {
assert(rxn->id != BNG::RXN_RULE_ID_INVALID);
if (reacA->is_vol()) {
p.inc_rxn_in_volume_occured_count(rxn->id, reacA->v.counted_volume_index);
}
else if (reacA->is_surf()) {
p.inc_rxn_on_surface_occured_count(rxn->id, reacA->s.wall_index);
}
}
Molecule* surf_reac = nullptr;
bool reactants_swapped = false;
// the second reactant might be a surface
uint num_mol_reactants =
(collision.is_wall_collision() || rxn->is_absorptive_region_rxn()) ?
1 : rxn->reactants.size();
if (num_mol_reactants == 2) {
reacB = &p.get_m(collision.colliding_molecule_id);
if (reacA->is_surf()) {
surf_reac = reacA;
}
else if (reacB->is_surf()) {
surf_reac = reacB;
}
// Ensure that reacA and reacB are sorted in the same order as the rxn players.
// Needed to maintain the same behavior as in mcell3
// With BNG, a pattern can match both of the reactants so we must check both
// Rules are usually short so this should be rather cheap
// TODO: use some other cached information such as RxnRule.species_applicable_as_reactant?
// what about ALL_MOLECULES?
if (!p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->reactants[0], reacA->species_id) ||
!p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->reactants[1], reacB->species_id)
) {
Molecule* tmp_mol = reacA;
reacA = reacB;
reacB = tmp_mol;
reactants_swapped = true;
}
// both reactants must match
assert(p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->reactants[0], reacA->species_id));
assert(p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->reactants[1], reacB->species_id));
keep_reacB = rxn->is_simple_cplx_reactant_on_both_sides_of_rxn_w_identical_compartments(1);
}
else {
surf_reac = reacA->is_surf() ? reacA : nullptr;
}
assert(p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->reactants[0], reacA->species_id));
keep_reacA = rxn->is_simple_cplx_reactant_on_both_sides_of_rxn_w_identical_compartments(0);
bool is_orientable = reacA->is_surf() || (reacB != nullptr && reacB->is_surf()) || collision.is_wall_collision();
WallTileIndexPair surf_reac_wall_tile;
assert(
( surf_reac == nullptr ||
(surf_reac->s.wall_index == WALL_INDEX_INVALID && surf_reac->s.grid_tile_index == TILE_INDEX_INVALID) ||
(surf_reac->s.wall_index != WALL_INDEX_INVALID && surf_reac->s.grid_tile_index != TILE_INDEX_INVALID)) &&
"Either both wall and tile index must be valid or both must be invalid"
);
if (surf_reac != nullptr) {
// we need to remember this value now because surf_reac's grid tile is freed a bit later to make a place for
// new product
surf_reac_wall_tile.wall_index = surf_reac->s.wall_index;
surf_reac_wall_tile.tile_index = surf_reac->s.grid_tile_index;
}
const RxnProductsVector& actual_products = collision.rxn_class->get_rxn_products_for_pathway(pathway_index);
release_assert(actual_products.size() <= rxn->products.size()); // some rxn products may be still connected
/* If the reaction involves a surface, make sure there is room for each product. */
GridPosVector assigned_surf_product_positions; // this array contains information on where to place the surface products
uint num_surface_products;
bool surf_pos_reacA_is_used;
if (is_orientable) {
int res = find_surf_product_positions(
p, collision, rxn, reacA, keep_reacA, reacB, keep_reacB, surf_reac, actual_products,
assigned_surf_product_positions, num_surface_products, surf_pos_reacA_is_used);
if (res == RX_BLOCKED) {
return RX_BLOCKED;
}
}
// free up tiles that we are probably going to reuse
if (reacA->is_surf() && !keep_reacA) {
p.get_wall(reacA->s.wall_index).grid.reset_molecule_tile(reacA->s.grid_tile_index);
reacA->s.grid_tile_index = TILE_INDEX_INVALID;
}
if (reacB != nullptr && reacB->is_surf() && !keep_reacB) {
p.get_wall(reacB->s.wall_index).grid.reset_molecule_tile(reacB->s.grid_tile_index);
reacB->s.grid_tile_index = TILE_INDEX_INVALID;
}
// remember reactant IDs
molecule_id_t reacA_id = reacA->id;
molecule_id_t reacB_id = (reacB != nullptr) ? reacB->id : MOLECULE_ID_INVALID;
molecule_id_t surf_reac_id = (surf_reac != nullptr) ? surf_reac->id : MOLECULE_ID_INVALID;
// create and place each product
uint current_surf_product_position_index = 0;
int res = RX_A_OK;
// need to determine orientations before the products are created because mcell3 does this earlier as well
vector<orientation_t> product_orientations;
if (is_orientable) {
for (uint product_index = 0; product_index < rxn->products.size(); product_index++) {
const BNG::Cplx& product = rxn->products[product_index];
if (product.get_orientation() == ORIENTATION_NONE) {
product_orientations.push_back( (rng_uint(&world->rng) & 1) ? ORIENTATION_UP : ORIENTATION_DOWN);
}
else {
orientation_t orient = product.get_orientation();
// set orientation relative to the durface comparmtment?
if (orient == ORIENTATION_DEPENDS_ON_SURF_COMP) {
orient = determine_orientation_depending_on_surf_comp(actual_products[product_index].product_species_id, surf_reac);
}
// flip orientation? e.g. such as for MCell3 rxn v' + s, -> s, + r, with reactants v + s'
else if (rxn->is_bimol() && rxn->is_surf_rxn() && !rxn->is_reactive_surface_rxn()) {
// see if orientations of the surface reactants from rule are different from the reactants
int reacA_match = 1;
if (reacA->is_surf() && rxn->reactants[0].get_orientation() != ORIENTATION_NONE &&
reacA->s.orientation != rxn->reactants[0].get_orientation()) {
reacA_match = -1;
}
int reacB_match = 1;
assert(reacB != nullptr);
if (reacB->is_surf() && rxn->reactants[1].get_orientation() != ORIENTATION_NONE &&
reacB->s.orientation != rxn->reactants[1].get_orientation()) {
reacB_match = -1;
}
// flip orientation as needed
orient = orient * reacA_match * reacB_match;
}
product_orientations.push_back(orient);
}
}
}
else {
// no surface reactant, all products will have orientataion none
product_orientations.resize(rxn->products.size(), ORIENTATION_NONE);
}
MoleculeIdsVector product_ids;
for (uint product_index = 0; product_index < actual_products.size(); product_index++) {
const ProductSpeciesIdWIndices& actual_product = actual_products[product_index];
// first we must check whether we are mapping a single product onto multiple complexes from the right-had side of the rule
assert(!actual_product.rule_product_indices.empty());
bool actual_prod_is_single_rxn_prod = actual_product.rule_product_indices.size() == 1;
release_assert(!actual_prod_is_single_rxn_prod || *actual_product.rule_product_indices.begin() == product_index);
// valid only if actual_prod_is_single_rxn_prod
uint single_rxn_product_index = product_index;
orientation_t product_orientation = ORIENTATION_NOT_SET;
for (uint rule_product_index: actual_product.rule_product_indices) {
const BNG::Cplx& rule_product = rxn->products[rule_product_index];
release_assert(
(product_orientation == ORIENTATION_NOT_SET ||
product_orientation == product_orientations[rule_product_index]) &&
"If a single actual product corresponds to multiple rxn products (such as in case of bond breakage), "
"orientations of all rxn products must be the same"
);
product_orientation = product_orientations[rule_product_index];
}
release_assert(product_orientation != ORIENTATION_NOT_SET);
// do not create anything new when the reactant is kept -
// for bimol reactions - the diffusion simply continues
// for unimol reactions - the unimol action action starts diffusion for the remaining timestep
if (actual_prod_is_single_rxn_prod && rxn->is_simple_cplx_product_on_both_sides_of_rxn_w_identical_compartments(single_rxn_product_index)) {
uint reactant_index;
bool ok = rxn->get_assigned_cplx_reactant_for_product(single_rxn_product_index, true, reactant_index);
assert(reactant_index == 0 || reactant_index == 1);
Molecule* reactant = ((reactant_index == 0) ? reacA : reacB);
// we are keeping the molecule, only the orientation changes?
if (rxn->reactants[reactant_index].get_orientation() != product_orientation ||
(reactant->is_surf() && reactant->s.orientation != product_orientation)) {
// initiator volume molecule passes through wall or was flipped?
// any surf mol -> set new orient
// if not swapped, reacA is the diffused molecule and matches the reactant with index 0
// reacA matches reactant with index 0, reacB matches reactant with index 1
assert(reactant != nullptr);
assert(p.bng_engine.matches_pattern_incl_all_mols_ignore_orientation(rxn->products[single_rxn_product_index], reactant->species_id));
if (reactant->is_vol()) {
Molecule* initiator = (!reactants_swapped) ? reacA : reacB;
if (reactant == initiator) {
res = RX_FLIP;
}
}
else if (reactant->is_surf()) {
// surface mol - set new orientation
reactant->s.orientation = product_orientation;
}
else {
assert(false);
}
}
// reactant was kept
product_ids.push_back(reactant->id);
continue;
}
species_id_t product_species_id = actual_products[product_index].product_species_id;
const BNG::Species& species = p.get_species(product_species_id);
molecule_id_t new_m_id;
// set only for new vol mols when one of the reactants is surf, invalid by default
WallTileIndexPair where_is_vm_created;
if (species.is_vol()) {
// create and place a volume molecule
Vec3 pos;
if (!collision.has_pos()) {
// only surf-surf rxns don't have position
assert(reacA->is_surf());
const Wall& w_pos = p.get_wall(reacA->s.wall_index);
pos = GeometryUtils::uv2xyz(reacA->s.pos, w_pos, p.get_wall_vertex(w_pos, 0));
}
else {
// TODO: check outcome of case: vol + surf -> vol
// Nov 10, 2022. Fix placement of non-diffusible vol product.
// Determine if one of the vol reactants is non-diffusive
// figure out which vol reactant is non-diffusive
// For bimolecular rxns:
// the vol product is non-diffusive if one of the vol reactants
// is non-diffusive. We should place the product at the location
// of the "colliding_molecule" which should be non-diffusive
// in this case.
// For unimolecular rxns:
// reacB_id is invalid
// and collision.pos is the location of the unimolecular reactant
if (species.D == 0 && reacB_id != MOLECULE_ID_INVALID) {
// set position of product to position of non-diffusive reactant
pos = p.get_m(collision.colliding_molecule_id).v.pos;
}
else {
// both reactants are diffusive or rxn is unimolecular:
pos = collision.pos;
}
}
Molecule vm_initialization(MOLECULE_ID_INVALID, product_species_id, pos, time);
assert(is_orientable
|| (collision.type != CollisionType::VOLMOL_SURFMOL && collision.type != CollisionType::SURFMOL_SURFMOL)
);
Wall* wall = nullptr;
if (is_orientable) {
if (surf_reac != nullptr) {
wall = &p.get_wall(surf_reac->s.wall_index);
// position is used to schedule a diffusion action
where_is_vm_created = surf_reac_wall_tile;
}
else {
assert(collision.is_wall_collision());
wall = &p.get_wall(collision.colliding_wall_index);
Vec2 hit_wall_pos2d = GeometryUtils::xyz2uv(p, collision.pos, *wall);
if (!wall->grid.is_initialized()) {
wall->initialize_grid(p);
}
tile_index_t hit_wall_tile_index = GridUtils::uv2grid_tile_index(hit_wall_pos2d, *wall);
where_is_vm_created = WallTileIndexPair(collision.colliding_wall_index, hit_wall_tile_index);
}
// tiny diffuse done in update_vol_mol_after_rxn_with_surf_mol
// cannot cross walls
CollisionUtils::update_counted_volume_id_when_crossing_wall(
p, *wall, product_orientation, vm_initialization);
}
// adding molecule might invalidate references of already existing molecules and also of species
Molecule& new_vm = p.add_volume_molecule(vm_initialization);
// id used to schedule a diffusion action
new_m_id = new_vm.id;
const BNG::Species& species_new_ref = p.get_species(product_species_id);
new_vm.set_flag(MOLECULE_FLAG_VOL);
new_vm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
if (is_orientable) {
// - for an orientable reaction, we need to move products away from the surface
// to ensure they end up on the correct side of the plane.
update_vol_mol_after_rxn_with_surf_mol(
p, *wall, product_orientation, collision, new_vm
);
}
#ifdef DEBUG_RXNS
DUMP_CONDITION4(
new_vm.id,
new_vm.dump(p, "", " created vm:", world->get_current_iteration(), time);
);
#endif
}
else {
// see release_event_t::place_single_molecule_onto_grid, merge somehow
// get info on where to place the product and increment the counter
assert(current_surf_product_position_index < assigned_surf_product_positions.size());
const GridPos& new_grid_pos = assigned_surf_product_positions[current_surf_product_position_index];
assert(new_grid_pos.is_assigned());
Vec2 pos;
switch (new_grid_pos.type) {
case GridPosType::REACA_UV:
if (rxn->is_unimol() && (num_surface_products == 2) && (surf_reac != NULL)) {
// there must be a single position with random setting for the second surface product,
// find and use it
const GridPos* second_prod_grid_pos =
GridPos::get_second_surf_product_pos(assigned_surf_product_positions, current_surf_product_position_index);
assert(second_prod_grid_pos != nullptr);
pos = GridPosition::find_closest_position(p, new_grid_pos, *second_prod_grid_pos);
}
else {
assert(new_grid_pos.pos_is_set);
pos = new_grid_pos.pos;
}
break;
case GridPosType::REACB_UV:
case GridPosType::POS_UV:
assert(new_grid_pos.pos_is_set);
pos = new_grid_pos.pos;
break;
case GridPosType::RANDOM:
if (rxn->is_unimol() && !surf_pos_reacA_is_used && (num_surface_products == 2)) {
const GridPos* second_prod_grid_pos =
GridPos::get_second_surf_product_pos(assigned_surf_product_positions, current_surf_product_position_index);
assert(second_prod_grid_pos != nullptr);
pos = GridPosition::find_closest_position(p, new_grid_pos, *second_prod_grid_pos);
}
else {
const Wall& wall = p.get_wall(new_grid_pos.wall_index);
pos = GridUtils::grid2uv_random(wall, new_grid_pos.tile_index, world->rng);
}
break;
default:
release_assert(false);
}
// create our new molecule
Molecule sm_to_add(MOLECULE_ID_INVALID, product_species_id, pos, time);
sm_to_add.set_flag(MOLECULE_FLAG_SURF);
sm_to_add.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
// set wall and grid information
sm_to_add.s.wall_index = new_grid_pos.wall_index;
sm_to_add.s.grid_tile_index = new_grid_pos.tile_index;
// and orientation
sm_to_add.s.orientation = product_orientation;
// might invalidate references of already existing molecules
// returned molecule has its id set
Molecule& new_sm = p.add_surface_molecule(sm_to_add);
Grid& grid = p.get_wall(new_grid_pos.wall_index).grid;
grid.set_molecule_tile(new_sm.s.grid_tile_index, new_sm.id);
new_m_id = new_sm.id;
#ifdef DEBUG_RXNS
DUMP_CONDITION4(
new_sm.id,
new_sm.dump(p, "", " created sm:", world->get_current_iteration(), time);
);
#endif
current_surf_product_position_index++;
}
p.get_m(new_m_id).diffusion_time = time;
if (before_this_iterations_end(time)) {
new_diffuse_actions.push_back(DiffuseAction(new_m_id, where_is_vm_created));
}
product_ids.push_back(new_m_id);
// refresh reacA and reacB pointers, we are added new molecules in this loop and they point to that vector
reacA = &p.get_m(reacA_id);
reacB = (reacB_id != MOLECULE_ID_INVALID) ? &p.get_m(reacB_id) : nullptr;
surf_reac = (surf_reac_id != MOLECULE_ID_INVALID) ? &p.get_m(surf_reac_id) : nullptr;
} // end for - product creation
// this is a safe point where we can manipulate contents of this event
bool cancel_reaction;
handle_rxn_callback(p, collision, time, rxn, reacA, reacB, product_ids, cancel_reaction);
if (cancel_reaction) {
// user requested to cancel the reaction, we must keep both reactants and remove products
set<molecule_id_t> reactant_ids;
reactant_ids.insert(reacA->id);
if (reacB != nullptr) {
reactant_ids.insert(reacB->id);
}
for (molecule_id_t prod_id: product_ids) {
// the product to be removed must not be a maintained reactant
if (reactant_ids.count(prod_id) == 0) {
// remove created products
p.set_molecule_as_defunct(p.get_m(prod_id));
}
}
keep_reacA = true;
if (reacB != nullptr) {
keep_reacB = true;
}
}
if (optional_product_ids != nullptr) {
*optional_product_ids = product_ids;
}
// we might need to swap info on which reactant was kept
if (reactants_swapped) {
bool tmp = keep_reacA;
keep_reacA = keep_reacB;
keep_reacB = tmp;
}
return res;
}
// ---------------------------------- unimolecular reactions ----------------------------------
// WARNING: might invalidate molecule and species references
// returns true if molecule survived
bool DiffuseReactEvent::outcome_unimolecular(
Partition& p,
Molecule& m,
const double scheduled_time,
RxnClass* rxn_class,
const BNG::rxn_class_pathway_index_t pathway_index,
MoleculeIdsVector* optional_product_ids
) {
molecule_id_t id = m.id;
// a PATHWAY_INDEX_NO_RXN pathway might have been selected
// when no unimol rxn matched compartments
if (pathway_index >= BNG::PATHWAY_INDEX_LEAST_VALID) {
Vec3 pos;
if (m.is_vol()) {
pos = m.v.pos;
}
else if (m.is_surf()) {
Wall& w = p.get_wall(m.s.wall_index);
const Vec3& wall_vert0 = p.get_geometry_vertex(w.vertex_indices[0]);
pos = GeometryUtils::uv2xyz(m.s.pos, w, wall_vert0);
}
else {
pos = Vec3(POS_INVALID);
assert(false);
}
Collision collision(
CollisionType::UNIMOLECULAR, &p, m.id, scheduled_time, pos, rxn_class);
bool ignoredA, ignoredB;
// creates new molecule(s) as output of the unimolecular reaction
// !! might invalidate references (we might reorder defuncting and outcome call later)
// we are not counting unimol rxns in p.stats because they cannot be missed
int outcome_res = outcome_products_random(
p, collision, scheduled_time, pathway_index, ignoredA, ignoredB, optional_product_ids);
assert(outcome_res == RX_A_OK || outcome_res == RX_BLOCKED);
Molecule& m_new_ref = p.get_m(id);
const RxnRule* unimol_rx = rxn_class->get_rxn_for_pathway(pathway_index);
// and defunct this molecule if it was not kept
assert(unimol_rx->reactants.size() == 1 || unimol_rx->is_absorptive_region_rxn());
if (outcome_res != RX_BLOCKED && !unimol_rx->is_simple_cplx_reactant_on_both_sides_of_rxn_w_identical_compartments(0)) {
#ifdef DEBUG_RXNS
DUMP_CONDITION4(
m_new_ref.id,
m_new_ref.dump(p, "", m_new_ref.is_vol() ? "Unimolecular vm defunct:" : "Unimolecular sm defunct:", world->get_current_iteration(), scheduled_time, false);
);
#endif
p.set_molecule_as_defunct(m_new_ref);
return false;
}
}
// molecule survived
// we must reschedule the molecule's unimol rxn, this will happen right away
// during the molecule's diffusion
Molecule& m_new_ref = p.get_m(id);
m_new_ref.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
return true;
}
// returns true if molecule survived
bool DiffuseReactEvent::cross_transparent_wall(
Partition& p,
const Collision& collision,
Molecule& vm, // moves vm to the reflection point
Vec3& remaining_displacement,
double& t_steps,
double& elapsed_molecule_time,
wall_index_t& last_hit_wall_index
) {
#ifdef DEBUG_COUNTED_VOLUMES
vm.dump(p, "- Before crossing: ");
#endif
const Wall& w = p.get_wall(collision.colliding_wall_index);
#ifdef DEBUG_TRANSPARENT_SURFACES
std::cout << "Crossed a transparent wall, side: " << w.side << "\n";
#endif
// check if we are not crossing a compartment boundary
const GeometryObject& obj = p.get_geometry_object(w.object_index);
if (obj.represents_compartment()) {
molecule_id_t orig_vm_id = vm.id;
// get species, pretty inefficient, may need to be cached if this is a feature that is used often
BNG::Species new_species = p.get_species(vm.species_id);
new_species.set_compartment_id(BNG::COMPARTMENT_ID_NONE);
new_species.finalize_species(world->bng_engine.get_config(), true);
species_id_t new_species_id = p.get_all_species().find_or_add(new_species, true);
// using the same computation of collision time as in collide_and_react_with_surf_mol
double collision_time = elapsed_molecule_time + t_steps * collision.time;
// we create a new molecule on the boundary, move it a tiny bit in the right direction
Molecule vm_initialization(
MOLECULE_ID_INVALID, new_species_id,
collision.pos + remaining_displacement * Vec3(EPS),
event_time + collision_time);
vm_initialization.v.previous_wall_index = w.index;
Molecule& new_vm = p.add_volume_molecule(vm_initialization);
new_vm.set_flag(MOLECULE_FLAG_VOL);
new_vm.set_flag(MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN);
// schedule a diffusion action
new_vm.diffusion_time = new_vm.birthday;
if (before_this_iterations_end(new_vm.birthday)) {
new_diffuse_actions.push_back(DiffuseAction(new_vm.id));
}
// and destroy the previous one
Molecule& orig_vm_new_ref = p.get_m(orig_vm_id);
p.set_molecule_as_defunct(orig_vm_new_ref);
#ifdef DEBUG_COUNTED_VOLUMES
vm_initialization.dump(p, "- After crossing: ");
#endif
return false;
}
else {
// keep the current molecule and just move it
// Update molecule location to the point of wall crossing
vm.v.pos = collision.pos;
vm.v.subpart_index = p.get_subpart_index(vm.v.pos);
const BNG::Species& sp = p.bng_engine.get_all_species().get(vm.species_id);
// it is ok that we ignore overlapped walls, counted volumes include all objects and
// if we cross somewhere where it is not clear, the counted volume for the molecule is
// recomputed
CollisionUtils::update_counted_volume_id_when_crossing_wall(
p, w, collision.get_orientation_against_wall(), vm);
// ignore the collision time, it is a bit earlier and does not fit for multiple collisions in the
// same time step
double t_smash = collision.time;
remaining_displacement = remaining_displacement * Vec3(1.0 - t_smash);
elapsed_molecule_time += t_steps * t_smash;
t_steps *= (1.0 - t_smash);
if (t_steps < EPS) {
t_steps = EPS;
}
last_hit_wall_index = w.index;
#ifdef DEBUG_COUNTED_VOLUMES
vm.dump(p, "- After crossing: ");
#endif
return true;
}
}
// ---------------------------------- dumping methods ----------------------------------
void DiffuseReactEvent::dump(const std::string ind) const {
cout << ind << "Diffuse-react event:\n";
std::string ind2 = ind + " ";
BaseEvent::dump(ind2);
cout << ind2 << "barrier_time_from_event_time: \t\t" << time_up_to_next_barrier << " [double] (may be unset initally)\t\t\n";
}
} /* namespace mcell */
| C++ |
3D | mcellteam/mcell | src4/bngl_exporter.cpp | .cpp | 24,033 | 660 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "bngl_exporter.h"
#include <iostream>
#include <sstream>
#include "world.h"
#include "partition.h"
#include "release_event.h"
#include "mol_or_rxn_count_event.h"
#include "vtk_utils.h"
#include "datamodel_defines.h"
using namespace std;
namespace MCell {
void BNGLExporter::clear_temporaries() {
nfsim_export = false;
world = nullptr;
}
// returns empty string if everything went well, nonempty string with error message
std::string BNGLExporter::export_to_bngl(
World* world_,
const std::string& file_name,
const API::BNGSimulationMethod simulation_method) {
clear_temporaries();
nfsim_export = simulation_method == API::BNGSimulationMethod::NF;
world = world_;
// contains all error messages, best effort approach is used where all parts are attempted to be generated
string err_msg;
ofstream out;
out.open(file_name);
if (!out.is_open()) {
return "Could not open output file " + file_name + ".";
}
out << "# This file was an automatically exported from MCell\n";
out << "# Used units:\n";
if (world->config.use_bng_units) {
out << "# Seed species rxn rates: N (copy number)\n";
out << "# Compartment volume: um^3\n";
out << "# Unimolecular rxn rates: 1/s\n";
if (world->config.use_bng_units) {
out << "# Bimolecular rxn rates: um^3*N^-1*s^-1\n";
}
else {
out << "# MCell bimolecular vol-vol or vol-surf rxn rates: M^-1*s^-1\n";
out << "# MCell bimolecular surf-surf rxn rates: um^2*N^-1*s^-1\n";
if (nfsim_export) {
out << "# NFSim bimolecular rxn rates: N^-1*s^-1 (compartment volumes are ignored)\n";
}
else {
out << "# BioNetGen (ODE, SSA, PLA) bimolecular rxn rates: um^3*N^-1*s^-1\n";
}
}
}
out << "\n";
const Partition& p = world->get_partition(PARTITION_ID_INITIAL);
if (nfsim_export) {
if (world->config.use_bng_units) {
// fail immediately
return "BNGL export with NFSim using BNG units as a source is not supported yet.\n";
}
if (p.get_geometry_objects().size() > 1) {
// fail immediately
return "BNGL export with NFSim is not supported only for models having 1 geometry object.\n";
}
}
// check if there is a single object
string single_object_name;
double single_object_volume = 0;
double single_object_area = 0;
if (p.get_geometry_objects().size() == 1) {
const GeometryObject& obj = p.get_geometry_objects()[0];
single_object_name = obj.name;
double volume_internal_units = VtkUtils::get_geometry_object_volume(world, obj);
if (volume_internal_units == FLT_INVALID) {
return "Compartment object " + obj.name + " is not watertight and its volume cannot be computed.\n";
}
single_object_volume = volume_internal_units * pow(world->config.length_unit, 3);
single_object_area = Geometry::compute_geometry_object_area(p, obj) * pow(world->config.length_unit, 2);
}
stringstream parameters;
stringstream molecule_types;
stringstream reaction_rules;
stringstream compartments;
parameters << BNG::BEGIN_PARAMETERS << "\n";
parameters << BNG::IND << "# general parameters\n";
if (world->config.use_bng_units) {
parameters << BNG::IND << BNG::BNG_UNITS << " 1\n";
}
parameters << BNG::IND << BNG::ITERATIONS << " " << world->total_iterations << "\n";
parameters << BNG::IND << BNG::MCELL_TIME_STEP << " " << f_to_str(world->config.time_unit) << "\n";
if (single_object_name == BNG::DEFAULT_COMPARTMENT_NAME) {
parameters << BNG::IND << BNG::MCELL_DEFAULT_COMPARTMENT_VOLUME << " " << f_to_str(single_object_volume) << "\n";
}
err_msg += set_compartment_volumes_and_areas();
err_msg += world->bng_engine.export_to_bngl(
parameters, molecule_types, compartments, reaction_rules,
simulation_method == API::BNGSimulationMethod::NF, single_object_volume, single_object_area);
// seed species
stringstream seed_species;
err_msg += export_releases_to_bngl_seed_species(parameters, seed_species);
stringstream observables;
err_msg += export_counts_to_bngl_observables(observables);
parameters << BNG::END_PARAMETERS << "\n";
out << parameters.str() << "\n";
out << molecule_types.str() << "\n";
out << compartments.str() << "\n";
out << seed_species.str() << "\n";
out << observables.str() << "\n";
out << reaction_rules.str() << "\n";
generate_simulation_action(out, simulation_method);
out.close();
return err_msg;
}
std::string BNGLExporter::set_compartment_volumes_and_areas() {
std::string err_msg;
const Partition& p = world->get_partition(PARTITION_ID_INITIAL);
BNG::BNGData& bng_data = world->bng_engine.get_data();
// first create a mapping of compartments -> geom. objects
map<BNG::compartment_id_t, const GeometryObject*> compartment_geom_obj_map;
for (const GeometryObject& obj: p.get_geometry_objects()) {
if (obj.name == BNG::DEFAULT_COMPARTMENT_NAME) {
// skip - not generated as compartment
continue;
}
// get compartment information
BNG::Compartment* compartment = bng_data.find_compartment(obj.name);
if (compartment == nullptr) {
err_msg += "Error: geometry object " + obj.name + " is not a BNGL compartment and cannot be exported.\n";
continue;
}
release_assert(compartment->is_3d);
compartment_geom_obj_map[compartment->id] = &obj;
if (compartment->parent_compartment_id != BNG::COMPARTMENT_ID_INVALID) {
BNG::Compartment& parent_compartment = bng_data.get_compartment(compartment->parent_compartment_id);
if (!parent_compartment.is_3d) {
// map also surface compartment
compartment_geom_obj_map[parent_compartment.id] = &obj;
}
}
}
// now start from compartments that have no children and gradually compute volumes
std::vector<BNG::compartment_id_t> sorted_compartment_ids;
bng_data.get_compartments_sorted_by_parents_first(sorted_compartment_ids);
for (int i = sorted_compartment_ids.size() - 1; i >= 0; i--) {
BNG::compartment_id_t comp_id = sorted_compartment_ids[i];
auto it = compartment_geom_obj_map.find(comp_id);
release_assert(it != compartment_geom_obj_map.end() && "Internal error during compartment export");
const GeometryObject* obj = it->second;
BNG::Compartment& comp = bng_data.get_compartment(comp_id);
if (comp.is_3d) {
// get volume of all children - we start from compartments with no children so the
// values were already computed
comp.set_volume(0);
double children_volume = comp.get_volume_including_children(bng_data, false);
// compute total volume
double volume_internal_units = VtkUtils::get_geometry_object_volume(world, *obj);
if (volume_internal_units == FLT_INVALID) {
return "Compartment object " + obj->name + " is not watertight and its volume cannot be computed.\n";
}
// must subtract volume of children
double volume = volume_internal_units * pow(world->config.length_unit, 3) - children_volume;
comp.set_volume(volume);
}
else {
double area = Geometry::compute_geometry_object_area(p, *obj) * pow(world->config.length_unit, 2);
comp.set_area(area);
}
}
return err_msg;
}
// returns true if check passed
static std::string get_explicit_compartment_name(
const BNG::BNGData& bng_data,
const std::string& err_suffix,
const bool vol_release,
const BNG::compartment_id_t release_compartment_id,
const BNG::compartment_id_t species_compartment_id,
std::string& explicit_compartment_name
) {
std::string err_msg;
const BNG::Compartment& comp = bng_data.get_compartment(release_compartment_id);
explicit_compartment_name = comp.name;
if (species_compartment_id != BNG::COMPARTMENT_ID_NONE) {
// check match
if (explicit_compartment_name != bng_data.get_compartment(species_compartment_id).name) {
return string(vol_release ? "Volume" : "Surface") +
" molecule's compartment does not match the target object compartment" + err_suffix;
}
// no need to generate compartment - species has the correct compartment
explicit_compartment_name = "";
}
if (vol_release) {
if (!comp.is_3d) {
return "Volume molecule's compartment is a surface/2D compartment" + err_suffix;
}
}
else {
if (comp.is_3d) {
return "Surface molecule's compartment is a volume/3D compartment" + err_suffix;
}
}
return "";
}
// search for the leftmost volume compartment if in a tree composed only from differences and leaves
static std::string get_leftmost_compartment_id_recursively(
const World* world, const std::string& err_suffix, const RegionExprNode* node, BNG::compartment_id_t& id) {
if (node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
const GeometryObject& obj = world->get_geometry_object(node->geometry_object_id);
if (obj.vol_compartment_id == BNG::COMPARTMENT_ID_NONE) {
return "Trying to convert a volume molecule release for BNGL export but used object " + obj.name + " has "
"no volume compartment specified" + err_suffix;
}
id = obj.vol_compartment_id;
return "";
}
else if (node->op == RegionExprOperator::DIFFERENCE) {
return get_leftmost_compartment_id_recursively(world, err_suffix, node->left, id);
}
else {
return "Unsupported volume region operator encountered when converting release for BNGL export" + err_suffix;
}
}
// search for the all volume compartments if in a tree composed only from differences and leaves
static std::string get_all_compartment_ids_recursively_right_is_leaf(
const World* world, const std::string& err_suffix, const RegionExprNode* node, std::vector<BNG::compartment_id_t>& ids) {
if (node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
const GeometryObject& obj = world->get_geometry_object(node->geometry_object_id);
if (obj.vol_compartment_id == BNG::COMPARTMENT_ID_NONE) {
return "Trying to convert a volume molecule release for BNGL export but used object " + obj.name + " has "
"no volume compartment specified" + err_suffix;
}
ids.push_back(obj.vol_compartment_id);
return "";
}
else if (node->op == RegionExprOperator::DIFFERENCE) {
string msg;
msg = get_all_compartment_ids_recursively_right_is_leaf(world, err_suffix, node->left, ids);
if (msg != "") {
return msg;
}
if (node->right->op != RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
return "Unsupported form of region operator expression encountered when converting release for BNGL export" + err_suffix;
}
msg = get_all_compartment_ids_recursively_right_is_leaf(world, err_suffix, node->right, ids);
return msg;
}
else {
return "Unsupported volume region operator encountered when converting release for BNGL export" + err_suffix;
}
}
std::string BNGLExporter::export_releases_to_bngl_seed_species(
std::ostream& parameters, std::ostream& seed_species) const {
string err_msg;
seed_species << BNG::BEGIN_SEED_SPECIES << "\n";
parameters << "\n" << BNG::IND << "# seed species counts\n";
vector<BaseEvent*> release_events;
world->scheduler.get_all_events_with_type_index(EVENT_TYPE_INDEX_RELEASE, release_events);
for (size_t i = 0; i < release_events.size(); i++) {
ReleaseEvent* re = dynamic_cast<ReleaseEvent*>(release_events[i]);
assert(re != nullptr);
if (re->release_shape == ReleaseShape::INITIAL_SURF_REGION) {
// TODO: check whether there are initial releases, ignoring it for now because it is not often used
continue;
}
const string & err_suffix = ", error for " + re->release_site_name + ".\n";
if (re->release_shape != ReleaseShape::REGION) {
err_msg += "Only region release shapes are currently supported for BNGL export" + err_suffix;
continue;
}
if (re->release_number_method != ReleaseNumberMethod::CONST_NUM) {
err_msg += "Only constant release number releases are currently supported for BNGL export" + err_suffix;
continue;
}
if (re->event_time != 0) {
err_msg += "Only releases for time 0 are currently supported for BNGL export" + err_suffix;
continue;
}
if (re->orientation != ORIENTATION_NONE && re->orientation != ORIENTATION_UP) {
err_msg += "Only releases for volume molecules or surface molecules with orientation UP (') "
"are currently supported for BNGL export" + err_suffix;
continue;
}
if (re->needs_release_pattern()) {
err_msg += "Releases with release patterns are not currently supported for BNGL export" + err_suffix;
continue;
}
// create parameter for the count
string seed_count_name = "seed_count_" + to_string(i);
parameters << BNG::IND << seed_count_name << " " << to_string(re->release_number) << "\n";
// determine compartment
const BNG::Species& species = world->bng_engine.get_all_species().get(re->species_id);
BNG::compartment_id_t species_compartment_id = species.get_primary_compartment_id();
const BNG::BNGData& bng_data = world->bng_engine.get_data();
string explicit_compartment_name = "";
const string err_mgs_only_compartments = "Only release regions that represent a compartment without its children "
"are supported for BNGL export" + err_suffix;
if (re->region_expr.root->op == RegionExprOperator::LEAF_SURFACE_REGION) {
// surface - must be a 2D release
const Region& region = world->get_region(re->region_expr.root->region_id);
if (DMUtils::get_region_name(region.name) != "ALL") {
return "Compartments that do not span the whole object are not supported yet" + err_suffix;
}
const GeometryObject& obj = world->get_geometry_object(region.geometry_object_id);
if (obj.surf_compartment_id == BNG::COMPARTMENT_ID_NONE) {
err_msg += "Trying to convert a surface molecule release for BNGL export but the object's surface has "
"no compartment specified" + err_suffix;
continue;
}
string msg = get_explicit_compartment_name(
bng_data, err_suffix, false, obj.surf_compartment_id, species_compartment_id,
explicit_compartment_name);
if (msg != "") {
err_msg += msg;
continue;
}
}
else if (re->region_expr.root->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
const GeometryObject& obj = world->get_geometry_object(re->region_expr.root->geometry_object_id);
if (obj.name == BNG::DEFAULT_COMPARTMENT_NAME) {
explicit_compartment_name = "";
}
else {
if (obj.vol_compartment_id == BNG::COMPARTMENT_ID_NONE) {
err_msg += "Trying to convert a volume molecule release for BNGL export but the object has "
"no volume compartment specified" + err_suffix;
continue;
}
string msg = get_explicit_compartment_name(
bng_data, err_suffix, true, obj.vol_compartment_id, species_compartment_id,
explicit_compartment_name);
if (msg != "") {
err_msg += msg;
continue;
}
}
}
else if (re->region_expr.root->op == RegionExprOperator::DIFFERENCE) {
// this may be a volume compartment that has children -> we must check that the
// release is exactly for this compartment
// example:
// EC with CP1 & CP2 -> the region expression must be in this form
// ((EC - CP1) - CP2)
BNG::compartment_id_t top_compartment_id;
string msg = get_leftmost_compartment_id_recursively(world, err_suffix, re->region_expr.root, top_compartment_id);
if (msg != "") {
err_msg += msg;
continue;
}
vector<BNG::compartment_id_t> all_compartments;
msg = get_all_compartment_ids_recursively_right_is_leaf(world, err_suffix, re->region_expr.root, all_compartments);
if (msg != "") {
err_msg += msg;
continue;
}
// now check that the compartment corresponds to
const BNG::Compartment& top_compartment = bng_data.get_compartment(top_compartment_id);
// number of children must match
if (all_compartments.size() != top_compartment.children_compartments.size() + 1) {
err_msg += err_mgs_only_compartments;
continue;
}
set<BNG::compartment_id_t> all_compartments_set(all_compartments.begin(), all_compartments.end());
// check that the same children are used
for (BNG::compartment_id_t id: top_compartment.children_compartments) {
if (all_compartments_set.count(id) != 0) {
err_msg += err_mgs_only_compartments;
continue;
}
}
msg = get_explicit_compartment_name(
bng_data, err_suffix, true, top_compartment_id, species_compartment_id,
explicit_compartment_name);
if (msg != "") {
err_msg += msg;
continue;
}
}
else {
err_msg += err_mgs_only_compartments;
continue;
}
if (explicit_compartment_name != "") {
seed_species << BNG::IND << "@" << explicit_compartment_name << ":";
}
else {
seed_species << BNG::IND;
}
seed_species << species.name << " " << seed_count_name << "\n";
}
seed_species << BNG::END_SEED_SPECIES << "\n";
return err_msg;
}
std::string BNGLExporter::export_counts_to_bngl_observables(std::ostream& observables) const {
string err_msg;
observables << BNG::BEGIN_OBSERVABLES << "\n";
vector<BaseEvent*> count_events;
world->scheduler.get_all_events_with_type_index(EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT, count_events);
for (size_t i = 0; i < count_events.size(); i++) {
MolOrRxnCountEvent* ce = dynamic_cast<MolOrRxnCountEvent*>(count_events[i]);
assert(ce != nullptr);
for (const MolOrRxnCountItem& item: ce->mol_rxn_count_items) {
const CountBuffer& buff = world->get_count_buffer(item.buffer_id);
string name;
// TODO: unify - we should use just column name
if (buff.get_output_format() == CountOutputFormat::DAT) {
// get observable name from filename
const string& path = world->get_count_buffer(item.buffer_id).get_filename();
size_t slash_pos = path.find_last_of("/\\");
release_assert(slash_pos != string::npos);
size_t dot_pos = path.rfind('.');
release_assert(dot_pos != string::npos);
name = path.substr(slash_pos + 1, dot_pos - slash_pos - 1);
}
else {
// use column name
name = buff.get_column_name(item.buffer_column_index);
}
const string& err_suffix = ", error for " + name + ".\n";
if (item.multiplier != 1.0) {
err_msg += "Observable expressions with a multiplier are not supported by BNGL export" + err_suffix;
continue;
}
string pattern;
string type;
for (const MolOrRxnCountTerm& term: item.terms) {
if (term.sign_in_expression != 1) {
err_msg += "Observable counts with negative value (subtracted) not supported by BNGL export" + err_suffix;
continue;
}
if (term.is_rxn_count()) {
err_msg += "Reaction counts are not supported by BNGL export" + err_suffix;
continue;
}
if (term.type == CountType::PresentOnSurfaceRegion) {
err_msg += "Surface molecule counts on specified regions are not supported by BNGL export, "
"use compartments if needed" + err_suffix;
continue;
}
if (term.region_expr.root != nullptr && term.region_expr.root->has_binary_op()) {
err_msg += "Counts that use region expressions with union, difference, or intersection are "
"not supported by BNGL export" + err_suffix;
continue;
}
string compartment_prefix = "";
if (term.type == CountType::EnclosedInVolumeRegion) {
if (term.primary_compartment_id != BNG::COMPARTMENT_ID_NONE) {
err_msg += "Counts that mix compartments and region are not supported by BNGL export"
"use only compartment if needed" + err_suffix;
continue;
}
release_assert(term.region_expr.root->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT);
const string& compartment_name = world->get_geometry_object(term.region_expr.root->geometry_object_id).name;
if (compartment_name != BNG::DEFAULT_COMPARTMENT_NAME) {
// NOTE: may also use compartment ID
compartment_prefix = "@" + world->get_geometry_object(term.region_expr.root->geometry_object_id).name + ":";
}
}
else if (term.primary_compartment_id != BNG::COMPARTMENT_ID_NONE) {
compartment_prefix = "@" + world->bng_engine.get_data().get_compartment(term.primary_compartment_id).name + ":";
}
// Species or Molecules
string term_type;
if (term.species_pattern_type == SpeciesPatternType::SpeciesPattern) {
term_type = BNG::OBSERVABLE_SPECIES;
}
else if (term.species_pattern_type == SpeciesPatternType::MoleculesPattern) {
term_type = BNG::OBSERVABLE_MOLECULES;
}
else {
release_assert("SpeciesId type should not be used here.");
}
if (type != "" && type != term_type) {
err_msg += "Combined Molecules and Species observables in one count are not supported by BNGL export" + err_suffix;
continue;
}
else {
type = term_type;
}
pattern += compartment_prefix + term.species_molecules_pattern.to_str(false, false) + " ";
}
observables << BNG::IND <<
type << " " << name << " " << pattern << "\n";
}
}
observables << BNG::END_OBSERVABLES << "\n";
return err_msg;
}
void BNGLExporter::generate_simulation_action(
std::ostream& out, const API::BNGSimulationMethod simulation_method) const {
if (simulation_method != API::BNGSimulationMethod::NF) {
out << "generate_network({overwrite=>1})\n";
}
string method;
switch (simulation_method) {
case API::BNGSimulationMethod::NONE:
// nothing to do
break;
case API::BNGSimulationMethod::ODE:
method = "ode";
break;
case API::BNGSimulationMethod::PLA:
method = "pla";
break;
case API::BNGSimulationMethod::SSA:
method = "ssa";
break;
case API::BNGSimulationMethod::NF:
method = "nf";
break;
default:
release_assert(false && "Invalid BNG simulation method.");
}
if (simulation_method != API::BNGSimulationMethod::NONE) {
// get sampling frequency from observables
std::vector<BaseEvent*> count_events;
world->scheduler.get_all_events_with_type_index(EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT, count_events);
double min_periodicity = FLT_INVALID;
for (const BaseEvent* e: count_events) {
if (e->periodicity_interval != 0 && e->periodicity_interval < min_periodicity) {
min_periodicity = e->periodicity_interval;
}
}
if (min_periodicity == FLT_INVALID) {
min_periodicity = 1;
}
out <<
"simulate({method=>\"" << method << "\"," <<
"seed=>1," <<
"t_end=>" << world->total_iterations * world->config.time_unit << ","
"n_steps=>" << world->total_iterations / min_periodicity;
if (simulation_method == API::BNGSimulationMethod::NF) {
out << ",glm=>1000000"; // just some default max. molecule count
}
out << "})\n";
}
}
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/collision_structs.h | .h | 6,684 | 244 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_COLLISION_STRUCTS_H_
#define SRC4_COLLISION_STRUCTS_H_
#include "defines.h"
#include <set>
#include "../libs/boost/container/small_vector.hpp"
#include "../libs/sparsehash/src/google/dense_hash_set"
#include "bng/bng.h"
namespace BNG {
class RxnClass;
}
namespace MCell {
enum class CollisionType {
INVALID,
WALL_REDO,
WALL_MISS,
WALL_FRONT,
WALL_BACK,
VOLMOL_VOLMOL,
SURFMOL_SURFMOL,
VOLMOL_SURFMOL,
UNIMOLECULAR,
INTERMEMBRANE_SURFMOL_SURFMOL
};
class Collision;
class Partition;
// TODO: use only dense hash map/set and boost vector where possible
#ifndef INDEXER_WA
typedef boost::container::small_vector<Collision, 16> CollisionsVector;
#else
typedef std::vector<Collision> CollisionsVector;
#endif
/**
* Information about collision of 2 volume/surface molecules or a of a wall collision,
* used in diffuse_react and in partition.
*/
class Collision {
public:
Collision()
#ifdef NDEBUG
:
type(CollisionType::INVALID), partition(nullptr),
diffused_molecule_id(0), time(0), pos(0),
colliding_molecule_id(0),
rxn_class(nullptr),
colliding_wall_index(0)
#else
:
type(CollisionType::INVALID), partition(nullptr),
diffused_molecule_id(MOLECULE_ID_INVALID), time(TIME_INVALID), pos(POS_INVALID),
colliding_molecule_id(MOLECULE_ID_INVALID),
rxn_class(nullptr),
colliding_wall_index(WALL_INDEX_INVALID)
#endif
{
}
// vol-surf or vol-mol collision
Collision(
const CollisionType type_,
Partition* partition_ptr,
const molecule_id_t diffused_molecule_id_,
const double time_,
const Vec3& pos_,
const molecule_id_t colliding_molecule_id_,
BNG::RxnClass* rxn_class_ptr
)
:
type(type_),
partition(partition_ptr),
diffused_molecule_id(diffused_molecule_id_),
time(time_),
pos(pos_),
colliding_molecule_id(colliding_molecule_id_),
rxn_class(rxn_class_ptr),
colliding_wall_index(WALL_INDEX_INVALID) {
assert((type == CollisionType::VOLMOL_VOLMOL || type == CollisionType::VOLMOL_SURFMOL)
&& "This constructor must be used only for volmol or volsurf collisions");
}
// surf-surf collision
Collision(
const CollisionType type_,
Partition* partition_ptr,
const molecule_id_t diffused_molecule_id_,
const double time_, // time from event start
const molecule_id_t colliding_molecule_id_,
BNG::RxnClass* rxn_class_ptr
)
:
type(type_),
partition(partition_ptr),
diffused_molecule_id(diffused_molecule_id_),
time(time_),
colliding_molecule_id(colliding_molecule_id_),
rxn_class(rxn_class_ptr),
colliding_wall_index(WALL_INDEX_INVALID) {
assert(
(type == CollisionType::SURFMOL_SURFMOL ||
type == CollisionType::INTERMEMBRANE_SURFMOL_SURFMOL) &&
"This constructor must be used only for surfsurf collisions");
}
// wall collision
Collision(
const CollisionType type_,
Partition* partition_ptr,
const molecule_id_t diffused_molecule_id_,
const double time_,
const Vec3& pos_,
const wall_index_t colliding_wall_index_
)
:
type(type_),
partition(partition_ptr),
diffused_molecule_id(diffused_molecule_id_),
time(time_),
pos(pos_),
colliding_molecule_id(MOLECULE_ID_INVALID),
rxn_class(nullptr),
colliding_wall_index(colliding_wall_index_) {
assert((type == CollisionType::WALL_BACK || type == CollisionType::WALL_FRONT) && "This constructor must be used only for wall collisions");
}
// unimolecular rxn
Collision(
const CollisionType type_,
Partition* partition_ptr,
const molecule_id_t diffused_molecule_id_,
const double time_,
const Vec3& pos_,
BNG::RxnClass* rxn_class_ptr
)
:
type(type_),
partition(partition_ptr),
diffused_molecule_id(diffused_molecule_id_),
time(time_),
pos(pos_),
colliding_molecule_id(MOLECULE_ID_INVALID),
rxn_class(rxn_class_ptr),
colliding_wall_index(WALL_INDEX_INVALID) {
assert(type == CollisionType::UNIMOLECULAR && "This constructor must be used only for unimol volmol collisions");
}
CollisionType type;
Partition* partition;
molecule_id_t diffused_molecule_id;
double time;
Vec3 pos;
// valid only for is_wall_collision
molecule_id_t colliding_molecule_id;
// used for VOLMOL_VOLMOL or type == CollisionType::VOLMOL_SURFMOL
BNG::RxnClass* rxn_class;
// valid only for COLLISION_WALL*
wall_index_t colliding_wall_index;
bool has_pos() const {
return
type != CollisionType::INVALID &&
type != CollisionType::SURFMOL_SURFMOL &&
type != CollisionType::INTERMEMBRANE_SURFMOL_SURFMOL;
}
bool is_vol_mol_vol_mol_collision() const {
return type == CollisionType::VOLMOL_VOLMOL;
}
bool is_unimol_reaction() const {
return type == CollisionType::UNIMOLECULAR;
}
bool is_mol_mol_reaction() const {
return
type == CollisionType::VOLMOL_VOLMOL ||
type == CollisionType::SURFMOL_SURFMOL ||
type == CollisionType::VOLMOL_SURFMOL ||
type == CollisionType::INTERMEMBRANE_SURFMOL_SURFMOL;
}
bool is_wall_collision() const {
assert(type != CollisionType::WALL_REDO && "Not sure yet what to do with redo");
return type == CollisionType::WALL_FRONT || type == CollisionType::WALL_BACK;
}
orientation_t get_orientation_against_wall() const {
if (type == CollisionType::WALL_BACK) {
return ORIENTATION_UP;
}
else if (type == CollisionType::WALL_FRONT) {
return ORIENTATION_DOWN;
}
else {
assert(false);
return ORIENTATION_NOT_SET;
}
}
// full dump
void dump(Partition& p, const std::string ind) const;
// for comparison with mcell3
void dump(
const Partition& p,
const std::string extra_comment,
const uint64_t iteration,
double time_override = TIME_INVALID
) const;
std::string to_string(const Partition& p) const;
static void dump_array(Partition& p, const CollisionsVector& vec);
};
} /* namespace MCell */
#endif /* SRC4_COLLISION_STRUCTS_H_ */
| Unknown |
3D | mcellteam/mcell | src4/region_utils.cpp | .cpp | 12,307 | 360 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "region_utils.h"
#include "partition.h"
#include "geometry_utils.h"
#include "geometry_utils.inl"
#include "rxn_utils.inl"
#include "wall_utils.inl"
#include "mcell_structs_shared.h"
namespace MCell {
namespace RegionUtils {
static bool is_any_rxn_reflect_or_absorb_region_border(const BNG::RxnClassesVector& rxns) {
for (const BNG::RxnClass* rxn_class: rxns) {
if (rxn_class->is_reflect_type() ||
rxn_class->is_absorb_region_border_type_incl_all_molecules()) {
return true;
}
}
return false;
}
/***********************************************************************
are_restricted_regions_for_species_on_object:
In: object
surface molecule
Out: true - if there are regions that are restrictive (REFL/ABSORB)
to the surface molecule on this object
false - if no such regions found
************************************************************************/
static bool are_restricted_regions_for_species_on_object(
Partition& p,
const GeometryObject& obj,
const Molecule& sm) {
assert(sm.is_surf());
wall_index_t wall_idx = WALL_INDEX_INVALID;
const BNG::Species& s = p.get_species(sm.species_id);
if (!s.can_interact_with_border()) {
return false;
}
// we must check all regions belonging to this object, not just the wall,
// and get all applicable reactions
BNG::RxnClassesVector matching_rxns;
RxnUtils::find_mol_reactions_with_surf_classes(p, sm, sm.s.orientation, obj, true, matching_rxns);
return is_any_rxn_reflect_or_absorb_region_border(matching_rxns);
}
/***********************************************************************
find_restricted_regions_by_object:
In: object
surface molecule
Out: an object's region list that are restrictive (REFL/ABSORB)
to the surface molecule
NULL - if no such regions found
Note: regions called "ALL" or the ones that have ALL_ELEMENTS are not
included in the return "region list".
************************************************************************/
static void find_restricted_regions_by_object(
Partition& p, const GeometryObject& obj, const Molecule& sm,
RegionIndicesSet& res) {
res.clear();
const BNG::Species& s = p.get_species(sm.species_id);
if (!s.can_interact_with_border()) {
return;
}
struct region *rp;
struct region_list *rlp, *rlps, *rlp_head = NULL;
int kk, i, wall_idx = INT_MIN;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
for (region_index_t ri: obj.regions) {
const Region& reg = p.get_region(ri);
if (reg.id == obj.encompassing_region_id) {
continue;
}
// find any wall that belongs to this region
if (reg.walls_and_edges.empty()) {
continue;
}
// we care only about reactive surfaces
if (!reg.has_surface_class()) {
continue;
}
BNG::RxnClassesVector matching_rxns;
// NOTE: MCell 3 calls also find_unimol_reactions_with_surf_classes
// however all reactions should be covered by surface_mol_reactions_with_surf_classes,
// reactions with surf classes should be always bimolecular - molecule + surf class
RxnUtils::find_mol_reactions_with_surf_classes(p, sm, sm.s.orientation, obj, true, matching_rxns);
if (is_any_rxn_reflect_or_absorb_region_border(matching_rxns)) {
res.insert(ri);
}
}
}
/************************************************************************
*
* this function determines where reactants grid1 and grid2 are located
* (inside/outside) with respect to their restrictive region borders if
* they have any.
*
* in: surface molecule 1 (located on wall 1)
* surface molecule 2 (located on wall 2)
* pointer to array with restrictive regions which contain wall 1
* pointer to array with restrictive regions which contain wall 2
* pointer to array with restrictive regions which don't contain wall 1
* pointer to array with restrictive regions which don't contain wall 2
*
* out: the 4 arrays with pointers to restrictive regions will be filled
* and returned
*
***********************************************************************/
uint determine_molecule_region_topology(
Partition& p,
const Molecule* reacA,
const Molecule* reacB,
const bool is_unimol,
RegionIndicesSet& rlp_wall_1,
RegionIndicesSet& rlp_wall_2,
RegionIndicesSet& rlp_obj_1,
RegionIndicesSet& rlp_obj_2) {
assert(reacA != nullptr);
const Molecule* sm_1 = (reacA->is_surf()) ? reacA : nullptr;
const Molecule* sm_2 = (reacB != nullptr && reacB->is_surf()) ? reacB : nullptr;
uint sm_bitmask = 0;
rlp_wall_1.clear();
rlp_wall_2.clear();
rlp_obj_1.clear();
rlp_obj_2.clear();
/* bimolecular surf-surf reaction */
if (sm_1 != NULL && sm_2 != NULL) {
const BNG::Species& species1 = p.get_species(sm_1->species_id);
const BNG::Species& species2 = p.get_species(sm_2->species_id);
const Wall& w_1 = p.get_wall(sm_1->s.wall_index);
const Wall& w_2 = p.get_wall(sm_2->s.wall_index);
const GeometryObject& go_1 = p.get_geometry_object(w_1.object_index);
const GeometryObject& go_2 = p.get_geometry_object(w_2.object_index);
/* both reactants have restrictive region borders */
if (
species1.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_1, *sm_1) &&
species2.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_2, *sm_2)
) {
WallUtils::find_restricted_regions_by_wall(p, w_1, *sm_1, rlp_wall_1);
WallUtils::find_restricted_regions_by_wall(p, w_2, *sm_2, rlp_wall_2);
/* both reactants are inside their respective restricted regions */
if (!rlp_wall_1.empty() && !rlp_wall_2.empty()) {
sm_bitmask |= ALL_INSIDE;
}
/* both reactants are outside their respective restricted regions */
else if (rlp_wall_1.empty() && rlp_wall_2.empty()) {
find_restricted_regions_by_object(p, go_1, *sm_1, rlp_obj_1);
find_restricted_regions_by_object(p, go_2, *sm_2, rlp_obj_2);
sm_bitmask |= ALL_OUTSIDE;
}
/* grid1 is inside and grid2 is outside of its respective
* restrictive region */
else if (!rlp_wall_1.empty() && rlp_wall_2.empty()) {
find_restricted_regions_by_object(p, go_2, *sm_2, rlp_obj_2);
sm_bitmask |= SURF1_IN_SURF2_OUT;
}
/* grid2 is inside and grid1 is outside of its respective
* restrictive region */
else if (rlp_wall_1.empty() && !rlp_wall_2.empty()) {
find_restricted_regions_by_object(p, go_1, *sm_1, rlp_obj_1);
sm_bitmask |= SURF1_OUT_SURF2_IN;
}
else {
assert(false);
}
}
/* only reactant sm_1 has restrictive region border property */
else if (
(species1.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_1, *sm_1)) &&
!(species2.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_2, *sm_2))
){
WallUtils::find_restricted_regions_by_wall(p, w_1, *sm_1, rlp_wall_1);
if (!rlp_wall_1.empty()) {
sm_bitmask |= SURF1_IN;
}
else {
find_restricted_regions_by_object(p, go_1, *sm_1, rlp_obj_1);
sm_bitmask |= SURF1_OUT;
}
}
/* only reactant "sm_2" has restrictive region border property */
else if (
!(species1.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_1, *sm_1)) &&
(species2.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_2, *sm_2))
){
WallUtils::find_restricted_regions_by_wall(p, w_2, *sm_2, rlp_wall_2);
if (!rlp_wall_2.empty()) {
sm_bitmask |= SURF2_IN;
}
else {
find_restricted_regions_by_object(p, go_2, *sm_2, rlp_obj_2);
sm_bitmask |= SURF2_OUT;
}
}
}
/* unimolecular reactions */
else if ((sm_1 != NULL) && is_unimol) {
const BNG::Species& species1 = p.get_species(sm_1->species_id);
const Wall& w_1 = p.get_wall(sm_1->s.wall_index);
const GeometryObject& go_1 = p.get_geometry_object(w_1.object_index);
if (
(species1.can_interact_with_border() &&
are_restricted_regions_for_species_on_object(p, go_1, *sm_1))
){
WallUtils::find_restricted_regions_by_wall(p, w_1, *sm_1, rlp_wall_1);
if (!rlp_wall_1.empty()) {
sm_bitmask |= ALL_INSIDE;
}
else {
find_restricted_regions_by_object(p, go_1, *sm_1, rlp_obj_1);
sm_bitmask |= ALL_OUTSIDE;
}
}
}
return sm_bitmask;
}
/***********************************************************************
*
* this function tests if wall target can be reached for product placement
* based on the previously stored reactant topology based on
* sm_bitmask. Below, wall 1 is the wall containing reactant 1 and
* wall 2 is the wall containing reactant 2.
*
* in: wall to test for product placement
* pointer to array with regions that contain wall 1
* pointer to array with regions that contain wall 2
* pointer to array with regions that do not contain wall 1
* pointer to array with regions that do not contain wall 2
*
* out: returns true or false depending if wall target can be
* used for product placement.
*
***********************************************************************/
bool product_tile_can_be_reached(
const Partition& p,
const wall_index_t wall_index,
const bool is_unimol,
const uint sm_bitmask,
const RegionIndicesSet& rlp_wall_1,
const RegionIndicesSet& rlp_wall_2,
const RegionIndicesSet& rlp_obj_1,
const RegionIndicesSet& rlp_obj_2) {
bool status = true;
const Wall& target = p.get_wall(wall_index);
if (sm_bitmask & ALL_INSIDE) {
if (is_unimol) {
if (!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_1)) {
status = false;
}
} else {
/* bimol reaction */
if (!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_1) ||
!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_2)) {
status = false;
}
}
} else if (sm_bitmask & ALL_OUTSIDE) {
if (is_unimol) {
if (WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_1)) {
status = false;
}
} else {
if (WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_1) ||
WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_2)) {
status = false;
}
}
} else if (sm_bitmask & SURF1_IN_SURF2_OUT) {
if (!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_1) ||
WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_2)) {
status = false;
}
} else if (sm_bitmask & SURF1_OUT_SURF2_IN) {
if (WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_1) ||
!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_2)) {
status = false;
}
} else if (sm_bitmask & SURF1_IN) {
if (!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_1)) {
status = false;
}
} else if (sm_bitmask & SURF1_OUT) {
if (WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_1)) {
status = false;
}
} else if (sm_bitmask & SURF2_IN) {
if (!WallUtils::wall_belongs_to_all_regions_in_region_list(target, rlp_wall_2)) {
status = false;
}
} else if (sm_bitmask & SURF2_OUT) {
if (WallUtils::wall_belongs_to_any_region_in_region_list(target, rlp_obj_2)) {
status = false;
}
}
return status;
}
} // namespace RegionUtil
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/scheduler.cpp | .cpp | 10,658 | 362 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "scheduler.h"
#include "generated/gen_names.h"
namespace MCell {
void Bucket::insert(BaseEvent* event) {
// check right away if the event belongs to the end
if (events.empty() || cmp_lt(events.back()->event_time, event->event_time, SCHEDULER_COMPARISON_EPS)) {
events.push_back(event);
}
else {
// go through the list and put our item to the right time and right order
auto it = events.begin();
// find the right time
while (it != events.end() && cmp_lt((*it)->event_time, event->event_time, SCHEDULER_COMPARISON_EPS)) {
it++;
}
// find the right ordering among events with the same event_time
while (it != events.end() && cmp_eq((*it)->event_time, event->event_time, SCHEDULER_COMPARISON_EPS)
&& (*it)->type_index <= event->type_index) {
// if we already found events with our type, check secondary ordering
if ((*it)->type_index == event->type_index && event->needs_secondary_ordering()) {
assert((*it)->needs_secondary_ordering());
// do we belong in front of the current event?
if (event->get_secondary_ordering_value() < (*it)->get_secondary_ordering_value()) {
// yes, terminate search
break;
}
}
it++;
}
events.insert(it, event);
}
}
Bucket::~Bucket() {
for (auto it = events.begin(); it != events.end(); it++) {
// delete remaining events, usually there should be none
delete *it;
}
}
void Bucket::dump() const {
for (const BaseEvent* event: events) {
event->dump();
}
}
// insert a new item with time event->event_time, create bucket if needed
void Calendar::insert(BaseEvent* event) {
// update barrier cache if needed
if (event->is_barrier() && event->event_time < cached_next_barrier_time) {
cached_next_barrier_time = event->event_time;
}
// align time to multiple of one if the value is close to it
// required for example for custom time step where 0.1 * 10 must be equal to 1
double rounded_time = round_f(event->event_time);
if (cmp_eq(round_f(event->event_time), event->event_time, SCHEDULER_COMPARISON_EPS)) {
event->event_time = rounded_time;
}
double bucket_start_time = event_time_to_bucket_start_time(event->event_time);
if (queue.empty()) {
// no items yet - simply create new bucket and insert our event there
queue.push_back( Bucket(bucket_start_time) );
queue.front().insert(event);
}
else {
// we first need to find out whether we already have a bucket for this event
double first_start_time = get_first_bucket_start_time();
release_assert(bucket_start_time - first_start_time >= 0 && "cannot schedule to the past"); // some eps?
size_t buckets_from_first = (bucket_start_time - first_start_time) / BUCKET_TIME_INTERVAL;
if (buckets_from_first < queue.size()) {
// bucket exists
queue[buckets_from_first].insert(event);
}
else {
// we need to create new buckets
size_t missing_buckets = buckets_from_first - queue.size() + 1;
if (missing_buckets > SCHEDULER_MAX_BUCKETS_TO_FUTURE) {
errs() << "An event such as " << API::NAME_CLASS_COUNT << " or " << API::NAME_CLASS_VIZ_OUTPUT <<
" is scheduled too far into the future (" << missing_buckets << " time steps). " <<
"This would require too much memory, please adjust its period with attribute " << API::NAME_EVERY_N_TIMESTEPS << "." <<
" (event type index " << event->type_index << ")\n";
exit(1);
}
double next_time = queue.back().start_time + BUCKET_TIME_INTERVAL;
for (size_t i = 0; i < missing_buckets; i++) {
queue.push_back(Bucket(next_time));
next_time += BUCKET_TIME_INTERVAL;
}
assert(buckets_from_first < queue.size());
queue[buckets_from_first].insert(event);
}
}
}
void Calendar::clear_empty_buckets() {
while (queue.front().events.empty()) {
queue.pop_front();
}
}
BaseEvent* Calendar::pop_next() {
clear_empty_buckets();
BaseEvent* next_event = queue.front().events.front();
queue.front().events.pop_front();
return next_event;
}
double Calendar::get_next_time() {
clear_empty_buckets();
assert(!queue.empty() && !queue.front().events.empty());
BaseEvent* next_event = queue.front().events.front();
return next_event->event_time;
}
void Calendar::dump() const {
for (const Bucket& bucket: queue) {
bucket.dump();
}
}
void Calendar::to_data_model(Json::Value& mcell_node, const bool only_for_viz) const {
for (const Bucket& bucket: queue) {
for (const BaseEvent* event: bucket.events) {
if (only_for_viz && event->type_index != EVENT_TYPE_INDEX_MOL_OR_RXN_COUNT) {
// include only visualization-related events
continue;
}
event->to_data_model(mcell_node);
}
}
}
const BaseEvent* Calendar::find_next_event_with_type_index(
const event_type_index_t event_type_index) const {
for (const Bucket& bucket: queue) {
for (const BaseEvent* event: bucket.events) {
if (event->type_index == event_type_index) {
return event;
}
}
}
return nullptr;
}
void Calendar::get_all_events_with_type_index(
const event_type_index_t event_type_index,
std::vector<BaseEvent*>& events
) {
for (const Bucket& bucket: queue) {
for (BaseEvent* event: bucket.events) {
if (event->type_index == event_type_index) {
events.push_back(event);
}
}
}
}
void Calendar::get_all_events_with_type_index(
const event_type_index_t event_type_index,
std::vector<const BaseEvent*>& events
) const {
for (const Bucket& bucket: queue) {
for (BaseEvent* event: bucket.events) {
if (event->type_index == event_type_index) {
events.push_back(event);
}
}
}
}
// returns max_time_step if no barrier is scheduled for interval
// current_time .. current_time+max_time_step
// if such a barrier exists, returns barrier time - current_time
double Calendar::get_time_up_to_next_barrier(
const double current_time, const double max_time_step) {
if (cached_next_barrier_time != TIME_INVALID &&
current_time < cached_next_barrier_time
) {
return std::min(cached_next_barrier_time - current_time, max_time_step);
}
// go through the whole schedule and find the first barrier
cached_next_barrier_time = TIME_FOREVER;
// expecting that there are only events that are scheduled
// for the future
bool found = false;
for (const Bucket& bucket: queue) {
for (const BaseEvent* event: bucket.events) {
if (event->is_barrier()) {
assert(event->event_time >= current_time);
cached_next_barrier_time = event->event_time;
found = true;
break;
}
}
if (found) {
break;
}
}
return std::min(cached_next_barrier_time - current_time, max_time_step);
}
void Scheduler::schedule_event(BaseEvent* event) {
release_assert(event->event_time != TIME_INVALID);
calendar.insert(event);
}
void Scheduler::schedule_event_asynchronously(BaseEvent* event) {
// may be called multiple times at the same moment e.g. when
// adding a checkpointing event based on some timer in Python
async_event_queue_lock.lock();
have_async_events_to_schedule = true;
async_event_queue.push_back(event);
async_event_queue_lock.unlock();
}
void Scheduler::schedule_events_from_async_queue() {
if (!have_async_events_to_schedule) {
return;
}
async_event_queue_lock.lock();
for (BaseEvent* e: async_event_queue) {
if (e->event_time == TIME_INVALID) {
// real asynchronous event,
// schedule correctly for an upcoming iteration while making sure
// that all the events from the current iteration are finished so that
// the event_type_index is correctly followed
e->event_time = floor_f(get_next_event_time(true) + 1);
}
schedule_event(e);
}
async_event_queue.clear();
have_async_events_to_schedule = false;
async_event_queue_lock.unlock();
}
double Scheduler::get_next_event_time(const bool skip_async_events_check) {
if (!skip_async_events_check) {
schedule_events_from_async_queue();
}
return calendar.get_next_time();
}
// pop next scheduled event and run its step method
EventExecutionInfo Scheduler::handle_next_event() {
// first check if there are any
schedule_events_from_async_queue();
BaseEvent* event = calendar.pop_next();
assert(event != NULL && "Empty event queue - at least end simulation event should be present");
double event_time = event->event_time;
if (event->may_be_blocked_by_barrier_and_needs_set_time_step()) {
double max_time_step = calendar.get_time_up_to_next_barrier(
event->event_time, event->get_max_time_up_to_next_barrier());
event->set_barrier_time_for_next_execution(max_time_step);
}
#ifdef DEBUG_SCHEDULER
event->dump("");
#endif
event_being_executed = event;
event->step();
event_being_executed = nullptr;
event_type_index_t type_index = event->type_index;
bool return_from_run_iterations = event->return_from_run_n_iterations_after_execution();
// schedule itself for the next period or just delete
double next_time;
bool to_schedule = event->update_event_time_for_next_scheduled_time();
if (to_schedule) {
calendar.insert(event);
}
else {
delete event;
}
return EventExecutionInfo(event_time, type_index, return_from_run_iterations);
}
void Scheduler::skip_events_up_to_time(const double start_time) {
// need to deal with imprecisions, e.g. 0.0000005 * 10^6 ~= 5.0000000000008
while (calendar.get_next_time() < start_time - EPS) {
BaseEvent* event = calendar.pop_next();
bool to_schedule = event->update_event_time_for_next_scheduled_time();
if (to_schedule) {
calendar.insert(event);
}
else {
delete event;
}
}
}
void Scheduler::dump() const {
calendar.dump();
}
void Scheduler::to_data_model(Json::Value& mcell_node, const bool only_for_viz) const {
// go through all events and run their conversion,
// for many events, the conversion does nothing
calendar.to_data_model(mcell_node, only_for_viz);
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/collision_structs.cpp | .cpp | 3,582 | 125 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <string>
#include <sstream>
#include "collision_structs.h"
#include "partition.h"
#include "molecule.h"
#include "debug_config.h"
using namespace std;
namespace MCell {
void Collision::dump(Partition& p, const std::string ind) const {
cout << ind << "diffused_molecule:\n";
p.get_m(diffused_molecule_id).dump(ind + " ");
if (type == CollisionType::VOLMOL_VOLMOL) { // dump is rather limited for now, goes not deal with all types
cout << ind << "colliding_molecule:\n";
p.get_m(colliding_molecule_id).dump(ind + " ");
cout << ind << "reaction:";
if (rxn_class != nullptr) {
rxn_class->dump(ind + " ");
}
}
else {
cout << ind << "colliding_wall_index: " << colliding_wall_index << "\n";
}
cout << "time: \t\t" << time << " [double] \t\t\n";
cout << "position: \t\t" << pos << " [vec3_t] \t\t\n";
}
void Collision::dump(
const Partition& p,
const std::string extra_comment,
const uint64_t iteration,
double time_override
) const {
cout << extra_comment << "it:" << iteration << ", ";
if (is_mol_mol_reaction()) {
cout <<
"bimol rxn" <<
", idA:" << diffused_molecule_id <<
", idB:" << colliding_molecule_id <<
", time: " << ((time_override == TIME_INVALID) ? time : time_override);
if (type != CollisionType::SURFMOL_SURFMOL) {
cout << ", pos " << pos;
}
}
else if (is_unimol_reaction()) {
cout <<
"unimol rxn" <<
", idA:" << diffused_molecule_id <<
", time: " << ((time_override == TIME_INVALID) ? time : time_override);
}
else if (is_wall_collision()) {
#ifndef NODEBUG_WALL_COLLISIONS
cout << "wall collision" <<
", idA:" << diffused_molecule_id <<
//", wall index:" << colliding_wall_index <<
", time: " << ((time_override == TIME_INVALID) ? time : time_override) <<
", pos " << pos;
#endif
}
else {
assert(false);
}
cout << "\n";
}
string Collision::to_string(const Partition& p) const {
stringstream ss;
if (type == CollisionType::VOLMOL_VOLMOL) {
ss << "coll_idx: " << colliding_molecule_id;
}
else {
ss << "obj name: " << p.get_geometry_object(p.get_wall(colliding_wall_index).object_index).name;
ss << ", wall index: " << colliding_wall_index;
ss << ", wall side: " << p.get_wall(colliding_wall_index).side;
#ifdef DEBUG_COUNTED_VOLUMES
ss << ", geom obj id: " << p.get_wall(colliding_wall_index).object_id;
#endif
}
ss << ", time: " << time << ", pos: " << pos;
return ss.str();
}
void Collision::dump_array(Partition& p, const CollisionsVector& vec) {
// printed in reverse - same as
for (size_t i = 0; i < vec.size(); i++) {
#ifdef NODEBUG_WALL_COLLISIONS
if (vec[i].type == CollisionType::WALL_FRONT || vec[i].type == CollisionType::WALL_BACK) {
continue;
}
#endif
const char* str_type = (vec[i].type == CollisionType::VOLMOL_VOLMOL) ? "mol collision " : "wall collision ";
cout << " " << str_type << i << ": " << vec[i].to_string(p) << "\n";
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/region_expr.cpp | .cpp | 4,153 | 157 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "region_expr.h"
#include "datamodel_defines.h"
#include "world.h"
#include "api/python_export_constants.h"
using namespace std;
namespace MCell {
string RegionExprNode::to_string(const World* world, const bool for_datamodel) const {
stringstream out;
assert(op != RegionExprOperator::INVALID);
if (op == RegionExprOperator::LEAF_SURFACE_REGION) {
if (world != nullptr) {
const string& region_name = world->get_region(region_id).name;
if (for_datamodel) {
return DMUtils::get_object_w_region_name(region_name);
}
else {
return region_name;
}
}
else {
return "region id: " + std::to_string(region_id);
}
}
else if (op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
if (world != nullptr) {
const string& go_name = world->get_geometry_object(geometry_object_id).name;
if (for_datamodel) {
return DMUtils::remove_obj_name_prefix(go_name) + API::REGION_ALL_SUFFIX;
}
else {
return go_name;
}
}
else {
return "geometry object id: " + std::to_string(geometry_object_id);
}
}
assert(left != nullptr);
out << "(";
out << left->to_string(world, for_datamodel);
switch(op) {
case RegionExprOperator::UNION:
out << " + ";
break;
case RegionExprOperator::INTERSECT:
out << " * ";
break;
case RegionExprOperator::DIFFERENCE:
out << " - ";
break;
default:
assert(false);
}
out << right->to_string(world, for_datamodel);
out << ")";
return out.str();
}
void RegionExprNode::dump(const World* world) const {
cout << to_string(world);
}
RegionExprNode* RegionExpr::create_new_expr_node_leaf_surface_region(const region_id_t id) {
assert(id != REGION_ID_INVALID);
RegionExprNode* res = new RegionExprNode;
res->op = RegionExprOperator::LEAF_SURFACE_REGION;
res->region_id = id;
all_region_expr_nodes.push_back(res);
return res;
}
RegionExprNode* RegionExpr::create_new_expr_node_leaf_geometry_object(const geometry_object_id_t id) {
assert(id != GEOMETRY_OBJECT_ID_INVALID);
RegionExprNode* res = new RegionExprNode;
res->op = RegionExprOperator::LEAF_GEOMETRY_OBJECT;
res->geometry_object_id = id;
all_region_expr_nodes.push_back(res);
return res;
}
RegionExprNode* RegionExpr::create_new_region_expr_node_op(
const RegionExprOperator op, RegionExprNode* left, RegionExprNode* right) {
RegionExprNode* res = new RegionExprNode;
res->op = op;
res->left = left;
res->right = right;
all_region_expr_nodes.push_back(res);
return res;
}
static RegionExprNode* clone_region_expr_recursively(
RegionExpr* re,
const RegionExprNode* src_node) {
assert(src_node != nullptr);
if (src_node->op == RegionExprOperator::LEAF_GEOMETRY_OBJECT) {
return re->create_new_expr_node_leaf_geometry_object(src_node->geometry_object_id);
}
else if (src_node->op == RegionExprOperator::LEAF_SURFACE_REGION) {
return re->create_new_expr_node_leaf_surface_region(src_node->region_id);
}
else if (src_node->has_binary_op()) {
return re->create_new_region_expr_node_op(
src_node->op,
clone_region_expr_recursively(re, src_node->left),
clone_region_expr_recursively(re, src_node->right));
}
else {
assert(false);
return nullptr;
}
}
RegionExpr& RegionExpr::operator=(const RegionExpr& other) {
if (other.root == nullptr) {
root = nullptr;
}
else {
root = clone_region_expr_recursively(this, other.root);
}
return *this;
}
RegionExpr::~RegionExpr() {
for (RegionExprNode* expr_node: all_region_expr_nodes) {
delete expr_node;
}
}
} /* namespace MCell */
| C++ |
3D | mcellteam/mcell | src4/sort_mols_by_subpart_event.cpp | .cpp | 2,889 | 101 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <algorithm>
#include "sort_mols_by_subpart_event.h"
#include "world.h"
#include "partition.h"
using namespace std;
namespace MCell {
void SortMolsBySubpartEvent::dump(const string ind) const {
cout << ind << "Sort mols by subpart event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
struct SubpartComparatorForId
{
SubpartComparatorForId(const vector<uint>& mempart_indices_)
: mempart_indices(mempart_indices_) {
}
bool operator () (const molecule_id_t id1, const molecule_id_t id2) const {
assert(id1 < mempart_indices.size());
assert(id2 < mempart_indices.size());
return mempart_indices[id1] < mempart_indices[id2];
}
const vector<uint>& mempart_indices;
};
struct SubpartComparatorForMol
{
SubpartComparatorForMol(const vector<uint>& mempart_indices_)
: mempart_indices(mempart_indices_) {
}
bool operator () (const Molecule& m1, const Molecule& m2) const {
assert(m1.id < mempart_indices.size());
assert(m2.id < mempart_indices.size());
return mempart_indices[m1.id] < mempart_indices[m2.id];
}
const vector<uint>& mempart_indices;
};
void SortMolsBySubpartEvent::step() {
for (Partition& p: world->get_partitions()) {
vector<Molecule>& molecules = p.get_molecules();
if (molecules.empty()) {
// simply skip if there are no molecules
continue;
}
// may create too large array when multiple partitions will be used
// but currently the molecule ID assignment is done in partitions anyway
vector<uint> mempart_indices(p.get_next_molecule_id_no_increment());
for (Molecule& m: molecules) {
const BNG::Species& sp = p.get_species(m.species_id);
if (m.is_vol() && sp.can_diffuse()) {
mempart_indices[m.id] = m.v.subpart_index;
}
else {
// set some value that should not collide with subpart indices
mempart_indices[m.id] = 0x80000000;
}
}
// also sort molecules in the molecules array
sort(molecules.begin(), molecules.end(), SubpartComparatorForMol(mempart_indices));
// and update their indices in the molecule_id_to_index_mapping
std::vector<molecule_index_t>& molecule_id_to_index_mapping = p.get_molecule_id_to_index_mapping();
for (size_t i = 0; i < molecules.size(); i++) {
const Molecule& m = molecules[i];
assert(molecule_id_to_index_mapping.size() < m.id);
molecule_id_to_index_mapping[m.id] = i;
}
}
}
} /* namespace mcell */
| C++ |
3D | mcellteam/mcell | src4/molecule.h | .h | 8,086 | 265 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MOLECULE_H_
#define SRC4_MOLECULE_H_
#include "bng/bng.h"
#include "defines.h"
namespace BNG {
class SpeciesContainer;
}
namespace MCell {
class Partition;
// WARNING: do not change these values, checkpointed models use them
// TODO: probably print this out in some reasonable form into checkpoints, it is printed as a number now
enum molecule_flag_t {
// volume/surface information is only cached from BNG CplxInstance
MOLECULE_FLAG_SURF = 1 << 0, // originally TYPE_SURF
MOLECULE_FLAG_VOL = 1 << 1, // originally TYPE_VOL
MOLECULE_FLAG_MATURE = 1 << 2, // originally MATURE_MOLECULE
MOLECULE_FLAG_ACT_CLAMPED = 1 << 3, // originally ACT_CLAMPED
MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN = 1 << 4,
MOLECULE_FLAG_RESCHEDULE_UNIMOL_RXN_ON_NEXT_RXN_RATE_UPDATE = 1 << 5,
// flags needed for concentration clamp handling,
// only one of them may be set
MOLECULE_FLAG_CLAMP_ORIENTATION_UP = 1 << 6,
MOLECULE_FLAG_CLAMP_ORIENTATION_DOWN = 1 << 7,
MOLECULE_FLAG_NO_NEED_TO_SCHEDULE = 1 << 14,
MOLECULE_FLAG_DEFUNCT = 1 << 15,
};
/**
* Base class for all molecules.
*/
class Molecule {
public:
// Warning: ctors do not reset surf or vol data
Molecule()
: id(MOLECULE_ID_INVALID), species_id(SPECIES_ID_INVALID), flags(0),
diffusion_time(TIME_INVALID), unimol_rxn_time(TIME_FOREVER),
birthday(TIME_INVALID) {
}
Molecule(const Molecule& m) {
*this = m;
}
// volume molecule
Molecule(
const molecule_id_t id_, const species_id_t species_id_,
const Vec3& pos_, const double birthday_
)
: id(id_), species_id(species_id_), flags(MOLECULE_FLAG_VOL),
diffusion_time(TIME_INVALID), unimol_rxn_time(TIME_INVALID),
birthday(birthday_) {
v.pos = pos_;
v.subpart_index = SUBPART_INDEX_INVALID;
v.reactant_subpart_index = SUBPART_INDEX_INVALID;
v.counted_volume_index = COUNTED_VOLUME_INDEX_INVALID;
v.previous_wall_index = WALL_INDEX_INVALID;
}
// surface molecule
Molecule(
const molecule_id_t id_, const species_id_t species_id_,
const Vec2& pos2d, const double birthday_
)
: id(id_), species_id(species_id_), flags(MOLECULE_FLAG_SURF),
diffusion_time(TIME_INVALID), unimol_rxn_time(TIME_INVALID),
birthday(birthday_) {
s.pos = pos2d;
s.orientation = ORIENTATION_NONE;
s.wall_index = WALL_INDEX_INVALID;
s.grid_tile_index = TILE_INDEX_INVALID;
}
// assuming that this function has no virtual methods and has only POD types
// gcc9 reports a warning but, the memcpy here is safe
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wclass-memaccess"
void operator = (const Molecule& m) {
memcpy(this, &m, sizeof(Molecule));
}
#pragma GCC diagnostic pop
void reset_vol_data() {
v.pos = Vec3(POS_INVALID);
v.subpart_index = SUBPART_INDEX_INVALID;
v.reactant_subpart_index = SUBPART_INDEX_INVALID;
v.counted_volume_index = COUNTED_VOLUME_INDEX_INVALID;
v.previous_wall_index = WALL_INDEX_INVALID;
}
void reset_surf_data() {
s.pos = Vec2(POS_INVALID);
s.orientation = ORIENTATION_NONE;
s.wall_index = WALL_INDEX_INVALID;
s.grid_tile_index = TILE_INDEX_INVALID;
}
// may set flag for optimizations
// called when a molecule is added to partition
void set_no_need_to_schedule_flag(const BNG::SpeciesContainer& all_species);
// data is ordered to avoid alignment holes (for 64-bit floats)
molecule_id_t id; // unique molecule id (for now it is unique per partition but should be world-wide unique)
species_id_t species_id;
uint flags;
// time for which it was scheduled, based on this value Partition creates 'ready list'
// for DiffuseAndReactEvent
double diffusion_time;
// time assigned for unimol rxn, TIME_INVALID if time has not been set or molecule has no unimol rxn,
// TIME_FOREVER if the probability of an existing unimol rxn is 0
double unimol_rxn_time;
// - time when the molecule was released or created
// - used when determining whether this molecule is mature
// - release delay time is not added to the birthday time, a newly released molecule
// with release delay will have its birthday at the beginning of the iteration
double birthday;
// update assignment operator when modifying this
union {
// volume molecule data
struct {
Vec3 pos;
subpart_index_t subpart_index;
// during diffusion the molecules' subpart index might change but the reactant_subpart_index
// stays the same until its moved in the Partition's volume_molecule_reactants_per_subpart[] array
subpart_index_t reactant_subpart_index;
// do not assign directly, use set_counted_volume_and_compartment istead
counted_volume_index_t counted_volume_index;
// needed for clamp concentration handling
wall_index_t previous_wall_index;
} v;
// surface molecule data
struct {
Vec2 pos;
// we probably do not want subpart index, wall index serves this purpose
//subpart_index_t subpart_index;
orientation_t orientation;
wall_index_t wall_index;
tile_index_t grid_tile_index;
} s;
};
bool has_flag(uint flag) const {
assert(__builtin_popcount(flag) == 1);
return (flags & flag) != 0;
}
void set_flag(uint flag) {
assert(__builtin_popcount(flag) == 1);
flags = flags | flag;
}
void clear_flag(uint flag) {
assert(__builtin_popcount(flag) == 1);
flags = flags & ~flag;
}
void set_clamp_orientation(orientation_t value) {
assert(value >= ORIENTATION_DOWN && value <= ORIENTATION_UP);
if (value == ORIENTATION_NONE) {
clear_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_UP);
clear_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_DOWN);
}
else if (value == ORIENTATION_DOWN) {
clear_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_UP);
set_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_DOWN);
}
else {
set_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_UP);
clear_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_DOWN);
}
}
int get_clamp_orientation() const {
if (has_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_UP)) {
return ORIENTATION_UP;
}
else if (has_flag(MOLECULE_FLAG_CLAMP_ORIENTATION_DOWN)) {
return ORIENTATION_DOWN;
}
else {
return ORIENTATION_NONE;
}
}
bool is_vol() const {
bool res = has_flag(MOLECULE_FLAG_VOL);
if (res) {
assert(!is_surf());
}
return res;
}
bool is_surf() const {
bool res = has_flag(MOLECULE_FLAG_SURF);
if (res) {
assert(!is_vol());
}
return res;
}
bool is_defunct() const {
// TODO LATER: molecules with release_delay > 0 were actually not released yet,
// but is seems that mcell3 does not care, so let's keep it like this for now
return has_flag(MOLECULE_FLAG_DEFUNCT) != 0;
}
void set_is_defunct() {
assert(!is_defunct() && "We really should not be defuncting one molecule multiple times");
flags |= MOLECULE_FLAG_DEFUNCT;
}
orientation_t get_orientation() const {
if (is_surf()) {
return s.orientation;
}
else {
return ORIENTATION_NONE; // or not set?
}
}
void dump(const std::string ind="") const;
void dump(
const Partition& p,
const std::string extra_comment,
const std::string ind = " ",
const uint64_t iteration = 0,
const double time = 0,
const bool print_position = true,
const bool print_flags = false
) const;
std::string to_string() const;
static void dump_array(const std::vector<Molecule>& vec);
};
} // namespace mcell
#endif // SRC4_MOLECULE_H_
| Unknown |
3D | mcellteam/mcell | src4/simulation_config.h | .h | 4,566 | 142 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_SIMULATION_CONFIG_H_
#define SRC4_SIMULATION_CONFIG_H_
#include "defines.h"
const char* const RUN_REPORT_PREFIX = "run_report_";
namespace MCell {
namespace API {
enum class WarningLevel;
};
/*
* Constant data set in initialization useful for all classes, single object is owned by world
*/
class SimulationConfig: public BNG::BNGConfig {
public:
SimulationConfig() :
initial_time(TIME_INVALID),
initial_iteration(UINT_INVALID),
vacancy_search_dist2(FLT_INVALID),
partition_edge_length(FLT_INVALID),
num_subparts_per_partition_edge(UINT_INVALID),
num_subparts_per_partition_edge_squared(UINT_INVALID),
num_subparts(UINT_INVALID),
subpart_edge_length(FLT_INVALID),
subpart_edge_length_rcp(FLT_INVALID),
num_radial_subdivisions(1024),
use_expanded_list(true),
randomize_smol_pos(false),
check_overlapped_walls(true),
rxn_class_cleanup_periodicity(0),
species_cleanup_periodicity(0),
molecules_order_random_shuffle_periodicity(DEFAULT_MOL_ORDER_SHUFFLE_PERIODICITY),
sort_mols_by_subpart(false),
memory_limit_gb(-1),
iteration_report(true),
wall_overlap_report(false),
simulation_stats_every_n_iterations(0),
continue_after_sigalrm(false),
has_intersecting_counted_objects(false)
{
// enable debug assertions in libBNG
debug_requires_diffusion_constants = true;
}
// configuration
double initial_time; // simulation start time in us, non-zero if starting from a checkpoint
uint64_t initial_iteration; // initial iteration, non-zero if starting from a checkpoint
pos_t vacancy_search_dist2; /* Square of distance to search for free grid
location to place surface product */
Vec3 partition0_llf;
pos_t partition_edge_length;
uint num_subparts_per_partition_edge;
uint num_subparts_per_partition_edge_squared;
uint num_subparts; // == num_subpartitions_per_partition_edge^3
pos_t subpart_edge_length; // == partition_edge_length / subpartitions_per_partition_dimension
pos_t subpart_edge_length_rcp; // == 1/subpartition_edge_length
uint num_radial_subdivisions; /* Size of 3D step length lookup tables, not configurable by user yet */
std::vector<double> radial_2d_step; /* Lookup table of 2D diffusion step lengths (r_step_surface) */
std::vector<double> radial_3d_step; /* Lookup table of 3D diffusion step lengths (r_step) */
// other options
bool use_expanded_list; /* If set, check neighboring subvolumes for mol-mol
interactions */
bool randomize_smol_pos; /* If set, always place surface molecule at random
location instead of center of grid */
bool check_overlapped_walls; /* Check geometry for overlapped walls? */
API::WarningLevel molecule_placement_failure;
uint rxn_class_cleanup_periodicity;
uint species_cleanup_periodicity;
uint molecules_order_random_shuffle_periodicity;
bool sort_mols_by_subpart;
int memory_limit_gb; // -1 means that limit is disabled
// similar to MCell3's ITERATION_REPORT
bool iteration_report;
bool wall_overlap_report;
int simulation_stats_every_n_iterations;
bool continue_after_sigalrm;
// initialized in World::init_counted_volumes
// also tells whether waypoints in a partition were initialized
bool has_intersecting_counted_objects;
void init() {
BNGConfig::init();
init_subpartition_edge_length();
init_radial_steps();
}
void dump();
double get_simulation_start_time() const {
assert(initial_time != TIME_INVALID);
// simulation starts always in integer values of internal time
double res = floor_to_multiple_f(initial_time / time_unit, 1);
assert((int)res == res);
return res;
}
// returns 'checkpoints/seed_<SEED>/it_' - without the iteration number
std::string get_default_checkpoint_dir_prefix() const;
std::string get_run_report_file_name() const;
void initialize_run_report_file();
private:
void init_subpartition_edge_length();
void init_radial_steps();
};
std::string get_seed_dir_name(const int seed);
} // namespace MCell
#endif // SRC4_SIMULATION_CONFIG_H_
| Unknown |
3D | mcellteam/mcell | src4/simulation_stats.cpp | .cpp | 4,382 | 130 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "simulation_stats.h"
#include "bng/bng.h"
using namespace std;
namespace MCell {
RxnCountStats& SimulationStats::get_rxn_stats(
const BNG::RxnContainer& all_rxns, const BNG::RxnClass* rxn_class) {
// we must use reactant name pairs to store the information
// because their count does not grow and rxn classes
// also assuming that the names of reactants in reactions are always sorted
// (does not matter how), i.e. there is always A + B -> C and A + B -> D,
// and not B + A -> E
assert(rxn_class->get_num_reactions() >= 1);
BNG::rxn_rule_id_t id = rxn_class->get_rxn_rule_id(0);
const BNG::RxnRule* rxn = all_rxns.get(id);
assert(rxn != nullptr);
assert(rxn->is_bimol());
const string& n1 = rxn->reactants[0].name;
assert(n1 != "");
const string& n2 = rxn->reactants[1].name;
assert(n2 != "");
// increment or add a new item if the pair we are searching for does not exist
auto it1 = bimol_rxn_stats.find(n1);
if (it1 == bimol_rxn_stats.end()) {
it1 = bimol_rxn_stats.insert(make_pair(n1, NameStatsMap())).first;
}
auto it2 = it1->second.find(n2);
if (it2 == it1->second.end()) {
it2 = it1->second.insert(make_pair(n2, RxnCountStats())).first;
}
return it2->second;
}
void SimulationStats::inc_rxn_occurred(
const BNG::RxnContainer& all_rxns, const BNG::RxnClass* rxn_class,
const uint64_t occurred) {
get_rxn_stats(all_rxns, rxn_class).occurred += occurred;
}
void SimulationStats::inc_rxn_skipped(
const BNG::RxnContainer& all_rxns, const BNG::RxnClass* rxn_class,
const double skipped) {
get_rxn_stats(all_rxns, rxn_class).skipped += skipped;
}
void SimulationStats::print_missed_rxns_warnings(const std::string& warnings_report_file_name) {
bool first_report = true;
stringstream ss;
for (auto n1_map_pair: bimol_rxn_stats) {
for (auto n2_stats_pair: n1_map_pair.second) {
const RxnCountStats& stats = n2_stats_pair.second;
if (stats.skipped > 0) {
if (first_report) {
ss << "Warning: Some reactions were missed because total reaction probability exceeded 1.\n";
first_report = false;
}
double perc =
0.001 * round(1000 * stats.skipped * 100 / (stats.skipped + stats.occurred));
if (perc >= SQRT_EPS) { // ignore really small values
ss <<
" " << n1_map_pair.first << " + " << n2_stats_pair.first << " -- " <<
perc << "% of reactions missed.\n";
}
}
}
}
if (ss.str() != "") {
cerr << ss.str();
if (warnings_report_file_name != "") {
BNG::append_to_report(warnings_report_file_name, ss.str());
}
}
}
void SimulationStats::print_report(const std::string& warnings_report_file_name) {
cout << "Total number of ray-subvolume intersection tests (number of ray_trace calls): " << ray_voxel_tests << "\n";
cout << "Total number of ray-polygon intersection tests: " << ray_polygon_tests << "\n";
cout << "Total number of ray-polygon intersections: " << ray_polygon_colls << "\n";
cout << "Total number of mol reflections from a wall: " << mol_wall_reflections << "\n";
cout << "Total number of vol mol vol mol collisions: " << vol_mol_vol_mol_collisions << "\n";
cout << "Total number of molecule moves between walls: " << mol_moves_between_walls << "\n";
cout << "Total number of usages of waypoints for counted volumes: " << num_waypoints_used << "\n";
cout << "Total number of counted volume recomputations: " << recomputations_of_counted_volume << "\n";
cout << "Total number of diffuse 3d calls: " << diffuse_3d_calls << "\n";
if (diffusion_number != 0) {
cout << "Average diffusion jump was: " <<
diffusion_cummtime / (double)diffusion_number << " timesteps " <<
" (" << diffusion_cummtime << "/" << diffusion_number << ")\n";
}
if (warnings_report_file_name != "") {
print_missed_rxns_warnings(warnings_report_file_name);
}
}
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/simulation_config.cpp | .cpp | 5,762 | 187 | /******************************************************************************
*
* Copyright (C) 2019,2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "simulation_config.h"
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
#include "bng/bng_defines.h"
#include "api/api_common.h"
using namespace std;
namespace MCell {
// returns 'checkpoints/seed_<SEED>/it_' - without the iteration number
std::string SimulationConfig::get_default_checkpoint_dir_prefix() const {
return
API::DEFAULT_CHECKPOINTS_DIR + BNG::PATH_SEPARATOR +
get_seed_dir_name(initial_seed) + BNG::PATH_SEPARATOR +
API::DEFAULT_ITERATION_DIR_PREFIX;
}
std::string SimulationConfig::get_run_report_file_name() const {
return std::string(BNG::REPORT_DIR) + BNG::PATH_SEPARATOR + RUN_REPORT_PREFIX + seed_as_str() + BNG::REPORT_EXT;
}
void SimulationConfig::initialize_run_report_file() {
BNG::initialize_report_file(get_run_report_file_name(), "Run");
}
void SimulationConfig::init_subpartition_edge_length() {
release_assert(partition_edge_length > 0);
subpart_edge_length = partition_edge_length / (double)num_subparts_per_partition_edge;
#if POS_T_BYTES == 4
// we must transform the subpart edge length so that it can be precisely represented with reciprocal
// -> clear the lowest bits
uint tmp;
memcpy(&tmp, &subpart_edge_length, sizeof(uint));
tmp &= 0xFFFFF000;
memcpy(&subpart_edge_length, &tmp, sizeof(uint));
subpart_edge_length_rcp = 1.0/subpart_edge_length;
assert(1.0f/subpart_edge_length_rcp == subpart_edge_length);
assert(length_unit == 1.0f/rcp_length_unit);
#else
subpart_edge_length_rcp = 1.0/subpart_edge_length;
#endif
partition_edge_length = subpart_edge_length * num_subparts_per_partition_edge;
num_subparts_per_partition_edge_squared = powu(num_subparts_per_partition_edge, 2);
num_subparts = powu(num_subparts_per_partition_edge, 3);
}
/***************************************************************************
r_func:
In: double containing distance (arbitrary units, mean=1.0)
Out: double containing probability of diffusing that distance
***************************************************************************/
static double r_func(double s) {
// keeping as double because it is used for time/spece step computations
double f, s_sqr, val;
f = 2.2567583341910251478; /* 4.0/sqrt(pi) */
s_sqr = s * s;
val = f * s_sqr * exp(-s_sqr);
return val;
}
/***************************************************************************
init_r_step:
In: number of desired radial subdivisions
Out: pointer to array of doubles containing those subdivisions
returns NULL on malloc failure
Note: This is for 3D diffusion from a point source (molecule movement)
***************************************************************************/
/***************************************************************************
init_r_step_surface:
In: number of desired radial subdivisions
Out: pointer to array of doubles containing those subdivisions
returns NULL on malloc failure
Note: This is for 3D molecules emitted from a plane
***************************************************************************/
void SimulationConfig::init_radial_steps() {
double inc, target, accum, r, r_max, delta_r, delta_r2;
// 3D
radial_3d_step.resize(num_radial_subdivisions);
inc = 1.0 / num_radial_subdivisions;
accum = 0;
r_max = 3.5;
delta_r = r_max / (1000 * num_radial_subdivisions);
delta_r2 = 0.5 * delta_r;
r = 0;
target = 0.5 * inc;
uint j = 0;
while (j < num_radial_subdivisions) {
accum = accum + (delta_r * r_func(r + delta_r2));
r = r + delta_r;
if (accum >= target) {
radial_3d_step[j] = r;
target = target + inc;
j++;
}
}
// 2D
radial_2d_step.resize(num_radial_subdivisions);
static const double sqrt_pi = 1.7724538509055160273;
double step = 1.0 / num_radial_subdivisions;
int i = 0;
double p = (1.0 - 1e-6) * step;
r = 0;
for (; p < 1.0; p += step, i++) {
double r_min = 0;
double r_max = 3.0; /* 17 bit high-end CDF cutoff */
for (int j = 0; j < 20; j++) /* 20 bits of accuracy */
{
r = 0.5 * (r_min + r_max);
double cdf = 1.0 - exp(-r * r) + sqrt_pi * r * erfc(r);
if (cdf > p)
r_max = r;
else
r_min = r;
}
radial_2d_step[i] = r;
}
}
void SimulationConfig::dump() {
BNGConfig::dump();
cout << "SimulationConfig:\n";
#define DUMP_ATTR(A) cout << " " #A ": \t\t" << A << "\n"
DUMP_ATTR(vacancy_search_dist2);
DUMP_ATTR(partition0_llf);
DUMP_ATTR(partition_edge_length);
DUMP_ATTR(num_subparts_per_partition_edge);
DUMP_ATTR(num_subparts_per_partition_edge_squared);
DUMP_ATTR(num_subparts);
DUMP_ATTR(subpart_edge_length);
DUMP_ATTR(subpart_edge_length_rcp);
DUMP_ATTR(num_radial_subdivisions);
DUMP_ATTR(use_expanded_list);
DUMP_ATTR(randomize_smol_pos);
DUMP_ATTR(check_overlapped_walls);
DUMP_ATTR(rxn_class_cleanup_periodicity);
DUMP_ATTR(species_cleanup_periodicity);
DUMP_ATTR(sort_mols_by_subpart);
DUMP_ATTR(memory_limit_gb);
DUMP_ATTR(simulation_stats_every_n_iterations);
DUMP_ATTR(has_intersecting_counted_objects);
#undef DUMP_ATTR
}
std::string get_seed_dir_name(const int seed) {
std::stringstream seed_num;
seed_num << std::setfill('0') << std::setw(API::DEFAULT_SEED_DIR_DIGITS) << seed;
return API::DEFAULT_SEED_DIR_PREFIX + seed_num.str();
}
} // namespace MCell
| C++ |
3D | mcellteam/mcell | src4/mol_order_shuffle_event.cpp | .cpp | 940 | 38 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <iostream>
#include <algorithm>
#include "mol_order_shuffle_event.h"
#include "world.h"
#include "partition.h"
using namespace std;
namespace MCell {
void MolOrderShuffleEvent::dump(const string ind) const {
cout << ind << "Mol order shuffle event:\n";
string ind2 = ind + " ";
BaseEvent::dump(ind2);
}
void MolOrderShuffleEvent::step() {
for (Partition& p: world->get_partitions()) {
p.shuffle_schedulable_molecule_ids();
}
}
} /* namespace mcell */
| C++ |
3D | mcellteam/mcell | src4/simulation_stats.h | .h | 3,880 | 163 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_SIMULATION_STATS_H_
#define SRC4_SIMULATION_STATS_H_
#include "defines.h"
namespace BNG {
class RxnContainer;
class RxnClass;
}
// for reporting of skipped reactions
struct RxnCountStats {
RxnCountStats() :
occurred(0),
skipped(0) {
}
long long occurred;
double skipped;
};
typedef std::map<std::string, RxnCountStats> NameStatsMap;
typedef std::map<std::string, NameStatsMap> BimolRxnCountStatsMap;
namespace MCell {
/*
* Stats collected during simulation, contains also the number of the current iteration
*/
class SimulationStats {
public:
SimulationStats() {
reset(true);
}
void inc_ray_voxel_tests() {
ray_voxel_tests++;
}
void inc_ray_polygon_tests() {
ray_polygon_tests++;
}
void inc_ray_polygon_colls() {
ray_polygon_colls++;
}
void inc_mol_wall_reflections() {
mol_wall_reflections++;
}
void inc_vol_mol_vol_mol_collisions() {
vol_mol_vol_mol_collisions++;
}
// new mcell4 stats
void inc_mol_moves_between_walls() {
mol_moves_between_walls++;
}
void inc_recomputations_of_counted_volume() {
recomputations_of_counted_volume++;
}
void inc_num_waypoints_used() {
num_waypoints_used++;
}
void inc_diffuse_3d_calls() {
diffuse_3d_calls++;
}
void inc_diffusion_cummtime(const double steps) {
diffusion_number++;
diffusion_cummtime += steps; // this is a bit weird, steps are not time
}
// warnings_report_file_name may be "", in that case warnings are not appended to
// the warnings file
void print_report(const std::string& warnings_report_file_name = "");
const uint64_t& get_current_iteration() const {
return current_iteration;
}
uint64_t& get_current_iteration() {
return current_iteration;
}
// to be used only in initialization
void set_current_iteration(const uint64_t it) {
current_iteration = it;
}
void inc_rxn_occurred(
const BNG::RxnContainer& all_rxns,
const BNG::RxnClass* rxn_class,
const uint64_t occurred = 1);
void inc_rxn_skipped(
const BNG::RxnContainer& all_rxns,
const BNG::RxnClass* rxn_class,
const double skipped);
void reset(const bool reset_also_current_iteration) {
if (reset_also_current_iteration) {
current_iteration = 0;
}
ray_voxel_tests = 0;
ray_polygon_tests = 0;
ray_polygon_colls = 0;
mol_wall_reflections = 0;
vol_mol_vol_mol_collisions = 0;
mol_moves_between_walls = 0;
num_waypoints_used = 0;
recomputations_of_counted_volume = 0;
diffuse_3d_calls = 0;
diffusion_number = 0;
diffusion_cummtime = 0.0;
}
private:
RxnCountStats& get_rxn_stats(
const BNG::RxnContainer& all_rxns, const BNG::RxnClass* rxn_class);
// warnings_report_file_name may be "", in that case warnings are not appended to
// the warnings file
void print_missed_rxns_warnings(const std::string& warnings_report_file_name);
uint64_t current_iteration;
// the stats below are not stored into checkpoint
uint64_t ray_voxel_tests;
uint64_t ray_polygon_tests;
uint64_t ray_polygon_colls;
uint64_t mol_wall_reflections;
uint64_t vol_mol_vol_mol_collisions;
uint64_t mol_moves_between_walls;
uint64_t num_waypoints_used;
uint64_t recomputations_of_counted_volume;
uint64_t diffuse_3d_calls;
uint64_t diffusion_number;
double diffusion_cummtime;
BimolRxnCountStatsMap bimol_rxn_stats;
};
} // namespace MCell
#endif // SRC4_SIMULATION_CONFIG_H_
| Unknown |
3D | mcellteam/mcell | src4/clamp_release_event.cpp | .cpp | 7,579 | 241 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "clamp_release_event.h"
#include "rng.h" // MCell 3
#include "isaac64.h"
#include "mcell_structs_shared.h"
#include "logging.h"
#include <iostream>
#include "defines.h"
#include "world.h"
#include "partition.h"
#include "datamodel_defines.h"
#include "release_event.h"
using namespace std;
namespace MCell {
void ClampReleaseEvent::dump(const std::string indent) const {
cout << "Concentration clamp event:\n";
string ind2 = indent + " ";
BaseEvent::dump(ind2);
cout << ind2 << "species_id: \t\t" << species_id << " [species_id_t]\n";
cout << ind2 << "surf_class_species_id: \t\t" << surf_class_species_id << " [species_id_t]\n";
cout << ind2 << "concentration: \t\t" << concentration << " [double]\n";
cout << ind2 << "scaling_factor: \t\t" << scaling_factor << " [double]\n";
dump_cumm_area_and_pwall_index_pairs(cumm_area_and_pwall_index_pairs, ind2);
}
void ClampReleaseEvent::to_data_model(Json::Value& mcell_node) const {
// --- define_surface_classes --- (only when needed)
Json::Value& define_surface_classes = mcell_node[KEY_DEFINE_SURFACE_CLASSES];
DMUtils::add_version(define_surface_classes, VER_DM_2014_10_24_1638);
Json::Value& surface_class_list = define_surface_classes[KEY_SURFACE_CLASS_LIST];
Json::Value clamp;
clamp[KEY_NAME] = world->get_all_species().get(surf_class_species_id).name;
clamp[KEY_DESCRIPTION] = "";
DMUtils::add_version(clamp, VER_DM_2018_01_11_1330);
Json::Value& surface_prop_list = clamp[KEY_SURFACE_CLASS_PROP_LIST];
surface_prop_list = Json::Value(Json::arrayValue);
Json::Value surface_prop_item;
surface_prop_item[KEY_CLAMP_VALUE] = f_to_str(concentration);
surface_prop_item[KEY_SURF_CLASS_ORIENT] = DMUtils::orientation_to_str(orientation);
surface_prop_item[KEY_MOLECULE] = world->get_all_species().get(species_id).name;
surface_prop_item[KEY_NAME] = ""; // blender exports name but it does not seem to be needed
surface_prop_item[KEY_AFFECTED_MOLS] = VALUE_SINGLE;
if (type == ClampType::CONCENTRATION) {
surface_prop_item[KEY_SURF_CLASS_TYPE] = VALUE_CLAMP_CONCENTRATION;
}
else if (type == ClampType::FLUX) {
surface_prop_item[KEY_SURF_CLASS_TYPE] = VALUE_CLAMP_FLUX;
}
else {
assert(false);
}
DMUtils::add_version(surface_prop_item, VER_DM_2015_11_08_1756);
surface_prop_list.append(surface_prop_item);
surface_class_list.append(clamp);
// the affected region is printed in Partition::to_data_model
}
void ClampReleaseEvent::update_cumm_areas_and_scaling() {
pos_t cumm_area = 0;
for (auto& area_pindex_pair: cumm_area_and_pwall_index_pairs) {
PartitionWallIndexPair pindex = area_pindex_pair.second;
const Wall& w = world->get_partition(pindex.first).get_wall(pindex.second);
assert(w.area != 0);
cumm_area += w.area;
area_pindex_pair.first = cumm_area;
}
if (!cumm_area_and_pwall_index_pairs.empty()) {
scaling_factor =
cumm_area_and_pwall_index_pairs.back().first * pow_f(world->config.length_unit, 3)
/ 2.9432976599069717358e-9; /* sqrt(MY_PI)/(1e-15*N_AV) */
}
else {
scaling_factor = 0;
}
}
/*************************************************************************
poisson_dist:
In: mean value
random number distributed uniformly between 0 and 1
Out: integer sampled from the Poisson distribution.
Note: This does not sample the CDF. Instead, it works its way outwards
from the peak of the PDF. Kinda weird. It is not the case
that low values of the random number will give low values. It
is also not super-efficient, but it works.
*************************************************************************/
static int poisson_dist(double lambda, double p) {
int i, lo, hi;
double plo, phi, pctr;
double lambda_i;
i = (int)lambda;
pctr = exp_f(-lambda + i * log_f(lambda) -
lgamma(i + 1)); /* Highest probability bin */
if (p < pctr) {
return i;
}
lo = hi = i;
plo = phi = pctr; /* Start at highest-probability bin and work outwards */
p -= pctr;
lambda_i = 1.0 / lambda;
while (p > 0) { /* Keep going until we exhaust probabilities */
if (lo > 0) { /* We still have a low tail, test it */
plo *= lo * lambda_i; /* Recursive formula for p for this bin */
lo--;
if (p < plo)
return lo;
p -= plo;
}
/* Always test the high tail (it's infinite) */
hi++;
phi = phi * lambda / hi; /* Recursive formula for p for this bin */
if (p < phi) {
return hi;
}
p -= phi + DBL_EPSILON; /* Avoid infinite loop from poor roundoff */
}
/* should never get here */
assert(false);
return -1;
}
/*************************************************************************
run_concentration_clamp:
Out: No return value. Molecules are released at concentration-clamped
surfaces to maintain the desired concentation.
*************************************************************************/
void ClampReleaseEvent::step() {
if (cumm_area_and_pwall_index_pairs.empty()) {
// nothing to do - maybe not schedule at all?
return;
}
Partition& p = world->get_partition(PARTITION_ID_INITIAL);
const BNG::Species& species = world->bng_engine.get_all_species().get(species_id);
assert(species.is_vol());
double n_collisions = scaling_factor * species.space_step * concentration / species.time_step;
release_assert(n_collisions < (double)INT_MAX);
if (orientation != ORIENTATION_NONE) {
n_collisions *= 0.5;
}
int n_to_emit = poisson_dist(n_collisions, rng_dbl(&world->rng));
if (n_to_emit == 0) {
return;
}
pos_t total_area = cumm_area_and_pwall_index_pairs.back().first;
while (n_to_emit > 0) {
int idx = cum_area_bisect_high(cumm_area_and_pwall_index_pairs, rng_dbl(&world->rng) * total_area);
assert(cumm_area_and_pwall_index_pairs[idx].second.first == PARTITION_ID_INITIAL);
const Wall& w = p.get_wall(cumm_area_and_pwall_index_pairs[idx].second.second);
const Vec3& v0 = p.get_wall_vertex(w, 0);
const Vec3& v1 = p.get_wall_vertex(w, 1);
const Vec3& v2 = p.get_wall_vertex(w, 2);
double s1 = sqrt_f(rng_dbl(&world->rng));
double s2 = rng_dbl(&world->rng) * s1;
Vec3 v;
v = v0 + Vec3(s1) * (v1 - v0) + Vec3(s2) * (v2 - v1);
orientation_t o;
if (orientation == ORIENTATION_NONE) {
o = (rng_uint(&world->rng) & 2) - 1;
}
else {
o = orientation;
}
pos_t eps = POS_EPS * o;
pos_t move1 = fabs_p(v.x);
pos_t move2 = fabs_p(v.y);
if (move1 < move2) {
move1 = move2;
}
move2 = fabs_p(v.z);
if (move1 < move2) {
move1 = move2;
}
if (move1 > 1.0f){
eps *= move1;
}
Vec3 pos = v + w.normal * Vec3(eps);
Molecule& new_vm = p.add_volume_molecule(
Molecule(MOLECULE_ID_INVALID, species_id, pos, event_time), 0.5 /* release delay time */
);
new_vm.flags |= MOLECULE_FLAG_ACT_CLAMPED | MOLECULE_FLAG_SCHEDULE_UNIMOL_RXN;
new_vm.set_clamp_orientation(o);
new_vm.v.previous_wall_index = w.index;
n_to_emit--;
}
}
} // namespace mcell
| C++ |
3D | mcellteam/mcell | src4/scheduler.h | .h | 5,859 | 198 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_SCHEDULER_H_
#define SRC4_SCHEDULER_H_
#include <deque>
#include <list>
#include <mutex>
#include "base_event.h"
namespace Json {
class Value;
}
namespace MCell {
// we should represent the time interval with a precisely
// represented floating point value
const double BUCKET_TIME_INTERVAL = 1;
class Bucket {
public:
Bucket(double start_time_) :
start_time(start_time_) {
}
~Bucket();
void insert(BaseEvent* event);
void dump() const;
double start_time;
std::list<BaseEvent*> events;
};
typedef std::deque<Bucket> BucketDeque;
class Calendar {
public:
Calendar() :
cached_next_barrier_time(TIME_INVALID) {
// create at least one item?
queue.push_back(Bucket(TIME_SIMULATION_START));
}
~Calendar() {
// implicitly calls destructors of items in queue and
// deletes all events
}
void insert(BaseEvent* event);
double get_next_time();
BaseEvent* pop_next();
void dump() const;
void to_data_model(Json::Value& mcell_node, const bool only_for_viz) const;
const BaseEvent* find_next_event_with_type_index(
const event_type_index_t event_type_index) const;
void get_all_events_with_type_index(
const event_type_index_t event_type_index, std::vector<BaseEvent*>& events);
void get_all_events_with_type_index(
const event_type_index_t event_type_index, std::vector<const BaseEvent*>& events) const;
double get_time_up_to_next_barrier(const double current_time, const double max_time_step);
void print_periodic_stats() const {
std::cout << "Calendar: queue.size() = " << queue.size() << "\n";
}
private:
// differs from get_next_time - does not clear empty buckets
// and returns bucket start time, not the next event time
double get_first_bucket_start_time() {
assert(queue.size() != 0);
return queue.front().start_time;
}
double event_time_to_bucket_start_time(const double time) {
// flooring to a multiple of BUCKET_TIME_INTERVAL
return floor_to_multiple_f(time, BUCKET_TIME_INTERVAL);
}
BucketDeque::iterator get_or_create_bucket(const double time);
void clear_empty_buckets();
// queue might be empty
BucketDeque queue;
// used in get_time_up_to_next_barrier
double cached_next_barrier_time;
};
// Structure used to return information about the event that was just handled
struct EventExecutionInfo {
EventExecutionInfo(
const double time_, const event_type_index_t type_index_, const bool return_from_run_iterations_) :
time(time_), type_index(type_index_), return_from_run_iterations(return_from_run_iterations_) {
}
double time;
event_type_index_t type_index;
bool return_from_run_iterations;
};
class Scheduler {
public:
Scheduler() :
event_being_executed(nullptr),
async_event_queue_lock(mtx, std::defer_lock),
have_async_events_to_schedule(false) {
}
// - scheduler becomes owner of the base_event object
// - event's time must be valid and not be in the past
void schedule_event(BaseEvent* event);
// - similar as schedule_event only guarded by a critical section and
// inserts the event into a separate queue of events,
// - every method whose outcome might be changed by the events in the async queue
// must call schedule_events_from_async_queue to schedule these events correctly
// - events that have event_time == TIME_INVALID will get time for the next iteration
// so that they are executed in the right order
void schedule_event_asynchronously(BaseEvent* event);
// returns the time of next event
double get_next_event_time(const bool skip_async_events_check = false);
// returns time of the event that was handled
EventExecutionInfo handle_next_event();
// skip events for checkpointing,
// may take long time if periodic events are scheduled
void skip_events_up_to_time(const double start_time);
void dump() const;
void to_data_model(Json::Value& mcell_node, const bool only_for_viz) const;
const BaseEvent* find_next_event_with_type_index(
const event_type_index_t event_type_index) {
schedule_events_from_async_queue();
return calendar.find_next_event_with_type_index(event_type_index);
}
void get_all_events_with_type_index(
const event_type_index_t event_type_index, std::vector<BaseEvent*>& events) {
schedule_events_from_async_queue();
return calendar.get_all_events_with_type_index(event_type_index, events);
}
BaseEvent* get_event_being_executed() {
return event_being_executed;
}
const BaseEvent* get_event_being_executed() const {
return event_being_executed;
}
void print_periodic_stats() const {
calendar.print_periodic_stats();
}
private:
// checks if there are events in the async queue and schedules them
// not really const but maintains the consistency of events visible to the outside
void schedule_events_from_async_queue();
Calendar calendar;
// callback might need to query which event is being executed right now
// is nullptr when no event is running
BaseEvent* event_being_executed;
// lock for asynchronous scheduling of events
std::mutex mtx;
std::unique_lock<std::mutex> async_event_queue_lock;
std::vector<BaseEvent*> async_event_queue;
volatile bool have_async_events_to_schedule; // unguarded flag for fast check whether async_event_queue is empty
};
} // namespace mcell
#endif // SRC4_SCHEDULER_H_
| Unknown |
3D | mcellteam/mcell | src4/bngl_exporter.h | .h | 1,407 | 58 | /******************************************************************************
*
* Copyright (C) 2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_BNGL_EXPORTER_H_
#define SRC4_BNGL_EXPORTER_H_
#include <string>
namespace MCell {
namespace API {
enum class BNGSimulationMethod;
}
class World;
class BNGLExporter {
public:
// returns empty string if everything went well,
// nonempty string with error message
std::string export_to_bngl(
World* world_,
const std::string& file_name,
const API::BNGSimulationMethod simulation_method);
private:
void clear_temporaries();
std::string set_compartment_volumes_and_areas();
std::string export_releases_to_bngl_seed_species(
std::ostream& parameters,
std::ostream& seed_species) const;
std::string export_counts_to_bngl_observables(
std::ostream& observables) const;
void generate_simulation_action(
std::ostream& out, const API::BNGSimulationMethod simulation_method) const;
World* world;
bool nfsim_export;
};
} // namespace MCell
#endif // SRC4_BNGL_EXPORTER_H_
| Unknown |
3D | mcellteam/mcell | src4/dyn_vertex_structs.h | .h | 1,794 | 60 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_DYN_VERTEX_STRUCTS_H_
#define SRC4_DYN_VERTEX_STRUCTS_H_
#include "defines.h"
#include "../libmcell/api/shared_structs.h"
namespace MCell {
class Partition;
struct WallMoveInfo {
bool wall_changes_area;
std::vector<VertexMoveInfo*> vertex_moves;
};
typedef std::map<wall_index_t, WallMoveInfo> WallsWithTheirMovesMap;
struct VolumeMoleculeMoveInfo {
VolumeMoleculeMoveInfo(const molecule_id_t molecule_id_, const wall_index_t wall_index_, const bool place_above_)
: molecule_id(molecule_id_), wall_index(wall_index_), place_above(place_above_) {
}
// molecule to move
molecule_id_t molecule_id;
// which wall moved this molecule first
wall_index_t wall_index;
// above or below
bool place_above;
};
typedef std::vector<VolumeMoleculeMoveInfo> VolumeMoleculeMoveInfoVector;
struct SurfaceMoleculeMoveInfo {
SurfaceMoleculeMoveInfo(const molecule_id_t molecule_id_, const wall_index_t wall_index_, const Vec3 pos3d_)
: molecule_id(molecule_id_), wall_index(wall_index_), pos3d(pos3d_) {
}
// molecule to move
molecule_id_t molecule_id;
// which wall moved this molecule first
wall_index_t wall_index;
// above or below
Vec3 pos3d;
};
typedef std::vector<SurfaceMoleculeMoveInfo> SurfaceMoleculeMoveInfoVector;
} // namespace MCell
#endif /* SRC4_DYN_VERTEX_STRUCTS_H_ */
| Unknown |
3D | mcellteam/mcell | src4/mcell3_world_converter.h | .h | 5,072 | 154 | /******************************************************************************
*
* Copyright (C) 2019 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_MCELL3_WORLD_CONVERTER_H_
#define SRC4_MCELL3_WORLD_CONVERTER_H_
#include "api/callbacks.h"
#include "mcell_structs_shared.h"
#include "world.h"
#include <map>
struct volume; // MCell3
struct wall;
struct region;
struct region_list;
struct geom_object;
struct pathway;
struct rxn;
struct release_evaluator;
namespace MCell {
class ReleaseEvent;
class RegionExprNode;
class ClampReleaseEvent;
class MCell3WorldConverter {
public:
MCell3WorldConverter() :
world(nullptr), callbacks(nullptr) {
}
~MCell3WorldConverter() {
delete world;
}
void reset();
bool convert(volume* s);
private:
bool convert_simulation_setup(volume* s);
void create_uninitialized_walls_for_polygonal_object(const geom_object* o);
bool convert_wall_and_update_regions(
const wall* w, GeometryObject& object,
const region_list* rl
);
bool convert_region(Partition& p, const region* r, region_index_t& region_index);
bool convert_polygonal_object(const geom_object* o, const std::string& instantiate_name);
bool convert_geometry_meta_object_recursively(volume* s, geom_object* meta_inst);
bool convert_geometry_objects(volume* s);
bool convert_species(volume* s);
void create_clamp_release_event(
const pathway* current_pathway, const BNG::RxnRule& rxn, const std::vector<species_id_t>& reactant_species_ids);
bool convert_single_reaction(const rxn *rx);
bool convert_rxns(volume* s);
RegionExprNode* create_release_region_terms_recursively(
release_evaluator* expr, ReleaseEvent& event_data, const bool is_vol_release
);
bool convert_release_events(volume* s);
bool convert_viz_output_events(volume* s);
bool convert_mol_or_rxn_count_events(volume* s);
void update_and_schedule_concentration_clamps();
public:
// contained world object
World* world;
API::Callbacks callbacks;
private:
species_id_t get_mcell4_species_id(u_int mcell3_id) {
auto it = mcell3_species_id_map.find(mcell3_id);
assert(it != mcell3_species_id_map.end());
assert(it->second != SPECIES_ID_INVALID);
return it->second;
}
// mapping from mcell3 species id to mcell4 species id
std::map<u_int, species_id_t> mcell3_species_id_map;
void add_mcell4_vertex_index_mapping(const vector3* mcell3_vertex, PartitionVertexIndexPair pindex) {
// check that if we are adding a vertex, it is exactly the same as there was before
auto it = vector_ptr_to_vertex_index_map.find(mcell3_vertex);
if (it != vector_ptr_to_vertex_index_map.end()) {
// note: this check probably doesn't make sense because the mcell3 vertices
// would have to change during conversion
assert(it->second == pindex);
}
else {
vector_ptr_to_vertex_index_map[mcell3_vertex] = pindex;
}
}
PartitionVertexIndexPair get_mcell4_vertex_index(const vector3* mcell3_vertex) {
auto it = vector_ptr_to_vertex_index_map.find(mcell3_vertex);
assert(it != vector_ptr_to_vertex_index_map.end());
return it->second;
}
std::map<const vector3*, PartitionVertexIndexPair> vector_ptr_to_vertex_index_map;
void add_mcell4_wall_index_mapping(const wall* mcell3_wall, PartitionWallIndexPair pindex) {
assert(wall_ptr_to_vertex_index_map.find(mcell3_wall) == wall_ptr_to_vertex_index_map.end() && "Wall mapping for this wall already exists");
wall_ptr_to_vertex_index_map[mcell3_wall] = pindex;
}
PartitionWallIndexPair get_mcell4_wall_index(const wall* mcell3_wall) {
auto it = wall_ptr_to_vertex_index_map.find(mcell3_wall);
assert(it != wall_ptr_to_vertex_index_map.end());
return it->second;
}
// use only through add_mcell4_wall_index_mapping, get_mcell4_wall_index
std::map<const wall*, PartitionWallIndexPair> wall_ptr_to_vertex_index_map;
void add_mcell4_region_index_mapping(const region* mcell3_region, PartitionWallIndexPair pindex) {
assert(region_ptr_to_region_index_map.find(mcell3_region) == region_ptr_to_region_index_map.end() && "Region mapping for this wall already exists");
region_ptr_to_region_index_map[mcell3_region] = pindex;
}
PartitionRegionIndexPair get_mcell4_region_index(const region* mcell3_region) {
auto it = region_ptr_to_region_index_map.find(mcell3_region);
assert(it != region_ptr_to_region_index_map.end());
return it->second;
}
// use only through add_mcell4_region_index_mapping, get_mcell4_region_index
std::map<const region*, PartitionRegionIndexPair> region_ptr_to_region_index_map;
std::vector<ClampReleaseEvent*> concentration_clamps;
};
} // namespace mcell
#endif // SRC4_MCELL3_WORLD_CONVERTER_H_
| Unknown |
3D | mcellteam/mcell | src4/world.h | .h | 9,184 | 306 | /******************************************************************************
*
* Copyright (C) 2019-2021 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_WORLD_H_
#define SRC4_WORLD_H_
#include <time.h>
#ifndef _WIN64
#include <sys/time.h> // Linux include
#include <sys/resource.h> // Linux include
#endif
#include <functional>
#include <chrono>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <iostream>
#include "bng/bng.h"
#include "api/checkpoint_signals.h"
#include "partition.h"
#include "scheduler.h"
#include "geometry.h"
#include "count_buffer.h"
#include "memory_limit_checker.h"
#include "logging.h"
#include "rng.h"
namespace Json {
class Value;
}
namespace MCell {
namespace API {
class Model;
class Callbacks;
enum class BNGSimulationMethod;
}
class MolOrRxnCountEvent;
class World {
public:
World(API::Callbacks& callbacks_);
~World();
// MCell MDL mode
void init_and_run_simulation(const bool dump_initial_state = false, const bool dump_with_geometry = false);
void init_simulation(const double start_time);
// MCell Python mode, init_simulation must be called first
// returns number of executed iterations
uint64_t run_n_iterations(
const uint64_t num_iterations,
const bool terminate_last_iteration_after_viz_output = false // used when ending simulation
);
void end_simulation(const bool print_final_report = true);
// used by converters
void create_initial_surface_region_release_event();
// checkpointing - called from signal handler
void set_to_create_checkpoint_event_from_signal_hadler(const int signo, API::Model* model) {
signaled_checkpoint_signo = signo;
signaled_checkpoint_model = model;
}
void schedule_checkpoint_event(
const uint64_t iteration, const bool continue_simulation, const API::CheckpointSaveEventContext& ctx);
// -------------- diverse getters -----------------------------
const SimulationConfig& get_config() {
return config;
}
uint64_t get_current_iteration() const {
return stats.get_current_iteration();
}
API::Callbacks& get_callbacks() {
return callbacks;
}
// -------------- partition manipulation methods --------------
partition_id_t get_partition_index(const Vec3& pos) {
// for now a slow approach, later some hashing/memoization might be needed
for (partition_id_t i = 0; i < partitions.size(); i++) {
if (partitions[i].in_this_partition(pos)) {
return i;
}
}
return PARTITION_ID_INVALID;
}
// add a partition in a predefined 'lattice' that contains point pos as its llf point
// size is given by config
partition_id_t add_partition(const Vec3& partition_llf) {
assert(config.partition_edge_length != 0);
assert(get_partition_index(partition_llf) == PARTITION_ID_INVALID && "Partition must not exist");
partitions.push_back(Partition(partitions.size(), partition_llf, config, bng_engine, stats));
return partitions.size() - 1;
}
Partition& get_partition(partition_id_t i) {
assert(i < partitions.size());
return partitions[i];
}
const Partition& get_partition(partition_id_t i) const {
assert(i < partitions.size());
return partitions[i];
}
PartitionVector& get_partitions() {
return partitions;
}
// -------------- object id counters --------------
wall_id_t get_next_wall_id() {
wall_id_t res = next_wall_id;
next_wall_id++;
return res;
}
region_id_t get_next_region_id() {
region_id_t res = next_region_id;
next_region_id++;
return res;
}
geometry_object_id_t get_next_geometry_object_id() {
geometry_object_id_t res = next_geometry_object_id;
next_geometry_object_id++;
return res;
}
void print_periodic_stats() const;
void dump(const bool with_geometry = false);
// exports model geometry to Wavefront OBJ format
void export_geometry_to_obj(const std::string& files_prefix) const;
// the export to directory is usually called periodically and the output is used for visualization
void export_data_model_to_dir(const std::string& prefix, const bool only_for_viz = true) const;
void export_data_model(const std::string& file_name, const bool only_for_viz) const;
void to_data_model(Json::Value& root, const bool only_for_viz) const;
// ---------------------- other ----------------------
BNG::SpeciesContainer& get_all_species() { return bng_engine.get_all_species(); }
const BNG::SpeciesContainer& get_all_species() const { return bng_engine.get_all_species(); }
BNG::RxnContainer& get_all_rxns() { return bng_engine.get_all_rxns(); }
const BNG::RxnContainer& get_all_rxns() const { return bng_engine.get_all_rxns(); }
count_buffer_id_t create_dat_count_buffer(
const std::string file_name, const size_t buffer_size, const bool open_for_append = false);
count_buffer_id_t create_gdat_count_buffer(
const std::string file_name, const std::vector<std::string>& column_names,
const size_t buffer_size, const bool open_for_append);
CountBuffer& get_count_buffer(const count_buffer_id_t id) {
assert(id < count_buffers.size());
return count_buffers[id];
}
const CountBuffer& get_count_buffer(const count_buffer_id_t id) const {
assert(id < count_buffers.size());
return count_buffers[id];
}
GeometryObject& get_geometry_object(const geometry_object_id_t id) {
// TODO: there will be multiple places where geom object id and index are mixed
return get_partition(0).get_geometry_object_by_id(id);
}
const GeometryObject& get_geometry_object(const geometry_object_id_t id) const {
// TODO: there will be multiple places where geom object id and index are mixed
return get_partition(0).get_geometry_object_by_id(id);
}
const Region& get_region(const region_id_t id) const {
return get_partition(0).get_region_by_id(id);
}
const Region* find_region_by_name(const std::string& name) const {
return get_partition(0).find_region_by_name(name);
}
static uint64_t determine_output_frequency(uint64_t iterations);
bool check_for_overlapped_walls();
void reset_unimol_rxn_times(const BNG::rxn_rule_id_t rxn_rule_id);
// gives ownership of the event to this World object
void add_unscheduled_count_event(MolOrRxnCountEvent* e) {
unscheduled_count_events.push_back(e);
}
void flush_buffers();
void flush_and_close_buffers();
// prints message, flushes buffers, and terminates
void fatal_error(const std::string& msg);
private:
void check_checkpointing_signal();
uint64_t time_to_iteration(const double time);
void init_fpu();
void init_counted_volumes();
void initialization_to_data_model(Json::Value& mcell_node) const;
void export_data_layout() const;
public:
// single instance for the whole mcell simulator,
// used as constants during simulation
SimulationConfig config;
BNG::BNGEngine bng_engine;
SimulationStats stats;
// owned by API::Model or references a global instance in case of MDL mode
API::Callbacks& callbacks;
mutable Scheduler scheduler; // scheduler might need to do some internal reorganization
std::vector<MolOrRxnCountEvent*> unscheduled_count_events;
uint64_t total_iterations; // number of iterations to simulate - move to Sim config
rng_state rng; // single state for the random number generator
private:
PartitionVector partitions;
CountBufferVector count_buffers;
// periodic check of used memory using timer
MemoryLimitChecker memory_limit_checker;
// global ID counters
wall_id_t next_wall_id;
region_id_t next_region_id;
geometry_object_id_t next_geometry_object_id;
// used by run_n_iterations to know whether the simulation was
// already initialized
bool simulation_initialized;
// set in run_n_iterations to know whether we should report
// final viz and rxn output in end_simulation
bool run_n_iterations_terminated_with_checkpoint;
// used to know whether we already reported final simulation stats
bool simulation_ended;
// buffers can be flushed only once
bool buffers_flushed;
// several variables to report simulation time
std::chrono::time_point<std::chrono::steady_clock> previous_progress_report_time;
rusage sim_start_time;
bool it1_start_time_set;
rusage it1_start_time; // time when 1st iteration started
std::chrono::time_point<std::chrono::steady_clock> previous_buffer_flush_time;
// and to nicely report simulation progress
uint64_t previous_iteration;
// SIGNO_NOT_SIGNALED (-1) if not signaled, supported values are SIGUSR1, SIGUSR2, and SIGALRM
int signaled_checkpoint_signo;
// checkpointing requires model pointer, do not use this for anything else,
// is not nullptr only when a checkpoint is scheduled
API::Model* signaled_checkpoint_model;
};
} // namespace mcell
#endif // SRC4_WORLD_H_
| Unknown |
3D | mcellteam/mcell | src4/grid_position.h | .h | 723 | 31 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#ifndef SRC4_GRID_POSITION_H_
#define SRC4_GRID_POSITION_H_
#include "defines.h"
namespace MCell {
class Partition;
class GridPos;
namespace GridPosition {
Vec2 find_closest_position(const Partition& p, const GridPos& gp1, const GridPos& gp2);
} // namespace GridPosition
} // namespace MCell
#endif // SRC4_GRID_POSITION_H_
| Unknown |
3D | mcellteam/mcell | src4/mcell4_iface_for_mcell3.cpp | .cpp | 1,230 | 45 | /******************************************************************************
*
* Copyright (C) 2020 by
* The Salk Institute for Biological Studies
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "mcell3_world_converter.h"
#include "world.h"
#include "datamodel_defines.h"
// holds global instance of world after conversion
MCell::MCell3WorldConverter g_converter;
bool mcell4_convert_mcell3_volume(volume* s) {
return g_converter.convert(s);
}
bool mcell4_run_simulation(const bool dump_initial_state, const bool dump_with_geometry) {
g_converter.world->init_and_run_simulation(dump_initial_state, dump_with_geometry);
return true;
}
void mcell4_convert_to_data_model(const bool only_for_viz) {
const char* fname;
if (only_for_viz) {
fname = DEFAULT_DATA_MODEL_VIZ_FILENAME;
}
else {
fname = DEFAULT_DATA_MODEL_FILENAME;
}
g_converter.world->export_data_model(fname, only_for_viz);
mcell_log("Datamodel was exported to '%s'.", fname);
}
void mcell4_delete_world() {
g_converter.reset();
}
| C++ |
3D | mcellteam/mcell | src/count_util.h | .h | 2,567 | 68 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
#include "dyngeom_parse_extras.h"
#include "vol_util.h"
int region_listed(struct region_list *rl, struct region *r);
void count_region_update(
struct volume *world,
struct volume_molecule *vm,
struct species *sp,
u_long id,
struct periodic_image *img,
struct region_list *rl,
int direction,
int crossed,
struct vector3 *loc,
double t);
void count_region_border_update(struct volume *world, struct species *sp,
struct hit_data *hd_info, u_long id);
void count_region_from_scratch(struct volume *world,
struct abstract_molecule *am,
struct rxn_pathname *rxpn, int n,
struct vector3 *loc, struct wall *my_wall,
double t, struct periodic_image *periodic_box);
void count_moved_surface_mol(struct volume *world, struct surface_molecule *sm,
struct surface_grid *sg, struct vector2 *loc, int count_hashmask,
struct counter **count_hash, long long *ray_polygon_colls,
struct periodic_image *previous_box);
void fire_count_event(struct volume *world, struct counter *event, int n,
struct vector3 *where, byte what, u_long id);
int place_waypoints(struct volume *world);
int prepare_counters(struct volume *world);
int check_counter_geometry(int count_hashmask, struct counter **count_hash,
byte *place_waypoints_flag);
int expand_object_output(struct output_request *request,
struct geom_object *obj,
struct sym_table_head *reg_sym_table);
int object_has_geometry(struct geom_object *obj);
/* hit data for region borders */
void update_hit_data(struct hit_data **hd_head, struct wall *current,
struct wall *target, struct surface_molecule *sm,
struct vector2 boundary_pos, int direction, int crossed);
int is_object_instantiated(struct sym_entry *entry,
struct geom_object *root_instance);
| Unknown |
3D | mcellteam/mcell | src/mcell_release.h | .h | 3,932 | 85 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
MCELL_STATUS mcell_create_list_release_site(
MCELL_STATE *state, struct geom_object *parent, char *site_name,
struct mcell_species *mol, double *x_pos, double *y_pos, double *z_pos, int n_site,
struct vector3 *diameter, struct geom_object **new_object);
MCELL_STATUS mcell_create_geometrical_release_site(
MCELL_STATE *state, struct geom_object *parent, const char *site_name, int shape,
struct vector3 *position, struct vector3 *diameter,
struct mcell_species *mol, double num, int num_type, double release_prob,
struct release_pattern *rpatp, struct geom_object **new_object);
MCELL_STATUS mcell_start_release_site(MCELL_STATE *state,
struct sym_entry *sym_ptr,
struct geom_object **obj);
MCELL_STATUS mcell_finish_release_site(struct sym_entry *sym_ptr,
struct geom_object **obj);
/* FIXME: some of the functions below should probably not be part of the API
* but the parser needs them right now */
int set_release_site_concentration(struct release_site_obj *rel_site_obj_ptr,
double conc);
MCELL_STATUS
mcell_create_region_release(MCELL_STATE *state, struct geom_object *parent,
struct geom_object *release_on_in, char *site_name,
char *reg_name, struct mcell_species *mol,
double num, int num_type, double rel_prob,
struct release_pattern *rpatp, struct geom_object **new_object);
MCELL_STATUS
mcell_create_region_release_boolean(MCELL_STATE *state, struct geom_object *parent,
char *site_name, struct mcell_species *mol,
double num, int num_type, double rel_prob,
struct release_pattern *rpatp, struct release_evaluator *rel_eval,
struct geom_object **new_object);
struct release_pattern *mcell_create_release_pattern(MCELL_STATE *state, char *name, double delay,
double release_interval, double train_interval,
double train_duration, int number_of_trains);
int mcell_set_release_site_geometry_region(
MCELL_STATE *state, struct release_site_obj *rel_site_obj_ptr,
struct geom_object *objp, struct release_evaluator *re);
int check_release_regions(struct release_evaluator *rel, struct geom_object *parent,
struct geom_object *instance);
int is_release_site_valid(struct release_site_obj *rel_site_obj_ptr);
struct release_evaluator *
new_release_region_expr_term(struct sym_entry *my_sym);
void set_release_site_constant_number(struct release_site_obj *rel_site_obj_ptr,
double num);
void set_release_site_gaussian_number(struct release_site_obj *rel_site_obj_ptr,
double mean, double stdev);
struct release_evaluator *
new_release_region_expr_binary(struct release_evaluator *reL,
struct release_evaluator *reR, int op);
void set_release_site_location(MCELL_STATE *state,
struct release_site_obj *rel_site_obj_ptr,
struct vector3 *location);
struct sym_entry *existing_region(MCELL_STATE *state,
struct sym_entry *obj_symp,
char *region_name);
| Unknown |
3D | mcellteam/mcell | src/mem_util.h | .h | 4,749 | 104 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#ifdef MEM_UTIL_KEEP_STATS
#include <stdio.h>
#include <stdlib.h>
char *mem_util_tracking_strdup(char const *in);
void *mem_util_tracking_malloc(unsigned int size);
void *mem_util_tracking_realloc(void *data, unsigned int size);
void mem_util_tracking_free(void *data);
#undef malloc
#undef free
#undef strdup
#define malloc mem_util_tracking_malloc
#define free mem_util_tracking_free
#define strdup mem_util_tracking_strdup
#define realloc mem_util_tracking_realloc
#endif
char *checked_strdup(char const *s, char const *file, unsigned int line,
char const *desc, int onfailure);
void *checked_malloc(size_t size, char const *file, unsigned int line,
char const *desc, int onfailure);
char *checked_alloc_sprintf(char const *file, unsigned int line, int onfailure,
char const *fmt, ...) PRINTF_FORMAT(4);
struct mem_helper;
void *checked_mem_get(struct mem_helper *mh, char const *file,
unsigned int line, char const *desc, int onfailure);
#define CM_EXIT (1)
#define CHECKED_STRDUP_NODIE(s, desc) \
checked_strdup((s), __FILE__, __LINE__, desc, 0)
#define CHECKED_STRDUP(s, desc) \
checked_strdup((s), __FILE__, __LINE__, desc, CM_EXIT)
#define CHECKED_MALLOC_NODIE(sz, desc) \
checked_malloc((sz), __FILE__, __LINE__, desc, 0)
#define CHECKED_MALLOC(sz, desc) \
checked_malloc((sz), __FILE__, __LINE__, desc, CM_EXIT)
#define CHECKED_MALLOC_STRUCT_NODIE(tp, desc) \
(tp *) checked_malloc(sizeof(tp), __FILE__, __LINE__, desc, 0)
#define CHECKED_MALLOC_STRUCT(tp, desc) \
(tp *) checked_malloc(sizeof(tp), __FILE__, __LINE__, desc, CM_EXIT)
#define CHECKED_MALLOC_ARRAY_NODIE(tp, num, desc) \
(tp *) checked_malloc((num) * sizeof(tp), __FILE__, __LINE__, desc, 0)
#define CHECKED_MALLOC_ARRAY(tp, num, desc) \
(tp *) checked_malloc((num) * sizeof(tp), __FILE__, __LINE__, desc, CM_EXIT)
#define CHECKED_MEM_GET_NODIE(mh, desc) \
checked_mem_get((mh), __FILE__, __LINE__, desc, 0)
#define CHECKED_MEM_GET(mh, desc) \
checked_mem_get((mh), __FILE__, __LINE__, desc, CM_EXIT)
#define CHECKED_SPRINTF_NODIE(fmt, ...) \
checked_alloc_sprintf(__FILE__, __LINE__, 0, fmt, ##__VA_ARGS__)
#define CHECKED_SPRINTF(fmt, ...) \
checked_alloc_sprintf(__FILE__, __LINE__, CM_EXIT, fmt, ##__VA_ARGS__)
/* Everything allocated by a mem_helper must start with a next pointer
as if it were derived from an abstract_list */
struct abstract_list {
struct abstract_list *next;
};
/* Data structure to allocate blocks of memory for a specific size of struct */
struct mem_helper {
int buf_len; /* Number of elements to allocate at once */
int buf_index; /* Index of the next unused element in the array */
size_t record_size; /* Size of the element to allocate */
unsigned char *heap_array; /* Block of memory for elements */
struct abstract_list *defunct; /* Linked list of elements that may be reused
for next memory request */
struct mem_helper *next_helper; /* Next (fully-used) mem_helper */
#ifdef MEM_UTIL_KEEP_STATS
struct mem_stats *stats;
#endif
};
#ifdef MEM_UTIL_KEEP_STATS
void mem_dump_stats(FILE *out);
#else
#define mem_dump_stats(out) \
do { /* do nothing */ \
} while (0)
#endif
struct mem_helper *create_mem_named(size_t size, int length, char const *name);
struct mem_helper *create_mem(size_t size, int length);
void *mem_get(struct mem_helper *mh);
void mem_put(struct mem_helper *mh, void *defunct);
void mem_put_list(struct mem_helper *mh, void *defunct);
void delete_mem(struct mem_helper *mh);
#define stack_nonempty(sh) ((sh)->index > 0 || (sh)->next != NULL)
| Unknown |
3D | mcellteam/mcell | src/init.c | .c | 264,480 | 6,806 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <time.h>
#ifndef _MSC_VER
#include <unistd.h>
#include <sys/types.h>
#include <sys/resource.h>
#endif
#include <vector>
#include "version_info.h"
#include "logging.h"
#include "rng.h"
#include "mcell_structs.h"
#include "sym_table.h"
#include "count_util.h"
#include "vol_util.h"
#include "wall_util.h"
#include "grid_util.h"
#include "viz_output.h"
#include "react.h"
#include "react_output.h"
#include "chkpt.h"
#include "init.h"
#include "mdlparse_aux.h"
#include "mcell_objects.h"
#include "dyngeom.h"
#include "dyngeom_parse_extras.h"
#include "triangle_overlap.h"
#include "debug_config.h"
#define MESH_DISTINCTIVE EPS_C
struct reschedule_helper {
struct reschedule_helper *next;
struct release_event_queue *req;
};
/* Initialize the visualization output (frame_data_lists). */
static int init_viz_output(struct volume *world);
static int compute_bb(struct volume *world, struct geom_object *objp,
double (*im)[4]);
static int compute_bb_release_site(struct volume *world, struct geom_object *objp,
double (*im)[4]);
static int compute_bb_polygon_object(struct volume *world, struct geom_object *objp,
double (*im)[4]);
static int init_species_defaults(struct volume *world);
static int init_regions_helper(struct volume *world);
static struct clamp_data* find_clamped_object_in_list(struct clamp_data *cdp,
struct geom_object *obj);
#define MICROSEC_PER_YEAR 365.25 * 86400.0 * 1e6
/* Sets default notification values */
int init_notifications(struct volume *world) {
if (!(world->notify = CHECKED_MALLOC_STRUCT_NODIE(struct notifications,
"notification states"))) {
return 1;
}
/* Notifications */
if (world->quiet_flag) {
world->notify->progress_report = NOTIFY_NONE;
world->notify->diffusion_constants = NOTIFY_NONE;
world->notify->reaction_probabilities = NOTIFY_NONE;
world->notify->time_varying_reactions = NOTIFY_NONE;
world->notify->reaction_prob_notify = 0.0;
world->notify->partition_location = NOTIFY_NONE;
world->notify->box_triangulation = NOTIFY_NONE;
world->notify->iteration_report = NOTIFY_NONE;
world->notify->custom_iteration_value = 0;
world->notify->release_events = NOTIFY_NONE;
world->notify->file_writes = NOTIFY_NONE;
world->notify->final_summary = NOTIFY_NONE;
world->notify->throughput_report = NOTIFY_NONE;
world->notify->checkpoint_report = NOTIFY_NONE;
world->notify->reaction_output_report = NOTIFY_NONE;
world->notify->volume_output_report = NOTIFY_NONE;
world->notify->viz_output_report = NOTIFY_NONE;
world->notify->molecule_collision_report = NOTIFY_NONE;
} else {
world->notify->progress_report = NOTIFY_FULL;
world->notify->diffusion_constants = NOTIFY_BRIEF;
world->notify->reaction_probabilities = NOTIFY_FULL;
world->notify->time_varying_reactions = NOTIFY_FULL;
world->notify->reaction_prob_notify = 0.0;
world->notify->partition_location = NOTIFY_NONE;
world->notify->box_triangulation = NOTIFY_NONE;
world->notify->iteration_report = NOTIFY_FULL;
world->notify->custom_iteration_value = 0;
world->notify->release_events = NOTIFY_FULL;
world->notify->file_writes = NOTIFY_NONE;
world->notify->final_summary = NOTIFY_FULL;
world->notify->throughput_report = NOTIFY_FULL;
world->notify->checkpoint_report = NOTIFY_FULL;
world->notify->reaction_output_report = NOTIFY_NONE;
world->notify->volume_output_report = NOTIFY_NONE;
world->notify->viz_output_report = NOTIFY_NONE;
world->notify->molecule_collision_report = NOTIFY_NONE;
}
/* Warnings */
world->notify->neg_diffusion = WARN_WARN;
world->notify->neg_reaction = WARN_WARN;
world->notify->high_reaction_prob = WARN_COPE;
world->notify->reaction_prob_warn = 1.0;
world->notify->close_partitions = WARN_WARN;
world->notify->degenerate_polys = WARN_WARN;
world->notify->overwritten_file = WARN_COPE;
world->notify->short_lifetime = WARN_WARN;
world->notify->short_lifetime_value = 50;
world->notify->missed_reactions = WARN_WARN;
world->notify->missed_reaction_value = 0.001;
world->notify->missed_surf_orient = WARN_ERROR;
world->notify->useless_vol_orient = WARN_WARN;
world->notify->mol_placement_failure = WARN_WARN;
world->notify->invalid_output_step_time = WARN_WARN;
world->notify->large_molecular_displacement = WARN_WARN;
world->notify->add_remove_mesh_warning = WARN_WARN;
if (world->log_freq != 0 && world->log_freq != ULONG_MAX) /* User set this */
{
world->notify->custom_iteration_value = world->log_freq;
}
return 0;
}
/*
* Initialize the volume data output. This will create a scheduler for the
* volume data, and add volume data output items to the scheduler.
*/
static void init_volume_data_output(struct volume *wrld) {
struct volume_output_item *vo, *vonext;
wrld->volume_output_scheduler = create_scheduler(
1.0, 100.0, 100, wrld->simulation_start_seconds / wrld->time_unit);
if (wrld->volume_output_scheduler == NULL)
mcell_allocfailed("Failed to create scheduler for volume output data.");
double r_time_unit = 1.0 / wrld->time_unit;
for (vo = wrld->volume_output_head; vo != NULL; vo = vonext) {
vonext = vo->next; /* schedule_add overwrites 'next' */
if (vo->timer_type == OUTPUT_BY_STEP) {
if (wrld->chkpt_seq_num == 1)
vo->t = 0.0;
else {
/* Get step time in internal units, find next scheduled output time */
double f = vo->step_time * r_time_unit;
vo->t = f * ceil(wrld->volume_output_scheduler->now / f);
}
} else if (vo->num_times > 0) {
/* Set time scaling factor depending on output type */
double time_scale = 0.0;
if (vo->timer_type == OUTPUT_BY_ITERATION_LIST)
time_scale = 1.0;
else
time_scale = r_time_unit;
/* Find the time of next output */
if (wrld->chkpt_seq_num == 1) {
vo->next_time = vo->times;
vo->t = time_scale * *vo->next_time;
} else /* Scan forward to find first output after checkpoint time */
{
int idx = bisect_high(vo->times, vo->num_times,
wrld->volume_output_scheduler->now / time_scale);
/* If we've already passed the last time for this one, skip it! */
if (idx < 0 || idx >= vo->num_times)
continue;
if (wrld->volume_output_scheduler->now / time_scale > vo->times[idx])
continue;
vo->t = vo->times[idx] * time_scale;
vo->next_time = vo->times + idx;
}
/* Advance the next_time pointer */
++vo->next_time;
}
if (schedule_add(wrld->volume_output_scheduler, vo))
mcell_allocfailed("Failed to add item to schedule for volume output.");
}
}
/***********************************************************************
*
* initialize the state of variables in world
*
***********************************************************************/
int init_variables(struct volume *world) {
world->dump_level = 0;
world->viz_options = 0;
world->bond_angle = 0.0;
world->t_start = time(NULL);
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("MCell initializing simulation...");
// XXX: This is in the wrong place here and should be moved
// to a separate function perhaps
install_emergency_output_hooks(world);
emergency_output_hook_enabled = 0;
world->curr_file = world->mdl_infile_name;
world->chkpt_iterations = 0;
world->last_checkpoint_iteration = 0;
world->chkpt_seq_num = 0;
world->keep_chkpts = 0;
world->last_timing_time = { 0, 0 };
world->last_timing_iteration = 0;
world->chkpt_flag = 0;
world->disable_polygon_objects = 0;
world->viz_blocks = NULL;
world->ray_voxel_tests = 0;
world->ray_polygon_tests = 0;
world->ray_polygon_colls = 0;
world->dyngeom_molec_displacements = 0;
world->vol_vol_colls = 0;
world->vol_surf_colls = 0;
world->surf_surf_colls = 0;
world->vol_wall_colls = 0;
world->vol_vol_vol_colls = 0;
world->vol_vol_surf_colls = 0;
world->vol_surf_surf_colls = 0;
world->surf_surf_surf_colls = 0;
world->diffuse_3d_calls = 0;
world->chkpt_start_time_seconds = 0;
world->chkpt_byte_order_mismatch = 0;
world->diffusion_number = 0;
world->diffusion_cumtime = 0.0;
world->current_iterations = 0;
world->elapsed_time = 0;
world->time_unit = 0;
world->time_step_max = 0;
world->start_iterations = 0;
world->current_time_seconds = 0;
world->simulation_start_seconds = 0;
world->grid_density = 10000;
world->r_length_unit = sqrt(world->grid_density);
world->length_unit = 1.0 / world->r_length_unit;
world->rx_radius_3d = 0;
world->radial_directions = 16384;
world->radial_subdivisions = 1024;
world->fully_random = 0;
world->num_directions = world->radial_directions;
world->r_step = NULL;
world->r_step_surface = NULL;
world->r_step_release = NULL;
world->d_step = NULL;
world->dissociation_index = DISSOCIATION_MAX;
world->place_waypoints_flag = 0;
world->periodic_traditional = false;
world->count_scheduler = NULL;
world->volume_output_scheduler = NULL;
world->storage_head = NULL;
world->storage_allocator = NULL;
world->x_partitions = NULL;
world->y_partitions = NULL;
world->z_partitions = NULL;
world->x_fineparts = NULL;
world->y_fineparts = NULL;
world->z_fineparts = NULL;
world->n_fineparts = 0;
world->mem_part_x = 14;
world->mem_part_y = 14;
world->mem_part_z = 14;
world->mem_part_pool = 0;
world->all_vertices = NULL;
world->walls_using_vertex = NULL;
world->periodic_box_obj = NULL;
world->use_expanded_list = 1;
world->randomize_smol_pos = 1;
world->vacancy_search_dist2 = 0.1;
world->surface_reversibility = 0;
world->volume_reversibility = 0;
world->n_reactions = 0;
world->current_mol_id = 0;
world->dynamic_geometry_molecule_placement = 0;
world->rxn_flags.vol_vol_reaction_flag = 0;
world->rxn_flags.vol_surf_reaction_flag = 0;
world->rxn_flags.surf_surf_reaction_flag = 0;
world->rxn_flags.vol_wall_reaction_flag = 0;
world->rxn_flags.vol_vol_vol_reaction_flag = 0;
world->rxn_flags.vol_vol_surf_reaction_flag = 0;
world->rxn_flags.vol_surf_surf_reaction_flag = 0;
world->rxn_flags.surf_surf_surf_reaction_flag = 0;
world->create_shared_walls_info_flag = 0;
world->reaction_prob_limit_flag = 0;
world->mcell_version = mcell_version;
world->clamp_list = NULL;
//NFSim variables
world->n_NFSimSpecies = 0;
world->n_NFSimReactions = 0;
world->n_NFSimPReactions = 0;
world->dynamic_geometry_filename = NULL;
// mcell4
world->partitions_initialized = false;
return 0;
}
/***********************************************************************
*
* initialize the main data structures in world
*
***********************************************************************/
int init_data_structures(struct volume *world) {
int i;
if (!(world->rng = CHECKED_MALLOC_STRUCT_NODIE(
struct rng_state, "random number generator state"))) {
return 1;
}
if (world->seed_seq < 1 || world->seed_seq > INT_MAX)
mcell_error(
"Random sequence number must be in the range 1 to 2^31-1 [2147483647]");
rng_init(world->rng, world->seed_seq);
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("MCell[%d]: random sequence %d", world->procnum, world->seed_seq);
world->count_hashmask = COUNT_HASHMASK;
if (!(world->count_hash =
CHECKED_MALLOC_ARRAY(struct counter *, (world->count_hashmask + 1),
"counter hash table"))) {
return 1;
}
for (i = 0; i <= world->count_hashmask; i++)
world->count_hash[i] = NULL;
world->oexpr_mem = create_mem_named(sizeof(struct output_expression), 128,
"output expression");
if (world->oexpr_mem == NULL) {
mcell_allocfailed_nodie("Failed to create memory pool for reaction data "
"output expressions.");
return 1;
}
world->outp_request_mem =
create_mem_named(sizeof(struct output_request), 64, "output request");
if (world->outp_request_mem == NULL) {
mcell_allocfailed_nodie("Failed to create memory pool for reaction data "
"output commands.");
return 1;
}
world->counter_mem = create_mem_named(sizeof(struct counter), 32, "counter");
if (world->counter_mem == NULL) {
mcell_allocfailed_nodie("Failed to create memory pool for reaction and "
"molecule counts.");
return 1;
}
world->trig_request_mem =
create_mem_named(sizeof(struct trigger_request), 32, "trigger request");
if (world->trig_request_mem == NULL) {
mcell_allocfailed_nodie("Failed to create memory pool for reaction and "
"molecule output triggers.");
return 1;
}
world->magic_mem = create_mem_named(sizeof(struct magic_list), 1024,
"reaction-triggered release");
if (world->magic_mem == NULL) {
mcell_allocfailed_nodie("Failed to create memory pool for "
"reaction-triggered release lists.");
return 1;
}
world->dynamic_geometry_events_mem = create_mem_named(
sizeof(struct dg_time_filename), 100, "dynamic geometry time filename");
if (world->dynamic_geometry_events_mem == NULL)
return 1;
if ((world->fstream_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie(
"Failed to initialize symbol table for file streams.");
return 1;
}
if ((world->mol_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie("Failed to initialize symbol table for molecules.");
return 1;
}
if ((world->mol_ss_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie("Failed to initialize symbol table for spatially structured molecules.");
return 1;
}
if ((world->rxn_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie("Failed to initialize symbol table for reactions.");
return 1;
}
if ((world->obj_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie("Failed to initialize symbol table for objects.");
return 1;
}
if ((world->reg_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie("Failed to initialize symbol table for regions.");
return 1;
}
if ((world->rpat_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie(
"Failed to initialize symbol table for release patterns.");
return 1;
}
if ((world->rxpn_sym_table = init_symtab(1024)) == NULL) {
mcell_allocfailed_nodie(
"Failed to initialize symbol table for reaction pathways.");
return 1;
}
struct sym_entry *sym;
if ((sym = store_sym("WORLD_OBJ", OBJ, world->obj_sym_table, NULL)) == NULL) {
mcell_allocfailed_nodie(
"Failed to store the world root object in the object symbol table.");
return 1;
}
world->root_object = (struct geom_object *)sym->value;
world->root_object->object_type = META_OBJ;
if (!(world->root_object->last_name = CHECKED_STRDUP_NODIE("", NULL))) {
return 1;
}
if ((sym = store_sym("WORLD_INSTANCE", OBJ, world->obj_sym_table, NULL)) ==
NULL) {
mcell_allocfailed_nodie(
"Failed to store the world root instance in the object symbol table.");
return 1;
}
world->root_instance = (struct geom_object *)sym->value;
world->root_instance->object_type = META_OBJ;
if (!(world->root_instance->last_name = CHECKED_STRDUP("", NULL))) {
return 1;
}
if ((sym = store_sym("DEFAULT_RELEASE_PATTERN", RPAT, world->rpat_sym_table,
NULL)) == NULL) {
mcell_allocfailed_nodie("Failed to store the default release pattern in "
"the release patterns symbol table.");
return 1;
}
world->default_release_pattern = (struct release_pattern *)sym->value;
world->default_release_pattern->delay = 0;
world->default_release_pattern->release_interval = FOREVER;
world->default_release_pattern->train_interval = FOREVER;
world->default_release_pattern->train_duration = FOREVER;
world->default_release_pattern->number_of_trains = 1;
if ((sym = store_sym("ALL_VOLUME_MOLECULES", MOL, world->mol_sym_table,
NULL)) == NULL) {
mcell_allocfailed_nodie(
"Failed to store all volume molecules in the molecule symbol table.");
return 1;
}
world->all_volume_mols = (struct species *)sym->value;
if ((sym = store_sym("ALL_SURFACE_MOLECULES", MOL, world->mol_sym_table,
NULL)) == NULL) {
mcell_allocfailed_nodie(
"Failed to store the surface molecules in the molecule symbol table.");
return 1;
}
world->all_surface_mols = (struct species *)sym->value;
if ((sym = store_sym("ALL_MOLECULES", MOL, world->mol_sym_table, NULL)) ==
NULL) {
mcell_allocfailed_nodie(
"Failed to store all molecules in the molecule symbol table.");
return 1;
}
world->all_mols = (struct species *)sym->value;
world->volume_output_head = NULL;
world->output_block_head = NULL;
world->output_request_head = NULL;
world->dynamic_geometry_head = NULL;
world->releaser = create_scheduler(1.0, 100.0, 100, 0.0);
if (world->releaser == NULL) {
mcell_allocfailed_nodie("Failed to create release scheduler.");
return 1;
}
init_dynamic_geometry(world);
return 0;
}
/***********************************************************************
*
* initialize the models' species table
*
***********************************************************************/
int init_species(struct volume *world) {
int reactants_3D_present = 0; /* flag to check whether there are 3D reactants
(participants in the reactions
between 3D molecules) in the simulation */
/* Set up the array of species */
if (init_species_defaults(world)) {
mcell_error_nodie("Unknown error while initializing species table.");
return 0;
}
no_printf("Done setting up species.\n");
/* Create linked lists of volume and surface molecules names */
struct name_list *vol_species_name_list = NULL;
struct name_list *surf_species_name_list = NULL;
if (world->notify->reaction_probabilities == NOTIFY_FULL) {
create_name_lists_of_volume_and_surface_mols(world, &vol_species_name_list,
&surf_species_name_list);
}
for (int i = 0; i < world->n_species; i++) {
struct species *sp = world->species_list[i];
if (sp->flags & IS_SURFACE) {
check_for_conflicts_in_surface_class(world, sp);
if (world->notify->reaction_probabilities == NOTIFY_FULL) {
publish_special_reactions_report(sp, vol_species_name_list,
surf_species_name_list,
world->n_species, world->species_list);
}
}
}
/* Memory deallocate linked lists of volume molecules names and surface
molecules names */
if (vol_species_name_list != NULL)
remove_molecules_name_list(&vol_species_name_list);
if (surf_species_name_list != NULL)
remove_molecules_name_list(&surf_species_name_list);
/* If there are no 3D molecules-reactants in the simulation
set up the "use_expanded_list" flag to zero. */
for (int i = 0; i < world->n_species; i++) {
struct species *sp = world->species_list[i];
if (sp == world->all_mols)
continue;
if (sp == world->all_volume_mols)
continue;
if (sp == world->all_surface_mols)
continue;
if (sp->flags & ON_GRID)
continue;
if (sp->flags & IS_SURFACE)
continue;
if ((sp->flags & (CAN_VOLVOL | CAN_VOLVOLVOL)) != 0) {
reactants_3D_present = 1;
break;
}
}
if (reactants_3D_present == 0) {
world->use_expanded_list = 0;
}
return 0;
}
/***********************************************************************
*
* initialize the models' vertices and walls
*
***********************************************************************/
int init_vertices_walls(struct volume *world) {
struct storage_list *sl;
int num_storages = 0; /* number of storages in the world */
int *num_vertices_this_storage; /* array of vertex counts belonging to each
storage */
for (sl = world->storage_head; sl != NULL; sl = sl->next) {
num_storages++;
}
/* Allocate array of counts (note: the ordering of this array follows the
* ordering of the linked list "world->storage_list") */
if (!(num_vertices_this_storage = CHECKED_MALLOC_ARRAY_NODIE(
int, num_storages, "array of vertex counts per storage"))) {
return 1;
}
memset(num_vertices_this_storage, 0, sizeof(int) * num_storages);
double tm[4][4];
init_matrix(tm);
/* Accumulate vertex counts and rescale each vertex coordinates if needed */
if (accumulate_vertex_counts_per_storage(world, world->root_instance,
num_vertices_this_storage, tm)) {
mcell_error_nodie("Error while accumulating vertex counts per storage.");
return 1;
}
/* Cumulate the vertex count */
for (int kk = 1; kk < num_storages; ++kk) {
num_vertices_this_storage[kk] += num_vertices_this_storage[kk - 1];
}
/* Allocate the global "all_vertices" array */
if (!(world->all_vertices = CHECKED_MALLOC_ARRAY_NODIE(
struct vector3, num_vertices_this_storage[num_storages - 1],
"array of all vertices in the world"))) {
return 1;
}
/* Allocate the global "walls_using_vertex" array */
if (world->create_shared_walls_info_flag) {
if (!(world->walls_using_vertex = CHECKED_MALLOC_ARRAY_NODIE(
struct wall_list *, num_vertices_this_storage[num_storages - 1],
"wall list pointers"))) {
return 1;
}
for (int kk = 0; kk < num_vertices_this_storage[num_storages - 1]; kk++) {
world->walls_using_vertex[kk] = NULL;
}
}
init_matrix(tm);
/* Copy vertices into the global array "world->all_vertices"
and fill "objp->vertices" for each object in the world */
if (fill_world_vertices_array(world, world->root_instance,
num_vertices_this_storage, tm))
return 1;
/* free memory */
free(num_vertices_this_storage);
init_matrix(tm);
/* Instantiate all objects */
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Instantiating objects...");
if (instance_obj(world, world->root_instance, tm))
return 1;
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Creating walls...");
if (distribute_world(world)) {
mcell_error_nodie("Unknown error while distributing geometry "
"among partitions.");
return 1;
}
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Creating edges...");
if (sharpen_world(world)) {
mcell_error_nodie("Unknown error while adding edges to geometry.");
return 1;
}
return 0;
}
/***********************************************************************
*
* initialize the models' regions
*
***********************************************************************/
int init_regions(struct volume *world) {
if (prepare_counters(world)) {
mcell_error_nodie(
"Unknown error while preparing counters for reaction data output.");
return 1;
}
if (init_regions_helper(world)) {
mcell_error_nodie("Unknown error while initializing object regions.");
return 1;
}
if (check_counter_geometry(world->count_hashmask, world->count_hash,
&world->place_waypoints_flag)) {
mcell_error_nodie(
"Unknown error while validating geometry of counting regions.");
return 1;
}
/* flags that tell whether there are regions set with surface classes
that contain ALL_MOLECULES or ALL_SURFACE_MOLECULES keywords.*/
int all_mols_region_present = 0, all_surf_mols_region_present = 0;
struct species *all_mols_sp = get_species_by_name(
"ALL_MOLECULES", world->n_species, world->species_list);
struct species *all_surf_mols_sp = get_species_by_name(
"ALL_SURFACE_MOLECULES", world->n_species, world->species_list);
if ((all_mols_sp != NULL) && (all_mols_sp->flags & REGION_PRESENT)) {
all_mols_region_present = 1;
}
if ((all_surf_mols_sp != NULL) &&
(all_surf_mols_sp->flags & REGION_PRESENT)) {
all_surf_mols_region_present = 1;
}
/* if surface molecules are defined as part of SURFACE_CLASS
definitions but there are no regions with this SURFACE_CLASS
in the model, then to speed up model simulation remove
the flag CAN_REGION_BORDER from the surface molecule */
if ((!all_mols_region_present) && (!all_surf_mols_region_present)) {
for (int i = 0; i < world->n_species; i++) {
struct species *sp = world->species_list[i];
if (sp->flags & ON_GRID) {
if ((sp->flags & CAN_REGION_BORDER) &&
((sp->flags & REGION_PRESENT) == 0)) {
sp->flags &= ~CAN_REGION_BORDER;
}
}
}
}
return 0;
}
/**********************************************************************
*
* initialize the hash which provides a mapping from the name of
* count statments (currently identical to the name of the output
* files) to the underlying output_block data structure containing
* the counts.
*
**********************************************************************/
int init_counter_name_hash(struct sym_table_head **counter_by_name,
struct output_block *output_block_head) {
*counter_by_name = init_symtab(2048);
if (*counter_by_name == NULL) {
mcell_log("error creating count symbol table");
return 1;
}
// insert count data
for (struct output_block *out_block = output_block_head;
out_block != NULL; out_block = out_block->next) {
for (struct output_set *set = out_block->data_set_head; set != NULL;
set = set->next) {
store_sym(set->outfile_name, COUNT_OBJ_PTR, *counter_by_name, set);
}
}
return 0;
}
/***********************************************************************
*
* load the model checkpoint data
* when only_time_and_iter is true, only time and iteration is read
*
***********************************************************************/
int load_checkpoint(struct volume *world, bool only_time_and_iter) {
FILE *chkpt_infs = NULL;
if ((chkpt_infs = fopen(world->chkpt_infile, "rb")) == NULL) {
world->chkpt_seq_num = 1;
} else {
mcell_log("Reading from checkpoint file '%s'.", world->chkpt_infile);
if (read_chkpt(world, chkpt_infs, only_time_and_iter)) {
mcell_error_nodie("Failed to read checkpoint file '%s'.",
world->chkpt_infile);
fclose(chkpt_infs);
return 1;
}
fclose(chkpt_infs);
}
return 0;
}
/***********************************************************************
*
* initialize the model's viz data output
*
***********************************************************************/
int init_viz_data(struct volume *world) {
/* Initialize the frame data for the visualization and reaction output. */
if (init_viz_output(world)) {
mcell_error_nodie("Unknown error while initializing VIZ output.");
return 1;
}
/* Initialize the volume output */
init_volume_data_output(world);
return 0;
}
/***********************************************************************
*
* initialize the model's reaction data output
*
***********************************************************************/
int init_reaction_data(struct volume *world) {
struct output_block *obp, *obpn;
struct output_set *set;
double f;
world->count_scheduler = create_scheduler(1.0, 100.0, 100, world->start_iterations);
if (world->count_scheduler == NULL) {
mcell_allocfailed_nodie(
"Failed to create scheduler for reaction data output.");
return 1;
}
/* Schedule the reaction data output events */
obp = world->output_block_head;
while (obp != NULL) {
obpn = obp->next; /* Save this--will be lost when we schedule obp */
if (obp->timer_type == OUTPUT_BY_STEP) {
if (world->chkpt_seq_num == 1)
obp->t = 0.0;
else {
double stepInt = obp->step_time/world->time_unit; /* Step time (internal units) */
double start = world->count_scheduler->now;
start += stepInt - fmod(start, stepInt);
obp->t = start;
}
} else if (obp->time_now == NULL) /* When would this be non-NULL?? */
{
/* Set time scaling factor depending on output type */
if (obp->timer_type == OUTPUT_BY_ITERATION_LIST)
f = 1.0;
else
f = 1.0 / world->time_unit;
/* Find the time of next output */
if (world->chkpt_seq_num == 1) {
obp->time_now = obp->time_list_head;
obp->t = f * obp->time_now->value;
} else /* Scan forward to find first output after checkpoint time */
{
for (obp->time_now = obp->time_list_head; obp->time_now != NULL;
obp->time_now = obp->time_now->next) {
if (obp->timer_type == OUTPUT_BY_ITERATION_LIST) {
obp->t = f * obp->time_now->value;
if (!(obp->t < world->iterations + 1 &&
obp->t <= world->count_scheduler->now))
break;
} else if (obp->timer_type == OUTPUT_BY_TIME_LIST) {
if (obp->time_now->value > world->simulation_start_seconds) {
obp->t = world->count_scheduler->now +
(obp->time_now->value - world->simulation_start_seconds) /
world->time_unit;
break;
}
}
}
}
}
if (!world->use_mcell4) { // do not clean mcell3 output files in mcell4 mode
for (set = obp->data_set_head; set != NULL; set = set->next) {
if (set->file_flags == FILE_SUBSTITUTE) {
if (world->chkpt_seq_num == 1) {
FILE *file = fopen(set->outfile_name, "w");
if (file == NULL) {
mcell_perror_nodie(errno, "Failed to open reaction data output "
"file '%s' for writing",
set->outfile_name);
return 1;
}
fclose(file);
} else if (obp->timer_type == OUTPUT_BY_ITERATION_LIST) {
if (obp->time_now == NULL)
continue;
if (truncate_output_file(set->outfile_name, obp->t)) {
mcell_error_nodie("Failed to prepare reaction data output file "
"'%s' to receive output.",
set->outfile_name);
return 1;
}
} else if (obp->timer_type == OUTPUT_BY_TIME_LIST) {
if (obp->time_now == NULL)
continue;
if (truncate_output_file(set->outfile_name,
obp->t * world->time_unit)) {
mcell_error_nodie("Failed to prepare reaction data output file "
"'%s' to receive output.",
set->outfile_name);
return 1;
}
} else {
/* we need to truncate up until the start of the new checkpoint
* simulation plus a single TIMESTEP */
double startTime =
world->chkpt_start_time_seconds + world->time_unit;
if (truncate_output_file(set->outfile_name, startTime)) {
mcell_error_nodie("Failed to prepare reaction data output file "
"'%s' to receive output.",
set->outfile_name);
return 1;
}
}
}
}
}
if (schedule_add(world->count_scheduler, obp)) {
mcell_allocfailed_nodie(
"Failed to add reaction data output item to scheduler.");
return 1;
}
obp = obpn;
}
return 0;
}
/***********************************************************************
*
* initialize the model's timers
*
***********************************************************************/
int init_timers(struct volume *world) {
struct rusage init_time;
getrusage(RUSAGE_SELF, &init_time);
world->u_init_time.tv_sec = init_time.ru_utime.tv_sec;
world->u_init_time.tv_usec = init_time.ru_utime.tv_usec;
world->s_init_time.tv_sec = init_time.ru_stime.tv_sec;
world->s_init_time.tv_usec = init_time.ru_stime.tv_usec;
no_printf("Done initializing simulation\n");
return 0;
}
/***********************************************************************
*
* initialize the model's checkpoint state
*
***********************************************************************/
int init_checkpoint_state(struct volume *world, long long *exec_iterations) {
if (world->notify->checkpoint_report != NOTIFY_NONE)
mcell_log("MCell: checkpoint sequence number %d begins at elapsed "
"time %1.15g seconds",
world->chkpt_seq_num, world->chkpt_start_time_seconds);
if (world->iterations < world->start_iterations) {
mcell_error_nodie("Start time after checkpoint %lld is greater than "
"total number of iterations specified %lld.",
world->start_iterations, world->iterations);
return 1;
}
if (world->chkpt_iterations &&
(world->iterations - world->start_iterations) < world->chkpt_iterations) {
world->chkpt_iterations = world->iterations - world->start_iterations;
}
if (world->chkpt_iterations)
*exec_iterations = world->chkpt_iterations;
else if (world->chkpt_infile)
*exec_iterations = world->iterations - world->start_iterations;
else
*exec_iterations = world->iterations;
if (*exec_iterations < 0) {
mcell_error_nodie(
"Number of iterations to execute is zero or negative. "
"Please verify ITERATIONS and/or CHECKPOINT_ITERATIONS commands.");
return 1;
}
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log(
"MCell: executing %lld iterations starting at iteration number %lld.",
*exec_iterations, world->start_iterations);
return 0;
}
/*****************************************************************************
*
* reschedule_release_events reschedules release events during restarts
* from a checkpoint.
*
* During parse time and initialization, release events (e.g. via release
* patterns combined with a delay) are scheduled based on the assumption that
* the timestep throughout the simulation was consistent and identical to the
* one in the parsed mdl file. This assumption may be wrong for restarts from
* a checkpoint in which the timestep was changed with respect to previous runs
* thus resulting in release events being scheduled at a wrong internal time.
* The current function computes the proper internal release time based on
* the start time of the checkpoint and the current iteration number and then
* reschedules all future events accordingly.
*
* This function returns 0 on success and 1 otherwise.
******************************************************************************/
int reschedule_release_events(struct volume *world) {
struct reschedule_helper *helper = NULL;
for (struct schedule_helper *sh = world->releaser; sh != NULL; sh = sh->next_scale) {
for (int i = -1; i < sh->buf_len; i++) {
for (struct abstract_element *ae = (i == -1) ? sh->current : sh->circ_buf_head[i];
ae != NULL; ae = ae->next) {
struct release_event_queue *req = (struct release_event_queue *)ae;
struct reschedule_helper *tmp =
CHECKED_MALLOC_STRUCT(struct reschedule_helper,
"Error creating reschedule helper");
if (helper == NULL) {
tmp->next = NULL;
} else {
tmp->next = helper;
}
tmp->req = req;
helper = tmp;
}
}
}
struct reschedule_helper *rh = helper;
while (rh != NULL) {
struct release_event_queue *req = rh->req;
rh = rh->next;
// adjust event time
double sched_time = req->event_time * world->time_unit;
double real_sched_time = convert_seconds_to_iterations(
world->start_iterations, world->time_unit,
world->chkpt_start_time_seconds, sched_time);
// adjust time of start of train
double train_time = req->train_high_time * world->time_unit;
req->train_high_time = convert_seconds_to_iterations(
world->start_iterations, world->time_unit,
world->chkpt_start_time_seconds, train_time);
schedule_reschedule(world->releaser, req, real_sched_time);
}
while (helper != NULL) {
rh = helper->next;
free(helper);
helper = rh;
}
return 0;
}
/*************************************************************************
Mark all molecule objects for inclusion in the specified viz output block.
In: vizblk: the viz output block in which to include the object
viz_state: the visualization state desired
Out: No return value. vizblk is updated.
*************************************************************************/
static void set_viz_all_molecules(struct volume *world,
struct viz_output_block *vizblk,
int viz_state) {
for (int i = 0; i < world->n_species; i++) {
struct species *sp = world->species_list[i];
if (sp->flags & IS_SURFACE)
continue;
if (sp == world->all_mols)
continue;
if (sp == world->all_volume_mols)
continue;
if (sp == world->all_surface_mols)
continue;
if (vizblk->species_viz_states[i] != EXCLUDE_OBJ)
continue;
/* set viz_state to INCLUDE_OBJ for the molecule we want to visualize
but will not assign state value */
vizblk->species_viz_states[i] = viz_state;
}
}
/*************************************************************************
Initialize the species state array for a given viz output block.
In: vizblk: the viz output block whose species table to update
Out: vizblk is updated
*************************************************************************/
static int init_viz_species_states(int n_species,
struct viz_output_block *vizblk) {
vizblk->species_viz_states =
CHECKED_MALLOC_ARRAY(int, n_species, "species viz states array");
if (vizblk->species_viz_states == NULL)
return 1;
for (int i = 0; i < n_species; ++i)
vizblk->species_viz_states[i] = EXCLUDE_OBJ;
int n_entries = vizblk->parser_species_viz_states.num_items;
int n_bins = vizblk->parser_species_viz_states.table_size;
for (int i = 0; n_entries > 0 && i < n_bins; ++i) {
struct species *specp =
(struct species *)(vizblk->parser_species_viz_states.keys[i]);
if (specp != NULL) {
int viz_state =
(int)(intptr_t)vizblk->parser_species_viz_states.values[i];
vizblk->species_viz_states[specp->species_id] = viz_state;
--n_entries;
}
}
pointer_hash_destroy(&vizblk->parser_species_viz_states);
return 0;
}
/*************************************************************************
Initialize all viz output blocks for this simulation.
In: None.
Out: 0 on success, 1 if an error occurs
*************************************************************************/
static int init_viz_output(struct volume *world) {
for (struct viz_output_block *vizblk = world->viz_blocks; vizblk != NULL;
vizblk = vizblk->next) {
/* Copy species states into an array. */
if (init_viz_species_states(world->n_species, vizblk))
return 1;
/* If ALL_MOLECULES were requested, mark them all for inclusion. */
if (vizblk->viz_output_flag & VIZ_ALL_MOLECULES)
set_viz_all_molecules(world, vizblk, vizblk->default_mol_state);
/* Initialize each data frame in this block. */
if (init_frame_data_list(world, vizblk)) {
mcell_internal_error("Unknown error while initializing VIZ output.");
/*return 1;*/
}
}
return 0;
}
/********************************************************************
init_species:
Initializes array of molecules types to the default properties values.
*********************************************************************/
static int init_species_defaults(struct volume *world) {
world->speed_limit = 0;
world->n_species = world->mol_sym_table->n_entries;
world->species_list =
CHECKED_MALLOC_ARRAY(struct species *, world->n_species, "species table");
unsigned int count = 0;
for (int i = 0; i < world->mol_sym_table->n_bins; i++) {
for (struct sym_entry *sym = world->mol_sym_table->entries[i];
sym != NULL; sym = sym->next) {
if (sym->sym_type == MOL) {
struct species *s = (struct species *)sym->value;
world->species_list[count] = s;
world->species_list[count]->species_id = count;
world->species_list[count]->chkpt_species_id = UINT_MAX;
world->species_list[count]->population = 0;
world->species_list[count]->n_deceased = 0;
world->species_list[count]->cum_lifetime_seconds = 0;
if (!(world->species_list[count]->flags & SET_MAX_STEP_LENGTH)) {
world->species_list[count]->max_step_length = DBL_MAX;
}
// If volume molecule, set max speed per time step.
if ((s->flags & NOT_FREE) == 0) {
double speed = 6.0 * s->space_step / sqrt(MY_PI);
if (speed > world->speed_limit)
world->speed_limit = speed;
}
count++;
}
}
}
return 0;
}
/********************************************************************
create_storage:
This is a helper function to create the storage associated with a
particular subdivision (i.e. an IxJxK box of subvolumes with a common
scheduler and common memory allocation).
When we create a storage, we need to decide how big the memory pools should
be.
If the memory pools are too small, you lose some of the benefits of memory
pooling, since your memory blocks are more scattered. You also take on
extra overhead because of the extra arenas you end up allocating when you
need more objects than the original pool could provide.
If the memory pools are too large, you waste a lot of memory, as the memory
pool will allocate far more objects than you end up using. This can be a
serious issue.
In the best of all possible worlds, we'd tune the memory pools to coincide
exactly with the peak usage of each type of object in that subdivision.
Unfortunately, this would require uncanny prescience.
In the absence of such foresight, this code uses a fairly dumb heuristic
for deciding how large the memory pools should be in a subdivision. It
uses the number of subvolumes in the subdivision to set the size. This
seems, in practice, to be adequate. It's almost certain that we can
improve upon it.
A fairly simple improvement here might multiply the arena sizes by
different factors depending upon the type of object. There will likely be
an approximate relation between, say, the number of edges and the number of
walls (roughly a factor of 1.5 for triangular walls on a manifold surface).
Another possible improvement here might be to adaptively size the memory
arenas in the pooled allocators as we create objects. The first arena may
be small, but each subsequent arena would be larger.
Obviously, there are many more complicated things we could do, but it's not
clear that they would gain us much.
In: int nsubvols - how many subvolumes will share this storage
Out: A freshly allocated storage with initialized memory pools.
*******************************************************************/
static struct storage *create_storage(struct volume *world, int nsubvols) {
struct storage *shared_mem = NULL;
shared_mem =
CHECKED_MALLOC_STRUCT(struct storage, "memory storage partition");
memset(shared_mem, 0, sizeof(struct storage));
if (world->mem_part_pool != 0)
nsubvols = world->mem_part_pool;
if (nsubvols < 8)
nsubvols = 8;
if (nsubvols > 4096)
nsubvols = 4096;
/* We should tune the algorithm for selecting allocation block sizes. */
/* XXX: Round up to power of 2? Shouldn't matter, I think. */
if ((shared_mem->list = create_mem_named(sizeof(struct wall_list), nsubvols,
"wall list")) == NULL)
mcell_allocfailed("Failed to create memory pool for wall list.");
if ((shared_mem->mol = create_mem_named(sizeof(struct volume_molecule),
nsubvols, "vol mol")) == NULL)
mcell_allocfailed("Failed to create memory pool for volume molecules.");
if ((shared_mem->smol = create_mem_named(sizeof(struct surface_molecule),
nsubvols, "surface mol")) == NULL)
mcell_allocfailed("Failed to create memory pool for surface molecules.");
if ((shared_mem->face =
create_mem_named(sizeof(struct wall), nsubvols, "wall")) == NULL)
mcell_allocfailed("Failed to create memory pool for walls.");
if ((shared_mem->join =
create_mem_named(sizeof(struct edge), nsubvols, "edge")) == NULL)
mcell_allocfailed("Failed to create memory pool for edges.");
if ((shared_mem->grids = create_mem_named(sizeof(struct surface_grid),
nsubvols, "surface grid")) == NULL)
mcell_allocfailed("Failed to create memory pool for surface grids.");
if ((shared_mem->regl = create_mem_named(sizeof(struct region_list), nsubvols,
"region list")) == NULL)
mcell_allocfailed("Failed to create memory pool for region lists.");
if ((shared_mem->pslv = create_mem_named(sizeof(struct per_species_list), 32,
"per species list")) == NULL)
mcell_allocfailed(
"Failed to create memory pool for per-species molecule lists.");
shared_mem->coll = world->coll_mem;
shared_mem->sp_coll = world->sp_coll_mem;
shared_mem->tri_coll = world->tri_coll_mem;
shared_mem->exdv = world->exdv_mem;
if (world->chkpt_init) {
if ((shared_mem->timer = create_scheduler(1.0, 100.0, 100, 0.0)) == NULL)
mcell_allocfailed("Failed to create molecule scheduler.");
shared_mem->current_time = 0.0;
}
if (world->time_step_max == 0.0)
shared_mem->max_timestep = MICROSEC_PER_YEAR;
else {
if (world->time_step_max < world->time_unit)
shared_mem->max_timestep = 1.0;
else
shared_mem->max_timestep = world->time_step_max / world->time_unit;
}
return shared_mem;
}
static void sanity_check_memory_subdivision(struct volume *world) {
if (world->mem_part_x <= 0) {
if (world->mem_part_x < 0) {
mcell_warn("X-axis memory partition bin size set to a negative value. "
"Setting to default value of 14.");
world->mem_part_x = 14;
} else
world->mem_part_x = 10000000;
}
if (world->mem_part_y <= 0) {
if (world->mem_part_y < 0) {
mcell_warn("Y-axis memory partition bin size set to a negative value. "
"Setting to default value of 14.");
world->mem_part_y = 14;
} else
world->mem_part_y = 10000000;
}
if (world->mem_part_z <= 0) {
if (world->mem_part_z < 0) {
mcell_warn("Z-axis memory partition bin size set to a negative value. "
"Setting to default value of 14.");
world->mem_part_z = 14;
} else
world->mem_part_z = 10000000;
}
}
/********************************************************************
init_partitions:
Initialize the partitions for the simulation.
When we create a storage, we need to decide how big the memory pools should
be.
If the memory pools are too small, you lose some of the benefits of memory
pooling, since your memory blocks are more scattered. You also take on
extra overhead because of the extra arenas you end up allocating when you
need more objects than the original pool could provide.
If the memory pools are too large, you waste a lot of memory, as the memory
pool will allocate far more objects than you end up using. This can be a
serious issue.
In the best of all possible worlds, we'd tune the memory pools to coincide
exactly with the peak usage of each type of object in that subdivision.
Unfortunately, this would require uncanny prescience.
In the absence of such foresight, this code uses a fairly dumb heuristic
for deciding how large the memory pools should be in a subdivision. It
uses the number of subvolumes in the subdivision to set the size. This
seems, in practice, to be adequate. It's almost certain that we can
improve upon it.
A fairly simple improvement here might multiply the arena sizes by
different factors depending upon the type of object. There will likely be
an approximate relation between, say, the number of edges and the number of
walls (roughly a factor of 1.5 for triangular walls on a manifold surface).
Another possible improvement here might be to adaptively size the memory
arenas in the pooled allocators as we create objects. The first arena may
be small, but each subsequent arena would be larger.
Obviously, there are many more complicated things we could do, but it's not
clear that they would gain us much.
In: int nsubvols - how many subvolumes will share this storage
Out: A freshly allocated storage with initialized memory pools, or NULL if
memory allocation fails. Program state remains valid upon failure of
this function.
*******************************************************************/
int init_partitions(struct volume *world) {
/* Initialize the partitions, themselves */
if (set_partitions(world))
return 1;
/* Initialize dummy waypoints (why do we do this?) */
world->n_waypoints = 1;
world->waypoints = CHECKED_MALLOC_ARRAY(struct waypoint, world->n_waypoints,
"dummy waypoint");
/* Waypoints are not used in all cases, need to clear them first */
memset(world->waypoints, 0, sizeof(*world->waypoints));
/* Allocate the subvolumes */
world->n_subvols =
(world->nz_parts - 1) * (world->ny_parts - 1) * (world->nx_parts - 1);
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Creating %d subvolumes (%d,%d,%d per axis).", world->n_subvols,
world->nx_parts - 1, world->ny_parts - 1, world->nz_parts - 1);
world->subvol = CHECKED_MALLOC_ARRAY(struct subvolume, world->n_subvols,
"spatial subvolumes");
/* Decide how fine-grained to make the memory subdivisions */
sanity_check_memory_subdivision(world);
/* Allocate the data structures which are shared between storages */
if ((world->coll_mem = create_mem_named(sizeof(struct collision), 128,
"collision")) == NULL)
mcell_allocfailed("Failed to create memory pool for collisions.");
if ((world->sp_coll_mem = create_mem_named(sizeof(struct sp_collision), 128,
"sp collision")) == NULL)
mcell_allocfailed(
"Failed to create memory pool for trimolecular-pathway collisions.");
if ((world->tri_coll_mem = create_mem_named(sizeof(struct tri_collision), 128,
"tri collision")) == NULL)
mcell_allocfailed(
"Failed to create memory pool for trimolecular collisions.");
if ((world->exdv_mem = create_mem_named(sizeof(struct exd_vertex), 64,
"exact disk vertex")) == NULL)
mcell_allocfailed(
"Failed to create memory pool for exact disk calculation vertices.");
/* How many storage subdivisions along each axis? */
#ifdef MCELL3_ONLY_ONE_MEMPART
// multiple memparts make comparison against mcell4 difficult because
// the order of simulation changes
world->mem_part_x = 1;
world->mem_part_y = 1;
world->mem_part_z = 1;
int nx = 1;
int ny = 1;
int nz = 1;
#else
int nx = (world->nx_parts + (world->mem_part_x) - 2) / (world->mem_part_x);
int ny = (world->ny_parts + (world->mem_part_y) - 2) / (world->mem_part_y);
int nz = (world->nz_parts + (world->mem_part_z) - 2) / (world->mem_part_z);
#endif
if (world->notify->progress_report != NOTIFY_NONE)
mcell_log("Creating %d memory partitions (%d,%d,%d per axis).",
nx * ny * nz, nx, ny, nz);
/* Create memory pool for storages */
if ((world->storage_allocator =
create_mem_named(sizeof(struct storage_list), nx * ny * nz,
"storage allocator")) == NULL)
mcell_allocfailed("Failed to create memory pool for storage list.");
/* Allocate the storages */
std::vector<struct storage *> shared_mem(nx * ny * nz);
int cx = 0, cy = 0, cz = 0;
for (int i = 0; i < nx * ny * nz; ++i) {
/* Determine the number of subvolumes included in this subdivision */
#ifdef MCELL3_ONLY_ONE_MEMPART
int xd = world->nx_parts;
int yd = world->ny_parts;
int zd = world->nz_parts;
#else
int xd = world->mem_part_x, yd = world->mem_part_y, zd = world->mem_part_z;
if (cx == nx - 1)
xd = (world->nx_parts - 1) % world->mem_part_x;
if (cy == ny - 1)
yd = (world->ny_parts - 1) % world->mem_part_y;
if (cz == nz - 1)
zd = (world->nz_parts - 1) % world->mem_part_z;
if (++cx == nx) {
cx = 0;
if (++cy == ny) {
cy = 0;
++cz;
}
}
#endif
/* Allocate this storage */
if ((shared_mem[i] = create_storage(world, xd * yd * zd)) == NULL)
mcell_internal_error("Unknown error while creating a storage.");
/* Add to the storage list */
struct storage_list *l = (struct storage_list *)CHECKED_MEM_GET(
world->storage_allocator, "storage list item");
l->next = world->storage_head;
l->store = shared_mem[i];
world->storage_head = l;
}
/* Initialize each subvolume */
for (int i = 0; i < world->nx_parts - 1; i++)
for (int j = 0; j < world->ny_parts - 1; j++)
for (int k = 0; k < world->nz_parts - 1; k++) {
int h = k + (world->nz_parts - 1) * (j + (world->ny_parts - 1) * i);
struct subvolume *sv = &(world->subvol[h]);
sv->wall_head = NULL;
memset(&sv->mol_by_species, 0, sizeof(struct pointer_hash));
sv->species_head = NULL;
sv->mol_count = 0;
sv->llf.x = bisect_near(world->x_fineparts, world->n_fineparts,
world->x_partitions[i]);
sv->llf.y = bisect_near(world->y_fineparts, world->n_fineparts,
world->y_partitions[j]);
sv->llf.z = bisect_near(world->z_fineparts, world->n_fineparts,
world->z_partitions[k]);
sv->urb.x = bisect_near(world->x_fineparts, world->n_fineparts,
world->x_partitions[i + 1]);
sv->urb.y = bisect_near(world->y_fineparts, world->n_fineparts,
world->y_partitions[j + 1]);
sv->urb.z = bisect_near(world->z_fineparts, world->n_fineparts,
world->z_partitions[k + 1]);
/* Set flags so we know which directions to not go (we will fall off the
* world!) */
sv->world_edge =
0; /* Assume we're not at the edge of the world in any direction */
if (i == 0)
sv->world_edge |= X_NEG_BIT;
if (i == world->nx_parts - 2)
sv->world_edge |= X_POS_BIT;
if (j == 0)
sv->world_edge |= Y_NEG_BIT;
if (j == world->ny_parts - 2)
sv->world_edge |= Y_POS_BIT;
if (k == 0)
sv->world_edge |= Z_NEG_BIT;
if (k == world->nz_parts - 2)
sv->world_edge |= Z_POS_BIT;
/* Bind this subvolume to the appropriate storage */
#ifdef MCELL3_ONLY_ONE_MEMPART
int shidx = 0;
#else
int shidx =
(i / (world->mem_part_x)) +
nx * (j / (world->mem_part_y) + ny * (k / (world->mem_part_z)));
#endif
sv->local_storage = shared_mem[shidx];
}
return 0;
}
/**
* Initializes the bounding boxes of the world.
*/
int init_bounding_box(struct volume *world) {
double tm[4][4];
double vol_infinity;
no_printf("Initializing physical objects\n");
vol_infinity = sqrt(DBL_MAX) / 4;
world->bb_llf.x = vol_infinity;
world->bb_llf.y = vol_infinity;
world->bb_llf.z = vol_infinity;
world->bb_urb.x = -vol_infinity;
world->bb_urb.y = -vol_infinity;
world->bb_urb.z = -vol_infinity;
init_matrix(tm);
if (compute_bb(world, world->root_instance, tm))
return 1;
if ((!distinguishable(world->bb_llf.x, vol_infinity, EPS_C)) &&
(!distinguishable(world->bb_llf.y, vol_infinity, EPS_C)) &&
(!distinguishable(world->bb_llf.z, vol_infinity, EPS_C)) &&
(!distinguishable(world->bb_urb.x, -vol_infinity, EPS_C)) &&
(!distinguishable(world->bb_urb.y, -vol_infinity, EPS_C)) &&
(!distinguishable(world->bb_urb.z, -vol_infinity, EPS_C))) {
world->bb_llf.x = 0;
world->bb_llf.y = 0;
world->bb_llf.z = 0;
world->bb_urb.x = 0;
world->bb_urb.y = 0;
world->bb_urb.z = 0;
}
if (world->procnum == 0) {
if (world->notify->progress_report) {
mcell_log("MCell: world bounding box in microns =");
mcell_log(" [ %.9g %.9g %.9g ] [ %.9g %.9g %.9g ]",
world->bb_llf.x * world->length_unit,
world->bb_llf.y * world->length_unit,
world->bb_llf.z * world->length_unit,
world->bb_urb.x * world->length_unit,
world->bb_urb.y * world->length_unit,
world->bb_urb.z * world->length_unit);
}
}
world->n_walls = world->root_instance->n_walls;
world->n_verts = world->root_instance->n_verts;
no_printf("World object contains %d walls and %d vertices\n", world->n_walls,
world->n_verts);
return 0;
}
/**
* Instantiates all physical objects.
* This function is recursively called on the tree object objp until
* all the objects in the data structure have been instantiated.
* <br>
* This function actually calls instance_release_site() and
* instance_polygon_object() to handle the actual instantiation of
* those objects.
*/
int instance_obj(struct volume *world, struct geom_object *objp, double (*im)[4]) {
double tm[4][4];
mult_matrix(objp->t_matrix, im, tm, 4, 4, 4);
switch (objp->object_type) {
case META_OBJ:
for (struct geom_object *child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (instance_obj(world, child_objp, tm))
return 1;
}
break;
case REL_SITE_OBJ:
if (instance_release_site(world->magic_mem, world->releaser, objp, tm))
return 1;
break;
case BOX_OBJ:
case POLY_OBJ:
if (instance_polygon_object(world->notify->degenerate_polys, objp))
return 1;
break;
case VOXEL_OBJ:
default:
UNHANDLED_CASE(objp->object_type);
}
return 0;
}
/************************************************************************
accumulate_vertex_counts_per_storage:
Calculates total number of vertices that belong to each storage.
This function is recursively called on the tree object objp until
all the vertices in the object and its children have been counted.
In: object
array of vertex counts per storage
transformation matrix
Out: 0 - on success, and 1 - on failure.
Array of vertex counts per storage is updated for each
object vertex and recursively for object's children
************************************************************************/
int accumulate_vertex_counts_per_storage(struct volume *world,
struct geom_object *objp,
int *num_vertices_this_storage,
double (*im)[4]) {
double tm[4][4];
mult_matrix(objp->t_matrix, im, tm, 4, 4, 4);
switch (objp->object_type) {
case META_OBJ:
for (struct geom_object *child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (accumulate_vertex_counts_per_storage(world, child_objp,
num_vertices_this_storage, tm))
return 1;
}
break;
case BOX_OBJ:
case POLY_OBJ:
if (accumulate_vertex_counts_per_storage_polygon_object(
world, objp, num_vertices_this_storage, tm))
return 1;
break;
case REL_SITE_OBJ:
case VOXEL_OBJ:
default:
break;
}
return 0;
}
/*************************************************************************
accumulate_vertex_counts_per_storage_polygon_object:
Array of vertex counts per storage is updated for each
polygon object vertex.
In: polygon object
array of vertex counts per storage
transformation matrix
Out: 0 - on success, and 1 - on failure.
Array of vertex counts per storage is updated for each
polygon object vertex
**************************************************************************/
int accumulate_vertex_counts_per_storage_polygon_object(
struct volume *world, struct geom_object *objp, int *num_vertices_this_storage,
double (*im)[4]) {
struct vertex_list *vl;
struct vector3 v;
struct polygon_object *pop;
/* index in the "simulated" array of storages that follows
the linked list "world->storage_list" */
int idx;
pop = (struct polygon_object *)objp->contents;
for (vl = pop->parsed_vertices; vl != NULL; vl = vl->next) {
double p[4][4];
p[0][0] = vl->vertex->x;
p[0][1] = vl->vertex->y;
p[0][2] = vl->vertex->z;
p[0][3] = 1.0;
mult_matrix(p, im, p, 1, 4, 4);
v.x = p[0][0];
v.y = p[0][1];
v.z = p[0][2];
idx = which_storage_contains_vertex(world, &v);
if (idx < 0)
return 1;
++num_vertices_this_storage[idx];
}
return 0;
}
/*************************************************************************
which_storage_contains_vertex:
Returns the index of storage in the list of storages where
the vertex resides (through the subvolume to which it belongs).
In: vertex
Out: index of the storage in "world->storage_head" list
or (-1) when not found
**************************************************************************/
int which_storage_contains_vertex(struct volume *world, struct vector3 *v) {
struct subvolume *sv;
struct storage_list *sl;
int kk;
sv = find_subvolume(world, v, NULL);
for (sl = world->storage_head, kk = 0; sl != NULL; sl = sl->next, kk++) {
if (sl->store == sv->local_storage)
return kk;
}
/* if we came here, the vertex was not found in any of the storages */
return -1;
}
/***********************************************************************
fill_world_vertices_array:
Fills the array "world->all_vertices" with information
about the vertices in the world by going recursively
through all children objects.
In: object
array of number of vertices per storage
transformation matrix
Out: 0 if successful (the array "world->all_vertices" is filled),
1 - on failure
************************************************************************/
int fill_world_vertices_array(struct volume *world, struct geom_object *objp,
int *num_vertices_this_storage, double (*im)[4]) {
double tm[4][4];
mult_matrix(objp->t_matrix, im, tm, 4, 4, 4);
switch (objp->object_type) {
case META_OBJ:
for (struct geom_object *child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (fill_world_vertices_array(world, child_objp,
num_vertices_this_storage, tm))
return 1;
}
break;
case BOX_OBJ:
case POLY_OBJ:
if (fill_world_vertices_array_polygon_object(world, objp,
num_vertices_this_storage, tm))
return 1;
break;
case REL_SITE_OBJ:
case VOXEL_OBJ:
default:
break;
}
return 0;
}
/***********************************************************************
fill_world_vertices_array_polygon_object:
Fills the array "world->all_vertices" with information
about the vertices in the polygon object.
Also creates and fills "objp->vertices" array
In: object
array of number of vertices per storage
transformation matrix
Out: 0 if successful (the array "world->all_vertices" is filled with
info about vertices in the polygon object)
1 - on failure
************************************************************************/
int fill_world_vertices_array_polygon_object(struct volume *world,
struct geom_object *objp,
int *num_vertices_this_storage,
double (*im)[4]) {
struct polygon_object *pop;
struct vertex_list *vl;
int cur_vtx = 0; /* index */
int which_storage, where_in_array;
struct vector3 *v, vv;
pop = (struct polygon_object *)objp->contents;
objp->vertices =
CHECKED_MALLOC_ARRAY(struct vector3 *, objp->n_verts, "polygon vertices");
for (vl = pop->parsed_vertices; vl != NULL; vl = vl->next) {
double p[4][4];
p[0][0] = vl->vertex->x;
p[0][1] = vl->vertex->y;
p[0][2] = vl->vertex->z;
p[0][3] = 1.0;
mult_matrix(p, im, p, 1, 4, 4);
vv.x = p[0][0];
vv.y = p[0][1];
vv.z = p[0][2];
which_storage = which_storage_contains_vertex(world, &vv);
where_in_array = --num_vertices_this_storage[which_storage];
v = world->all_vertices + where_in_array;
*v = vv;
objp->vertices[cur_vtx++] = v;
}
return 0;
}
/**
* Instantiates a release site.
* Creates a new release site from a template release site
* as defined in the MDL file after applying the necessary
* geometric transformations (rotation and translation).
* Adds the rel
*/
int instance_release_site(struct mem_helper *magic_mem,
struct schedule_helper *releaser, struct geom_object *objp,
double (*im)[4]) {
struct release_event_queue *reqp;
struct release_site_obj *rsop = (struct release_site_obj *)objp->contents;
no_printf("Instancing release site object %s\n", objp->sym->name);
if (!distinguishable(rsop->release_prob, MAGIC_PATTERN_PROBABILITY, EPS_C)) {
struct magic_list *ml = (struct magic_list *)CHECKED_MEM_GET(
magic_mem, "rxn-triggered release descriptor");
ml->data = rsop;
ml->type = magic_release;
struct rxn_pathname *rxpn = (struct rxn_pathname *)rsop->pattern;
ml->next = rxpn->magic;
rxpn->magic = ml;
/* Region releases need to be in release queue to get initialized */
/* Release code itself is smart enough to ignore MAGIC_PATTERNs */
if (rsop->release_shape == SHAPE_REGION) {
reqp = CHECKED_MALLOC_STRUCT(struct release_event_queue, "release site");
reqp->release_site = rsop;
reqp->event_time = 0;
reqp->train_counter = 0;
reqp->train_high_time = 0;
if (schedule_add(releaser, reqp))
mcell_allocfailed("Failed to schedule molecule release.");
}
} else {
reqp = CHECKED_MALLOC_STRUCT(struct release_event_queue, "release site");
reqp->release_site = rsop;
reqp->event_time = rsop->pattern->delay;
reqp->train_counter = 0;
reqp->train_high_time = rsop->pattern->delay;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
reqp->t_matrix[i][j] = im[i][j];
/* Schedule the release event */
if (schedule_add(releaser, reqp))
mcell_allocfailed("Failed to schedule molecule release.");
if (rsop->pattern->train_duration > rsop->pattern->train_interval)
mcell_error(
"Release pattern train duration is greater than train interval.");
}
objp->is_closed = SHRT_MIN;
no_printf("Done instancing release site object %s\n", objp->sym->name);
return 0;
}
/**
* Computes the bounding box for the entire simulation world.
* Does things recursively in a manner similar to instance_obj().
*/
static int compute_bb(struct volume *world, struct geom_object *objp,
double (*im)[4]) {
double tm[4][4];
mult_matrix(objp->t_matrix, im, tm, 4, 4, 4);
switch (objp->object_type) {
case META_OBJ:
for (struct geom_object *child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (compute_bb(world, child_objp, tm))
return 1;
}
break;
case REL_SITE_OBJ:
if (compute_bb_release_site(world, objp, tm))
return 1;
break;
case BOX_OBJ:
case POLY_OBJ:
if (compute_bb_polygon_object(world, objp, tm))
return 1;
break;
case VOXEL_OBJ:
default:
UNHANDLED_CASE(objp->object_type);
}
return 0;
}
/**
* Updates the bounding box of the world based on the size
* and location of a release site.
* Used by compute_bb().
*/
static int compute_bb_release_site(struct volume *world, struct geom_object *objp,
double (*im)[4]) {
struct release_site_obj *rsop = (struct release_site_obj *)objp->contents;
if (rsop->release_shape == SHAPE_REGION)
return 0;
if (rsop->location == NULL)
mcell_error("Location is not specified for the geometrical shape release "
"site '%s'.",
objp->sym->name);
double location[1][4];
location[0][0] = rsop->location->x;
location[0][1] = rsop->location->y;
location[0][2] = rsop->location->z;
location[0][3] = 1.0;
mult_matrix(location, im, location, 1, 4, 4);
double diam_x, diam_y, diam_z; /* diameters of the release_site */
if (rsop->diameter == NULL) {
diam_x = diam_y = diam_z = 0;
} else {
diam_x = rsop->diameter->x;
diam_y = rsop->diameter->y;
diam_z = rsop->diameter->z;
}
if (location[0][0] - diam_x < world->bb_llf.x) {
world->bb_llf.x = location[0][0] - diam_x;
}
if (location[0][1] - diam_y < world->bb_llf.y) {
world->bb_llf.y = location[0][1] - diam_y;
}
if (location[0][2] - diam_z < world->bb_llf.z) {
world->bb_llf.z = location[0][2] - diam_z;
}
if (location[0][0] + diam_x > world->bb_urb.x) {
world->bb_urb.x = location[0][0] + diam_x;
}
if (location[0][1] + diam_y > world->bb_urb.y) {
world->bb_urb.y = location[0][1] + diam_y;
}
if (location[0][2] + diam_z > world->bb_urb.z) {
world->bb_urb.z = location[0][2] + diam_z;
}
return 0;
}
/**
* Updates the bounding box of the world based on the size
* and location of a polygon_object. Also updates the vertices in
"pop->parsed_vertices" array.
* Used by compute_bb().
*/
static int compute_bb_polygon_object(struct volume *world, struct geom_object *objp,
double (*im)[4]) {
struct polygon_object *pop = (struct polygon_object *)objp->contents;
assert(pop != NULL);
for (struct vertex_list *vl = pop->parsed_vertices;
vl != NULL;
vl = vl->next) {
double p[1][4];
p[0][0] = vl->vertex->x;
p[0][1] = vl->vertex->y;
p[0][2] = vl->vertex->z;
p[0][3] = 1.0;
mult_matrix(p, im, p, 1, 4, 4);
if (p[0][0] < world->bb_llf.x)
world->bb_llf.x = p[0][0];
if (p[0][1] < world->bb_llf.y)
world->bb_llf.y = p[0][1];
if (p[0][2] < world->bb_llf.z)
world->bb_llf.z = p[0][2];
if (p[0][0] > world->bb_urb.x)
world->bb_urb.x = p[0][0];
if (p[0][1] > world->bb_urb.y)
world->bb_urb.y = p[0][1];
if (p[0][2] > world->bb_urb.z)
world->bb_urb.z = p[0][2];
}
return 0;
}
/**
* Instantiates a polygon_object.
* Creates walls from a template polygon_object or box object
* as defined in the MDL file after applying the necessary geometric
* transformations (scaling, rotation and translation).
* <br>
*/
int instance_polygon_object(enum warn_level_t degenerate_polys,
struct geom_object *objp) {
int index_0, index_1, index_2;
unsigned int degenerate_count;
struct polygon_object *pop = (struct polygon_object *)objp->contents;
int n_walls = pop->n_walls;
double total_area = 0;
/* Allocate and initialize walls and vertices */
struct wall *w = CHECKED_MALLOC_ARRAY(struct wall, n_walls, "polygon walls");
struct wall **wp = CHECKED_MALLOC_ARRAY(struct wall *, n_walls, "polygon wall pointers");
objp->walls = w;
objp->wall_p = wp;
/* we do not need "parsed_vertices" info */
if (pop->parsed_vertices != NULL) {
free_vertex_list(pop->parsed_vertices);
pop->parsed_vertices = NULL;
}
degenerate_count = 0;
for (int n_wall = 0; n_wall < n_walls; ++n_wall) {
if (!get_bit(pop->side_removed, n_wall)) {
wp[n_wall] = &w[n_wall];
index_0 = pop->element[n_wall].vertex_index[0];
index_1 = pop->element[n_wall].vertex_index[1];
index_2 = pop->element[n_wall].vertex_index[2];
/* sanity check that the vertex indices are in range */
if ((index_0 > pop->n_verts) || (index_1 > pop->n_verts) ||
(index_2 > pop->n_verts)) {
mcell_error("object %s has elements with out of bounds vertex indices",
objp->sym->name);
}
init_tri_wall(objp, n_wall, objp->vertices[index_0],
objp->vertices[index_1], objp->vertices[index_2]);
total_area += wp[n_wall]->area;
if (!distinguishable(wp[n_wall]->area, 0, EPS_C)) {
if (degenerate_polys != WARN_COPE) {
if (degenerate_polys == WARN_ERROR) {
mcell_error("Degenerate polygon found: %s %d\n"
" Vertex 0: %.5e %.5e %.5e\n"
" Vertex 1: %.5e %.5e %.5e\n"
" Vertex 2: %.5e %.5e %.5e",
objp->sym->name, n_wall, objp->vertices[index_0]->x,
objp->vertices[index_0]->y, objp->vertices[index_0]->z,
objp->vertices[index_1]->x, objp->vertices[index_1]->y,
objp->vertices[index_1]->z, objp->vertices[index_2]->x,
objp->vertices[index_2]->y, objp->vertices[index_2]->z);
} else
mcell_warn(
"Degenerate polygon found and automatically removed: %s %d\n"
" Vertex 0: %.5e %.5e %.5e\n"
" Vertex 1: %.5e %.5e %.5e\n"
" Vertex 2: %.5e %.5e %.5e",
objp->sym->name, n_wall, objp->vertices[index_0]->x,
objp->vertices[index_0]->y, objp->vertices[index_0]->z,
objp->vertices[index_1]->x, objp->vertices[index_1]->y,
objp->vertices[index_1]->z, objp->vertices[index_2]->x,
objp->vertices[index_2]->y, objp->vertices[index_2]->z);
}
set_bit(pop->side_removed, n_wall, 1);
objp->n_walls_actual--;
degenerate_count++;
wp[n_wall] = NULL;
}
} else {
wp[n_wall] = NULL;
}
}
if (degenerate_count)
remove_gaps_from_regions(objp);
objp->total_area = total_area;
objp->is_closed = SHRT_MIN;
#ifdef DEBUG
printf("n_walls = %d\n", n_walls);
printf("n_walls_actual = %d\n", objp->n_walls_actual);
#endif
return 0;
}
/********************************************************************
init_regions_helper:
Traverse the world initializing regions on each object.
In: none
Out: 0 on success, 1 on failure
*******************************************************************/
static int init_regions_helper(struct volume *world) {
if (world->clamp_list != NULL)
init_clamp_lists(world->clamp_list);
return instance_obj_regions(world, world->root_instance);
}
/* First part of concentration clamp initialization. */
/* After this, list is grouped by surface class. */
/* Second part (list of objects) happens with regions. */
void init_clamp_lists(struct clamp_data *clamp_list) {
/* Sort by memory order of surface_class pointer--handy way to collect like
* classes */
clamp_list = (struct clamp_data *)void_list_sort(
(struct void_list *)clamp_list);
/* Toss other molecules in same surface class into next_mol lists */
for (struct clamp_data *cdp = clamp_list; cdp != NULL; cdp = cdp->next) {
while (cdp->next != NULL && cdp->surf_class == cdp->next->surf_class) {
cdp->next->next_mol = cdp->next_mol;
cdp->next_mol = cdp->next;
cdp->next = cdp->next->next;
}
for (struct clamp_data *temp = cdp->next_mol;
temp != NULL;
temp = temp->next_mol) {
temp->next = cdp->next;
}
}
}
/**
* Traverse through metaobjects, placing regions on real objects as we find
* them.
*/
int instance_obj_regions(struct volume *world, struct geom_object *objp) {
switch (objp->object_type) {
case META_OBJ:
for (struct geom_object *child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (instance_obj_regions(world, child_objp))
return 1;
}
break;
case REL_SITE_OBJ:
break;
case BOX_OBJ:
case POLY_OBJ:
if (init_wall_regions(world->length_unit, world->clamp_list,
world->species_list, world->n_species, objp))
return 1;
break;
case VOXEL_OBJ:
default:
UNHANDLED_CASE(objp->object_type);
}
return 0;
}
/**
* Initialize data associated with wall regions.
* This function is called during wall instantiation Pass #3
* after walls have been copied to sub-volume local memory.
* Sets wall surf_class by region.
* Creates surface grids.
* Populates surface molecule tiles by region.
* Creates virtual regions on which to clamp concentration
*/
int init_wall_regions(double length_unit, struct clamp_data *clamp_list,
struct species **species_list, int n_species,
struct geom_object *objp) {
struct wall *w;
struct region *rp;
struct region_list *rlp, *wrlp;
struct surf_class_list *scl;
struct edge_list *el;
struct void_list *temp_list;
int num_boundaries;
struct pointer_hash *borders;
struct edge_list *rp_borders_head;
int surf_class_present;
struct species *sp;
struct name_orient *no;
const struct polygon_object *pop = (struct polygon_object *)objp->contents;
int n_walls = pop->n_walls;
no_printf("Processing %d regions in polygon list object: %s\n",
objp->num_regions, objp->sym->name);
/* prepend a copy of sm_dat for each element referenced in each region
of this object to the sm_prop list for the referenced element */
for (rlp = objp->regions; rlp != NULL; rlp = rlp->next) {
rp = rlp->reg;
// One of the only places to set COUNT_CONTENTS is when creating a release
// site (mdl_set_release_site_geometry_object), which will never get called
// during a dynamic geometry event, so we need to do it here.
rp->flags |= COUNT_CONTENTS;
if (rp->membership == NULL)
mcell_internal_error("Missing region information for '%s'.",
rp->sym->name);
/* This code is used in the description of "restrictive regions"
for surface molecules. The flag REGION_SET indicates that for
the surface molecule that has CAN_REGION_BORDER flag set through
the SURFACE_CLASS definition there are regions defined with
this surface_class assigned. */
if (rp->surf_class != NULL) {
for (no = rp->surf_class->refl_mols; no != NULL; no = no->next) {
sp = get_species_by_name(no->name, n_species, species_list);
if (sp != NULL) {
if ((sp->flags & REGION_PRESENT) == 0) {
sp->flags |= REGION_PRESENT;
}
}
}
for (no = rp->surf_class->absorb_mols; no != NULL; no = no->next) {
sp = get_species_by_name(no->name, n_species, species_list);
if (sp != NULL) {
if ((sp->flags & REGION_PRESENT) == 0) {
sp->flags |= REGION_PRESENT;
}
}
}
for (no = rp->surf_class->transp_mols; no != NULL; no = no->next) {
sp = get_species_by_name(no->name, n_species, species_list);
if (sp != NULL) {
if ((sp->flags & REGION_PRESENT) == 0) {
sp->flags |= REGION_PRESENT;
}
}
}
}
rp_borders_head = NULL;
int count = 0;
for (int n_wall = 0; n_wall < rp->membership->nbits; ++n_wall) {
if (get_bit(rp->membership, n_wall)) {
count++;
}
}
if (count == n_walls)
rp->region_has_all_elements = 1;
for (int n_wall = 0; n_wall < rp->membership->nbits; ++n_wall) {
if (get_bit(rp->membership, n_wall)) {
/* prepend this region to wall region list of i_th wall only if the
* region is used in counting */
w = objp->wall_p[n_wall];
rp->area += w->area;
if (rp->surf_class != NULL) {
/* check whether this region's surface class is already
assigned to the wall's surface class list */
surf_class_present = 0;
for (scl = w->surf_class_head; scl != NULL; scl = scl->next) {
if (scl->surf_class == rp->surf_class) {
surf_class_present = 1;
break;
}
}
if (!surf_class_present) {
scl = CHECKED_MALLOC_STRUCT(struct surf_class_list,
"surf_class_list");
scl->surf_class = rp->surf_class;
if (w->surf_class_head == NULL) {
scl->next = NULL;
w->surf_class_head = scl;
} else {
scl->next = w->surf_class_head;
w->surf_class_head = scl;
}
w->num_surf_classes++;
}
}
if ((rp->flags & COUNT_SOME_MASK) != 0) {
wrlp = (struct region_list *)CHECKED_MEM_GET(w->birthplace->regl,
"wall region list");
wrlp->reg = rp;
wrlp->next = w->counting_regions;
w->counting_regions = wrlp;
w->flags |= rp->flags;
}
/* add edges of this wall to the region's edge list */
if ((strcmp(rp->region_last_name, "ALL") != 0) &&
(!(rp->region_has_all_elements))) {
for (int ii = 0; ii < 3; ii++) {
if ((el = CHECKED_MALLOC_STRUCT(struct edge_list, "edge_list")) ==
NULL) {
mcell_internal_error(
"Out of memory while creating edge list for the region '%s'",
rp->sym->name);
}
el->ed = w->edges[ii];
el->next = rp_borders_head;
rp_borders_head = el;
}
}
}
} /* end for */
/* from all edges in the region collect ones that
constitute external borders of the region into "rp->boundaries" */
if ((strcmp(rp->region_last_name, "ALL") != 0) &&
(!(rp->region_has_all_elements))) {
/* sort the linked list */
temp_list = void_list_sort((struct void_list *)rp_borders_head);
/* remove all internal edges */
num_boundaries = remove_both_duplicates(&temp_list);
rp_borders_head = (struct edge_list *)temp_list;
if ((borders = CHECKED_MALLOC_STRUCT(struct pointer_hash,
"pointer_hash")) == NULL) {
mcell_internal_error("Out of memory while creating boundary pointer "
"hash for the region %s",
rp->sym->name);
}
if (pointer_hash_init(borders, 2 * num_boundaries)) {
mcell_error(
"Failed to initialize data structure for region boundaries.");
/*return 1;*/
}
rp->boundaries = borders;
for (el = rp_borders_head; el != NULL; el = el->next) {
unsigned int keyhash = (unsigned int)(intptr_t)(el->ed);
void *key = (void *)(el->ed);
if (pointer_hash_add(rp->boundaries, key, keyhash, (void *)(el->ed))) {
mcell_allocfailed(
"Failed to store edge in the region pointer_hash table.");
}
}
delete_void_list((struct void_list *)rp_borders_head);
rp_borders_head = NULL;
}
} /*end loop over all regions in object */
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
if (get_bit(pop->side_removed, n_wall))
continue;
w = objp->wall_p[n_wall];
if (w->counting_regions != NULL) {
w->counting_regions = (struct region_list *)void_list_sort((
struct void_list *)w->counting_regions); /* Helpful for comparisons */
}
if (w->num_surf_classes > 1)
check_for_conflicting_surface_classes(w, n_species, species_list);
}
/* Check to see if we need to generate virtual regions for */
/* concentration clamps on this object */
if (clamp_list != NULL) {
struct clamp_data *cdp;
struct clamp_data *temp;
int j;
int found_something = 0;
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
if (get_bit(pop->side_removed, n_wall))
continue;
if (objp->wall_p[n_wall]->surf_class_head != NULL) {
for (scl = objp->wall_p[n_wall]->surf_class_head; scl != NULL;
scl = scl->next) {
for (cdp = clamp_list; cdp != NULL; cdp = cdp->next) {
if (scl->surf_class == cdp->surf_class) {
if (cdp->objp != objp) {
if (cdp->objp == NULL)
cdp->objp = objp;
else if ((temp = find_clamped_object_in_list(cdp, objp)) != NULL)
{
cdp = temp;
}
else {
temp = CHECKED_MALLOC_STRUCT(struct clamp_data,
"clamp data");
memcpy(temp, cdp, sizeof(struct clamp_data));
temp->objp = objp;
temp->sides = NULL;
temp->n_sides = 0;
temp->side_idx = NULL;
temp->cum_area = NULL;
cdp->next_obj = temp;
cdp = temp;
}
}
if (cdp->sides == NULL) {
cdp->sides = new_bit_array(n_walls);
if (cdp->sides == NULL)
mcell_allocfailed("Failed to allocate membership bit array "
"for concentration clamp data.");
set_all_bits(cdp->sides, 0);
}
set_bit(cdp->sides, n_wall, 1);
cdp->n_sides++;
found_something = 1;
}
}
}
}
}
if (found_something) {
for (cdp = clamp_list; cdp != NULL; cdp = cdp->next) {
if (cdp->objp != objp) {
if (cdp->next_obj != NULL && cdp->next_obj->objp == objp)
cdp = cdp->next_obj;
else
continue;
}
cdp->side_idx = CHECKED_MALLOC_ARRAY(
int, cdp->n_sides, "concentration clamp polygon side index");
cdp->cum_area = CHECKED_MALLOC_ARRAY(
double, cdp->n_sides,
"concentration clamp polygon side cumulative area");
j = 0;
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
if (get_bit(cdp->sides, n_wall)) {
cdp->side_idx[j] = n_wall;
cdp->cum_area[j] = objp->wall_p[n_wall]->area;
j++;
}
}
if (j != cdp->n_sides)
mcell_internal_error("Miscounted the number of walls for "
"concentration clamp. object=%s surface "
"class=%s",
objp->sym->name, cdp->surf_class->sym->name);
for (j = 1; j < cdp->n_sides; j++)
cdp->cum_area[j] += cdp->cum_area[j - 1];
cdp->scaling_factor =
cdp->cum_area[cdp->n_sides - 1] * length_unit *
length_unit * length_unit /
2.9432976599069717358e-9; /* sqrt(MY_PI)/(1e-15*N_AV) */
}
}
}
return 0;
}
/********************************************************************
init_surf_mols:
Traverse the world placing surface molecules.
In: none
Out: 0 on success, 1 on failure
*******************************************************************/
int init_surf_mols(struct volume *world) {
return instance_obj_surf_mols(world, world->root_instance);
}
/********************************************************************
instance_obj_surf_mols:
Place any appropriate surface molecules on this object and/or its children.
In: struct object *objp - the object upon which to instantiate molecules
Out: 0 on success, 1 on failure
*******************************************************************/
int instance_obj_surf_mols(struct volume *world, struct geom_object *objp) {
struct geom_object *child_objp;
switch (objp->object_type) {
case META_OBJ:
for (child_objp = objp->first_child; child_objp != NULL;
child_objp = child_objp->next) {
if (instance_obj_surf_mols(world, child_objp))
return 1;
}
break;
case REL_SITE_OBJ:
break;
case BOX_OBJ:
case POLY_OBJ:
if (init_wall_surf_mols(world, objp))
return 1;
break;
case VOXEL_OBJ:
default:
break;
}
return 0;
}
/********************************************************************
init_wall_surf_mols:
Place any appropriate surface molecules on this wall. The object passed in
must be a box or a polygon.
In: struct object *objp - the object upon which to instantiate molecules
Out: 0 on success, 1 on failure
*******************************************************************/
int init_wall_surf_mols(struct volume *world, struct geom_object *objp) {
struct sm_dat *smdp, *dup_smdp, **sm_prop;
struct region_list *rlp, *rlp2, *reg_sm_num_head;
/* byte all_region; */ /* flag that points to the region called ALL */
struct surf_class_list *scl;
const struct polygon_object *pop = (struct polygon_object *)objp->contents;
int n_walls = pop->n_walls;
/* allocate scratch storage to hold surface molecule info for each wall */
sm_prop = CHECKED_MALLOC_ARRAY(struct sm_dat *, n_walls,
"surface molecule data scratch space");
for (int n_wall = 0; n_wall < n_walls; ++n_wall)
sm_prop[n_wall] = NULL;
/* prepend a copy of sm_dat for each element referenced in each region
of this object to the sm_prop list for the referenced element */
reg_sm_num_head = NULL;
for (rlp = objp->regions; rlp != NULL; rlp = rlp->next) {
struct region *rp = rlp->reg;
byte reg_sm_num = 0;
/* all_region = (strcmp(rp->region_last_name, "ALL") == 0); */
/* Place molecules defined through DEFINE_SURFACE_REGIONS */
for (int n_wall = 0; n_wall < rp->membership->nbits; n_wall++) {
if (get_bit(rp->membership, n_wall)) {
/* prepend region sm data for this region to sm_prop for i_th wall */
for (smdp = rp->sm_dat_head; smdp != NULL; smdp = smdp->next) {
if (smdp->quantity_type == SURFMOLDENS) {
dup_smdp =
CHECKED_MALLOC_STRUCT(struct sm_dat, "surface molecule data");
dup_smdp->sm = smdp->sm;
dup_smdp->quantity_type = smdp->quantity_type;
dup_smdp->quantity = smdp->quantity;
dup_smdp->orientation = smdp->orientation;
dup_smdp->next = sm_prop[n_wall];
sm_prop[n_wall] = dup_smdp;
} else
reg_sm_num = 1;
}
}
} /* done checking each wall */
if (rp->surf_class != NULL) {
for (smdp = rp->surf_class->sm_dat_head; smdp != NULL;
smdp = smdp->next) {
if (smdp->quantity_type == SURFMOLNUM) {
reg_sm_num = 1;
break;
}
}
}
if (reg_sm_num) {
rlp2 = CHECKED_MALLOC_STRUCT(struct region_list,
"surface molecule placement region list");
rlp2->reg = rp;
rlp2->next = reg_sm_num_head;
reg_sm_num_head = rlp2;
}
} /*end for (... ; rlp != NULL ; ...) */
/* Place molecules defined through DEFINE_SURFACE_CLASSES */
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
struct wall *w = objp->wall_p[n_wall];
if (w == NULL)
continue;
for (scl = w->surf_class_head; scl != NULL; scl = scl->next) {
for (smdp = scl->surf_class->sm_dat_head; smdp != NULL;
smdp = smdp->next) {
if (smdp->quantity_type == SURFMOLDENS) {
dup_smdp =
CHECKED_MALLOC_STRUCT(struct sm_dat, "surface molecule data");
dup_smdp->sm = smdp->sm;
dup_smdp->quantity_type = smdp->quantity_type;
dup_smdp->quantity = smdp->quantity;
dup_smdp->orientation = smdp->orientation;
dup_smdp->next = sm_prop[n_wall];
sm_prop[n_wall] = dup_smdp;
}
}
}
}
/* Place regular (non-macro) molecules by density */
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
if (!get_bit(pop->side_removed, n_wall)) {
if (sm_prop[n_wall] != NULL) {
if (init_surf_mols_by_density(world, objp->wall_p[n_wall],
sm_prop[n_wall]))
return 1;
}
}
}
/* Place regular (non-macro) molecules by number */
if (reg_sm_num_head != NULL) {
if (init_surf_mols_by_number(world, objp, reg_sm_num_head))
return 1;
/* free region list created to hold regions populated by number */
rlp = reg_sm_num_head;
while (rlp != NULL) {
rlp2 = rlp;
rlp = rlp->next;
free(rlp2);
}
}
/* free sm_prop array and contents */
for (int n_wall = 0; n_wall < n_walls; n_wall++) {
if (sm_prop[n_wall] != NULL) {
smdp = sm_prop[n_wall];
while (smdp != NULL) {
dup_smdp = smdp;
smdp = smdp->next;
free(dup_smdp);
}
}
}
free(sm_prop);
return 0;
}
/********************************************************************
init_surf_mols_by_density:
Place surface molecules on the specified wall. This occurs before placing
surface molecules by number. This is done by computing a per-tile
probability, and releasing a molecule onto each tile with the appropriate
probability.
In: struct wall *w - wall upon which to place
struct sm_dat *smdp - description of what to release
Out: 0 on success, 1 on failure
*******************************************************************/
int init_surf_mols_by_density(struct volume *world, struct wall *w,
struct sm_dat *smdp_head) {
no_printf("Initializing surface molecules by density...\n");
if (create_grid(world, w, NULL))
mcell_allocfailed("Failed to create grid for wall.");
struct geom_object *objp = w->parent_object;
int num_sm_dat = 0;
for (struct sm_dat *smdp = smdp_head; smdp != NULL; smdp = smdp->next)
++num_sm_dat;
struct species **sm =
CHECKED_MALLOC_ARRAY(struct species *, num_sm_dat,
"surface-molecule-by-density placement array");
memset(sm, 0, num_sm_dat * sizeof(struct species *));
double *prob = CHECKED_MALLOC_ARRAY(
double, num_sm_dat, "surface-molecule-by-density placement array");
memset(prob, 0, num_sm_dat * sizeof(double));
short *orientation = CHECKED_MALLOC_ARRAY(
short, num_sm_dat, "surface-molecule-by-density placement array");
memset(orientation, 0, num_sm_dat * sizeof(short));
struct surface_grid *sg = w->grid;
unsigned int n_tiles = sg->n_tiles;
double area = w->area;
objp->n_tiles += n_tiles;
no_printf("Initializing %d surf_mols...\n", n_tiles);
no_printf(" Area = %.9g\n", area);
no_printf(" Grid_size = %d\n", sg->n);
no_printf(" Number of surface molecule types in wall = %d\n", num_sm_dat);
unsigned int n_sm_entry = 0;
double tot_prob = 0;
double tot_density = 0;
for (struct sm_dat *smdp = smdp_head; smdp != NULL; smdp = smdp->next) {
no_printf(" Adding surface molecule %s to wall at density %.9g\n",
smdp->sm->sym->name, smdp->quantity);
tot_prob += (area * smdp->quantity) / (n_tiles * world->grid_density);
prob[n_sm_entry] = tot_prob;
if (smdp->orientation > 0)
orientation[n_sm_entry] = 1;
else if (smdp->orientation < 0)
orientation[n_sm_entry] = -1;
else
orientation[n_sm_entry] = 0;
sm[n_sm_entry++] = smdp->sm;
tot_density += smdp->quantity;
}
if (tot_density > world->grid_density)
mcell_warn(
"Total surface molecule density too high: %f. Filling all available "
"surface molecule sites.",
tot_density);
if (world->chkpt_init) {
for (unsigned int n_tile = 0; n_tile < n_tiles; ++n_tile) {
if (sg->sm_list[n_tile] && sg->sm_list[n_tile]->sm)
continue;
int p_index = -1;
double rnd = rng_dbl(world->rng);
for (int n_sm = 0; n_sm < num_sm_dat; ++n_sm) {
if (rnd <= prob[n_sm]) {
p_index = n_sm;
break;
}
}
if (p_index == -1)
continue;
struct periodic_image periodic_box = {0, 0, 0};
struct vector3 pos3d = {0, 0, 0};
short flags = TYPE_SURF | ACT_NEWBIE | IN_SCHEDULE | IN_SURFACE;
struct surface_molecule *new_sm = place_single_molecule(
world, w, n_tile, sm[p_index], 0, flags, orientation[p_index], 0, 0, 0,
&periodic_box, &pos3d);
if (trigger_unimolecular(world->reaction_hash, world->rx_hashsize,
sm[p_index]->hashval,
(struct abstract_molecule *)new_sm) != NULL ||
(sm[p_index]->flags & CAN_SURFWALL) != 0) {
new_sm->flags |= ACT_REACT;
}
}
}
unsigned int n_occupied = w->grid->n_occupied;
sg->n_occupied = n_occupied;
objp->n_occupied_tiles += n_occupied;
#ifdef DEBUG
for (int n_sm = 0; n_sm < num_sm_dat; ++n_sm)
no_printf("Total number of surface molecules %s = %d\n",
sm[n_sm]->sym->name, sm[n_sm]->population);
#endif
free(sm);
free(prob);
free(orientation);
no_printf("Done initializing %u surface molecules by density\n", n_occupied);
return 0;
}
/********************************************************************
init_surf_mols_by_number:
Place surface molecules on the specified object. This occurs after placing
surface molecules by density.
In: struct object *objp - object upon which to place
struct region_list *reg_sm_num_head - list of what to place
Out: 0 on success, 1 on failure
*******************************************************************/
int init_surf_mols_by_number(struct volume *world, struct geom_object *objp,
struct region_list *reg_sm_num_head) {
static struct surface_molecule DUMMY_MOLECULE;
static struct surface_molecule *bread_crumb = &DUMMY_MOLECULE;
short flags = TYPE_SURF | ACT_NEWBIE | IN_SCHEDULE | IN_SURFACE;
unsigned int n_free_sm;
// struct subvolume *gsv = NULL;
no_printf("Initializing surface molecules by number...\n");
/* traverse region list and add surface molecule sites by number to whole
regions as appropriate */
for (struct region_list *rlp = reg_sm_num_head; rlp != NULL;
rlp = rlp->next) {
struct region *rp = rlp->reg;
/* initialize surface molecule grids in region as needed and */
/* count total number of free surface molecule sites in region */
n_free_sm = 0;
for (int n_wall = 0; n_wall < rp->membership->nbits; n_wall++) {
if (get_bit(rp->membership, n_wall)) {
struct wall *w = objp->wall_p[n_wall];
if (create_grid(world, w, NULL))
mcell_allocfailed("Failed to allocate grid for wall.");
struct surface_grid *sg = w->grid;
n_free_sm = n_free_sm + (sg->n_tiles - sg->n_occupied);
}
}
no_printf("Number of free surface molecule tiles in region %s = %d\n",
rp->sym->name, n_free_sm);
if (n_free_sm == 0) {
mcell_warn("Number of free surface molecule tiles in region %s = %d",
rp->sym->name, n_free_sm);
continue;
}
if (world->chkpt_init) { /* only needed for denovo initiliazation */
/* allocate memory to hold array of pointers to all free tiles */
struct surface_molecule ***tiles =
CHECKED_MALLOC_ARRAY(struct surface_molecule **, n_free_sm,
"surface molecule placement tiles array");
unsigned int *idx = CHECKED_MALLOC_ARRAY(
unsigned int, n_free_sm, "surface molecule placement indices array");
struct wall **walls = CHECKED_MALLOC_ARRAY(
struct wall *, n_free_sm, "surface molecule placement walls array");
/* initialize array of pointers to all free tiles */
int n_slot = 0;
for (int n_wall = 0; n_wall < rp->membership->nbits; n_wall++) {
if (get_bit(rp->membership, n_wall)) {
struct wall *w = objp->wall_p[n_wall];
struct surface_grid *sg = w->grid;
if (sg != NULL) {
for (unsigned int n_tile = 0; n_tile < sg->n_tiles; n_tile++) {
if (sg->sm_list[n_tile] == NULL || sg->sm_list[n_tile]->sm == NULL) {
sg->sm_list[n_tile] = add_surfmol_with_unique_pb_to_list(sg->sm_list[n_tile], NULL);
tiles[n_slot] = &(sg->sm_list[n_tile]->sm);
idx[n_slot] = n_tile;
walls[n_slot++] = w;
}
}
}
}
}
// reverse - by default release by density are in correct order, but
// release by num in opposite,
// we do not want to introduce this into MCell3 so this is a permanent change
#ifdef MCELL3_REVERSE_INITIAL_SURF_MOL_PLACEMENT_BY_NUM
std::vector<sm_dat*> sm_dat_vec;
for (struct sm_dat *smdp = rp->sm_dat_head; smdp != NULL; smdp = smdp->next) {
sm_dat_vec.insert(sm_dat_vec.begin(), smdp);
}
#else
std::vector<sm_dat*> sm_dat_vec;
for (struct sm_dat *smdp = rp->sm_dat_head; smdp != NULL; smdp = smdp->next) {
sm_dat_vec.push_back(smdp);
}
#endif
/* distribute desired number of surface molecule sites */
/* for each surface molecule type to add */
/* place molecules BY NUMBER when it is defined through
* DEFINE_SURFACE_REGION */
for (struct sm_dat *smdp: sm_dat_vec) {
if (smdp->quantity_type == SURFMOLNUM) {
struct species *sm = smdp->sm;
short orientation;
unsigned int n_set = (unsigned int)smdp->quantity;
unsigned int n_clear = n_free_sm - n_set;
/* Compute orientation */
if (smdp->orientation > 0)
orientation = 1;
else if (smdp->orientation < 0)
orientation = -1;
else
orientation = 0;
/* Clamp n_set to number of available slots (w/ warning). */
if (n_set > n_free_sm) {
mcell_warn(
"Number of %s surface molecules to place (%d) exceeds number "
"of free surface molecule tiles (%d) in region %s[%s].\n"
"Surface molecule %s placed on all available surface molecule "
"sites.",
sm->sym->name, n_set, n_free_sm, rp->parent->sym->name,
rp->region_last_name, sm->sym->name);
n_set = n_free_sm;
n_clear = 0;
}
no_printf("distribute %d of surface molecule %s\n", n_set,
sm->sym->name);
no_printf("n_set = %d n_clear = %d n_free_sm = %d\n", n_set,
n_clear, n_free_sm);
/* if filling more than half the free tiles
init all with bread_crumbs
choose which tiles to free again
and then convert remaining bread_crumbs to actual molecules */
if (n_set > n_free_sm / 2) {
no_printf("filling more than half the free tiles: init all with "
"bread_crumb\n");
for (unsigned int j = 0; j < n_free_sm; j++) {
*tiles[j] = bread_crumb;
}
no_printf("choose which tiles to free again\n");
for (unsigned int j = 0; j < n_clear; j++) {
/* Loop until we find a vacant tile. */
while (1) {
int slot_num = (int)(rng_dbl(world->rng) * n_free_sm);
if (*tiles[slot_num] == bread_crumb) {
*tiles[slot_num] = NULL;
break;
}
}
}
no_printf("convert remaining bread_crumbs to actual molecules\n");
for (unsigned int j = 0; j < n_free_sm; j++) {
if (*tiles[j] == bread_crumb) {
struct periodic_image periodic_box = {0, 0, 0};
struct vector3 pos3d = {0, 0, 0};
struct surface_molecule *new_sm = place_single_molecule(
world, walls[j], idx[j], sm, 0, flags, orientation, 0, 0, 0,
&periodic_box, &pos3d);
if (trigger_unimolecular(
world->reaction_hash, world->rx_hashsize, sm->hashval,
(struct abstract_molecule *)new_sm) != NULL ||
(sm->flags & CAN_SURFWALL) != 0) {
new_sm->flags |= ACT_REACT;
}
}
}
} else { /* just fill only the tiles we need */
no_printf("fill only the tiles we need\n");
for (unsigned int j = 0; j < n_set; j++) {
/* Loop until we find a vacant tile. */
while (1) {
int slot_num = (int)(rng_dbl(world->rng) * n_free_sm);
if (*tiles[slot_num] == NULL) {
struct periodic_image periodic_box = {0, 0, 0};
struct vector3 pos3d = {0, 0, 0};
struct surface_molecule *new_sm = place_single_molecule(
world, walls[slot_num], idx[slot_num], sm, 0, flags,
orientation, 0, 0, 0, &periodic_box, &pos3d);
if (trigger_unimolecular(
world->reaction_hash, world->rx_hashsize, sm->hashval,
(struct abstract_molecule *)new_sm) != NULL ||
(sm->flags & CAN_SURFWALL) != 0) {
new_sm->flags |= ACT_REACT;
}
break;
}
}
}
}
if (n_clear > 0) {
struct surface_molecule ***tiles_tmp;
unsigned int *idx_tmp;
struct wall **walls_tmp;
/* allocate memory to hold array of pointers to remaining free tiles
*/
tiles_tmp =
CHECKED_MALLOC_ARRAY(struct surface_molecule **, n_clear,
"surface molecule placement tiles array");
idx_tmp = CHECKED_MALLOC_ARRAY(
unsigned int, n_clear,
"surface molecule placement indices array");
walls_tmp =
CHECKED_MALLOC_ARRAY(struct wall *, n_clear,
"surface molecule placement walls array");
n_slot = 0;
for (unsigned int n_sm = 0; n_sm < n_free_sm; n_sm++) {
if (*tiles[n_sm] == NULL) {
tiles_tmp[n_slot] = tiles[n_sm];
idx_tmp[n_slot] = idx[n_sm];
walls_tmp[n_slot++] = walls[n_sm];
}
}
/* free original array of pointers to all free tiles */
free(tiles);
free(idx);
free(walls);
tiles = tiles_tmp;
idx = idx_tmp;
walls = walls_tmp;
n_free_sm = n_free_sm - n_set;
}
/* update n_occupied for each surface molecule grid */
for (int n_wall = 0; n_wall < rp->membership->nbits; n_wall++) {
if (get_bit(rp->membership, n_wall)) {
struct surface_grid *sg = objp->wall_p[n_wall]->grid;
if (sg != NULL) {
sg->n_occupied = 0;
for (unsigned int n_tile = 0; n_tile < sg->n_tiles; ++n_tile) {
if (sg->sm_list[n_tile]->sm != NULL)
sg->n_occupied++;
}
}
}
}
}
}
/* place molecules BY NUMBER when it is defined through
* DEFINE_SURFACE_CLASS */
if (rp->surf_class != NULL) {
for (struct sm_dat *smdp = rp->surf_class->sm_dat_head; smdp != NULL;
smdp = smdp->next) {
if (smdp->quantity_type == SURFMOLNUM) {
struct species *sm = smdp->sm;
short orientation;
unsigned int n_set = (unsigned int)smdp->quantity;
unsigned int n_clear = n_free_sm - n_set;
/* Compute orientation */
if (smdp->orientation > 0)
orientation = 1;
else if (smdp->orientation < 0)
orientation = -1;
else
orientation = 0;
/* Clamp n_set to number of available slots (w/ warning). */
if (n_set > n_free_sm) {
mcell_warn(
"Number of %s surface molecules to place (%d) exceeds number "
"of free surface molecule tiles (%d) in region %s[%s].\n"
"Surface molecules %s placed on all available surface "
"molecule sites.",
sm->sym->name, n_set, n_free_sm, rp->parent->sym->name,
rp->region_last_name, sm->sym->name);
n_set = n_free_sm;
n_clear = 0;
}
no_printf("distribute %d of surface molecule %s\n", n_set,
sm->sym->name);
no_printf("n_set = %d n_clear = %d n_free_sm = %d\n", n_set,
n_clear, n_free_sm);
/* if filling more than half the free tiles
init all with bread_crumbs
choose which tiles to free again
and then convert remaining bread_crumbs to actual molecules */
if (n_set > n_free_sm / 2) {
no_printf("filling more than half the free tiles: init all with "
"bread_crumb\n");
for (unsigned int j = 0; j < n_free_sm; j++) {
*tiles[j] = bread_crumb;
}
no_printf("choose which tiles to free again\n");
for (unsigned int j = 0; j < n_clear; j++) {
/* Loop until we find a vacant tile. */
while (1) {
int slot_num = (int)(rng_dbl(world->rng) * n_free_sm);
if (*tiles[slot_num] == bread_crumb) {
*tiles[slot_num] = NULL;
break;
}
}
}
no_printf("convert remaining bread_crumbs to actual molecules\n");
for (unsigned int j = 0; j < n_free_sm; j++) {
if (*tiles[j] == bread_crumb) {
struct periodic_image periodic_box = {0, 0, 0};
struct vector3 pos3d = {0, 0, 0};
struct surface_molecule *new_sm = place_single_molecule(
world, walls[j], idx[j], sm, 0, flags, orientation, 0, 0, 0,
&periodic_box, &pos3d);
if (trigger_unimolecular(
world->reaction_hash, world->rx_hashsize, sm->hashval,
(struct abstract_molecule *)new_sm) != NULL ||
(sm->flags & CAN_SURFWALL) != 0) {
new_sm->flags |= ACT_REACT;
}
}
}
} else { /* just fill only the tiles we need */
no_printf("fill only the tiles we need\n");
for (unsigned int j = 0; j < n_set; j++) {
/* Loop until we find a vacant tile. */
while (1) {
int slot_num = (int)(rng_dbl(world->rng) * n_free_sm);
if (*tiles[slot_num] == NULL) {
struct periodic_image periodic_box = {0, 0, 0};
struct vector3 pos3d = {0, 0, 0};
struct surface_molecule *new_sm = place_single_molecule(
world, walls[slot_num], idx[slot_num], sm, 0, flags,
orientation, 0, 0, 0, &periodic_box, &pos3d);
if (trigger_unimolecular(
world->reaction_hash, world->rx_hashsize,
sm->hashval,
(struct abstract_molecule *)new_sm) != NULL ||
(sm->flags & CAN_SURFWALL) != 0) {
new_sm->flags |= ACT_REACT;
}
break;
}
}
}
}
if (n_clear > 0) {
struct surface_molecule ***tiles_tmp;
unsigned int *idx_tmp;
struct wall **walls_tmp;
/* allocate memory to hold array of pointers to remaining free
* tiles */
tiles_tmp = CHECKED_MALLOC_ARRAY(
struct surface_molecule **, n_clear,
"surface molecule placement tiles array");
idx_tmp = CHECKED_MALLOC_ARRAY(
unsigned int, n_clear,
"surface molecule placement indices array");
walls_tmp = CHECKED_MALLOC_ARRAY(
struct wall *, n_clear,
"surface molecule placement walls array");
n_slot = 0;
for (unsigned int n_sm = 0; n_sm < n_free_sm; n_sm++) {
if (*tiles[n_sm] == NULL) {
tiles_tmp[n_slot] = tiles[n_sm];
idx_tmp[n_slot] = idx[n_sm];
walls_tmp[n_slot++] = walls[n_sm];
}
}
/* free original array of pointers to all free tiles */
free(tiles);
free(idx);
free(walls);
tiles = tiles_tmp;
idx = idx_tmp;
walls = walls_tmp;
n_free_sm = n_free_sm - n_set;
}
/* update n_occupied for each surface molecule grid */
for (int n_wall = 0; n_wall < rp->membership->nbits; n_wall++) {
if (get_bit(rp->membership, n_wall)) {
struct surface_grid *sg = objp->wall_p[n_wall]->grid;
if (sg != NULL) {
sg->n_occupied = 0;
for (unsigned int n_tile = 0; n_tile < sg->n_tiles;
++n_tile) {
if (sg->sm_list[n_tile]->sm != NULL)
sg->n_occupied++;
}
}
}
}
}
}
} /* end of if (rp->surf_clas != NULL) */
/* free array of pointers to all free tiles */
if (tiles != NULL) {
free(tiles);
}
if (idx != NULL) {
free(idx);
}
if (walls != NULL) {
free(walls);
}
} /* end if (world->chkpt_init) */
}
no_printf("Done initializing surface molecules by number.\n");
return 0;
}
/***************************************************************************
rel_expr_grab_obj:
In: release expression
place to allocate memory for temporary void_list
Out: a linked list containing all the objects referred to in the
release expression (including duplcates), or NULL if there are
no such objects.
***************************************************************************/
/* Not the most efficient due to slow merging, but it works. */
static struct void_list *rel_expr_grab_obj(struct release_evaluator *root,
struct mem_helper *voidmem) {
struct void_list *vl = NULL;
struct void_list *vr = NULL;
if (root->left != NULL) {
if (root->op & REXP_LEFT_REGION) {
vl = (struct void_list *)CHECKED_MEM_GET(voidmem, "temporary list for region release");
if (vl == NULL)
return NULL;
vl->data = ((struct region *)(root->left))->parent;
vl->next = NULL;
} else
vl = (struct void_list *)rel_expr_grab_obj((struct release_evaluator *)root->left, voidmem);
}
if (root->right != NULL) {
if (root->op & REXP_RIGHT_REGION) {
vr = (struct void_list *)CHECKED_MEM_GET(voidmem, "temporary list for region release");
if (vr == NULL)
return NULL;
vr->data = ((struct region *)(root->right))->parent;
vr->next = NULL;
} else
vr = (struct void_list *)rel_expr_grab_obj((struct release_evaluator *)root->right, voidmem);
}
if (vl == NULL) {
if (vr == NULL)
return NULL;
return vr;
} else if (vr == NULL) {
return vl;
} else {
struct void_list *vp;
for (vp = vl; vp->next != NULL; vp = vp->next) {
}
vp->next = vr;
return vl;
}
return NULL;
}
/***************************************************************************
find_unique_rev_objects:
In: release expression
place to store the number of unique objects we find
Out: an array of pointers to each object listed in the release
expression (no duplicates), or NULL if out of memory. The
second argument is set to the length of the array.
***************************************************************************/
static struct geom_object **find_unique_rev_objects(struct release_evaluator *root,
int *n) {
struct geom_object **o_array;
struct void_list *vp, *vq;
struct mem_helper *voidmem;
int n_unique;
voidmem = create_mem(sizeof(struct void_list), 1024);
if (voidmem == NULL)
mcell_allocfailed("Failed to create temporary list memory pool.");
vp = rel_expr_grab_obj(root, voidmem);
if (vp == NULL)
return NULL;
vp = void_list_sort(vp);
for (n_unique = 1, vq = vp; vq != NULL && vq->next != NULL;
vq = vq->next, n_unique++) {
while (vq->data == vq->next->data) {
vq->next = vq->next->next;
if (vq->next == NULL)
break;
}
}
if (vq == NULL)
n_unique--;
*n = n_unique;
o_array = CHECKED_MALLOC_ARRAY(struct geom_object *, n_unique,
"object array for region release");
vq = vp;
for (unsigned int n_obj = 0; vq != NULL; vq = vq->next, ++n_obj)
o_array[n_obj] = (struct geom_object *)vq->data;
delete_mem(voidmem);
return o_array;
}
/***************************************************************************
eval_rel_region_expr:
In: release expression for a 2D region release
the number of distinct objects in the world listed in the expression
array of pointers to each of those objects
array of pointers to bit arrays specifying which walls of each
object are included in this release
Out: 0 on success, 1 on failure. On success, the bit arrays are set
so that they indicate which walls of each object are included in
this release site.
***************************************************************************/
static int eval_rel_region_expr(struct release_evaluator *expr, int n,
struct geom_object **objs,
struct bit_array **result) {
char bit_op;
if (expr->left != NULL) {
if (expr->op & REXP_LEFT_REGION) {
int pos = void_array_search((void **)objs, n,
((struct region *)(expr->left))->parent);
result[pos] =
duplicate_bit_array(((struct region *)(expr->left))->membership);
if (result[pos] == NULL)
return 1;
} else {
if (eval_rel_region_expr((struct release_evaluator *)expr->left, n, objs, result))
return 1;
}
if (expr->right == NULL) {
if (expr->op & REXP_NO_OP)
return 0;
else
return 1;
}
if (expr->op & REXP_RIGHT_REGION) {
int pos = void_array_search((void **)objs, n,
((struct region *)(expr->right))->parent);
if (result[pos] == NULL) {
result[pos] =
duplicate_bit_array(((struct region *)(expr->right))->membership);
if (result[pos] == NULL)
return 1;
} else {
if (expr->op & REXP_UNION)
bit_op = '|';
else if (expr->op & REXP_SUBTRACTION)
bit_op = '-';
else if (expr->op & REXP_INTERSECTION)
bit_op = '&';
else
return 1;
bit_operation(result[pos], ((struct region *)(expr->right))->membership,
bit_op);
}
} else {
std::vector<struct bit_array*> res2(n);
for (int i = 0; i < n; i++)
res2[i] = NULL;
if (eval_rel_region_expr((struct release_evaluator *)expr->right, n, objs, &res2[0]))
return 1;
for (int i = 0; i < n; i++) {
if (res2[i] == NULL)
continue;
if (result[i] == NULL)
result[i] = res2[i];
else {
if (expr->op & REXP_UNION)
bit_op = '|';
else if (expr->op & REXP_SUBTRACTION)
bit_op = '-';
else if (expr->op & REXP_INTERSECTION)
bit_op = '&';
else
return 1;
bit_operation(result[i], res2[i], bit_op);
free_bit_array(res2[i]);
}
}
}
} else
return 1; /* Left should always have something! */
return 0;
}
/***************************************************************************
init_rel_region_data_2d:
In: release data for a release of 2D molecules onto a region
Out: 0 on success, 1 on failure. A summary of all potentially available
space over all objects contained in the region expression is
generated and stored in arrays (typically of length equal to the
number of walls in the region expression).
***************************************************************************/
static int init_rel_region_data_2d(struct release_site_obj *rsop,
struct release_region_data *rrd) {
rrd->owners = find_unique_rev_objects(rrd->expression, &(rrd->n_objects));
if (rrd->owners == NULL)
mcell_error("No objects were found matching the 2-D region release request "
"for release site '%s'.",
rsop->name);
rrd->in_release =
CHECKED_MALLOC_ARRAY(struct bit_array *, rrd->n_objects,
"region membership array for 2D region release");
for (int n_object = 0; n_object < rrd->n_objects; ++n_object)
rrd->in_release[n_object] = NULL;
if (eval_rel_region_expr(rrd->expression, rrd->n_objects, rrd->owners,
rrd->in_release))
mcell_error("Could not evaluate region expression for release site '%s'.",
rsop->name);
for (int n_object = 0; n_object < rrd->n_objects; n_object++) {
if (rrd->owners[n_object] == NULL)
mcell_internal_error("Object %d of %d in region expression for release "
"site '%s' was not found!",
n_object + 1, rrd->n_objects, rsop->name);
}
rrd->walls_per_obj = CHECKED_MALLOC_ARRAY(
int, rrd->n_objects, "wall counts for 2D region release");
rrd->n_walls_included = 0;
for (int n_object = 0; n_object < rrd->n_objects; ++n_object) {
if (rrd->in_release[n_object] == NULL)
rrd->walls_per_obj[n_object] = 0;
else
rrd->walls_per_obj[n_object] = count_bits(rrd->in_release[n_object]);
rrd->n_walls_included += rrd->walls_per_obj[n_object];
}
rrd->cum_area_list =
CHECKED_MALLOC_ARRAY(double, rrd->n_walls_included,
"cumulative area list for 2D region release");
rrd->wall_index = CHECKED_MALLOC_ARRAY(int, rrd->n_walls_included,
"wall indices for 2D region release");
rrd->obj_index = CHECKED_MALLOC_ARRAY(int, rrd->n_walls_included,
"object indices for 2D region release");
unsigned int n_wall_overall = 0;
for (int n_object = 0; n_object < rrd->n_objects; ++n_object) {
if (rrd->walls_per_obj[n_object] == 0)
continue;
int owner_type = rrd->owners[n_object]->object_type;
if (owner_type != POLY_OBJ && owner_type != BOX_OBJ)
mcell_internal_error("Found a region on an object which is neither a box "
"nor a polygon (type=%d).",
owner_type);
struct polygon_object *po =
(struct polygon_object *)(rrd->owners[n_object]->contents);
int n_walls = po->n_walls;
for (int n_wall = 0; n_wall < n_walls; ++n_wall) {
if (get_bit(rrd->in_release[n_object], n_wall)) {
rrd->cum_area_list[n_wall_overall] =
rrd->owners[n_object]->wall_p[n_wall]->area;
rrd->obj_index[n_wall_overall] = n_object;
rrd->wall_index[n_wall_overall] = n_wall;
++n_wall_overall;
}
}
}
for (int n_wall = 1; n_wall < rrd->n_walls_included; n_wall++) {
rrd->cum_area_list[n_wall] += rrd->cum_area_list[n_wall - 1];
}
return 0;
}
/***************************************************************************
create_region_bbox:
In: a region
Out: pointer to a 2-element array contining the LLF and URB corners of
a bounding box around the region, or NULL if out of memory.
***************************************************************************/
struct vector3 *create_region_bbox(struct region *r) {
struct vector3 *bbox =
CHECKED_MALLOC_ARRAY(struct vector3, 2, "region bounding box");
int found_first_wall = 0;
for (int n_wall = 0; n_wall < r->membership->nbits; ++n_wall) {
if (get_bit(r->membership, n_wall)) {
if (!found_first_wall) {
bbox[0].x = bbox[1].x = r->parent->wall_p[n_wall]->vert[0]->x;
bbox[0].y = bbox[1].y = r->parent->wall_p[n_wall]->vert[0]->y;
bbox[0].z = bbox[1].z = r->parent->wall_p[n_wall]->vert[0]->z;
found_first_wall = 1;
}
for (unsigned int n_vert = 0; n_vert < 3; ++n_vert) {
struct vector3 *v = r->parent->wall_p[n_wall]->vert[n_vert];
if (bbox[0].x > v->x)
bbox[0].x = v->x;
else if (bbox[1].x < v->x)
bbox[1].x = v->x;
if (bbox[0].y > v->y)
bbox[0].y = v->y;
else if (bbox[1].y < v->y)
bbox[1].y = v->y;
if (bbox[0].z > v->z)
bbox[0].z = v->z;
else if (bbox[1].z < v->z)
bbox[1].z = v->z;
}
}
}
return bbox;
}
/***************************************************************************
eval_rel_region_bbox:
In: release expression for a 3D region release
place to store LLF corner of the bounding box for the release
place to store URB corner
Out: 0 on success, 1 on failure. Bounding box is set based on release
expression (based boolean intersection of bounding boxes for each
region). The function reports failure if any region is unclosed.
***************************************************************************/
static int eval_rel_region_bbox(struct release_evaluator *expr,
struct vector3 *llf, struct vector3 *urb) {
struct region *r;
int count_regions_flag = 1;
if (expr->left != NULL) {
if (expr->op & REXP_LEFT_REGION) {
r = (struct region *)(expr->left);
if (r->bbox == NULL)
r->bbox = create_region_bbox(r);
llf->x = r->bbox[0].x;
llf->y = r->bbox[0].y;
llf->z = r->bbox[0].z;
urb->x = r->bbox[1].x;
urb->y = r->bbox[1].y;
urb->z = r->bbox[1].z;
if (r->manifold_flag == MANIFOLD_UNCHECKED) {
if (is_manifold(r, count_regions_flag))
r->manifold_flag = IS_MANIFOLD;
else
mcell_error(
"Cannot release a 3D molecule inside the unclosed region '%s'.",
r->sym->name);
}
} else {
if (eval_rel_region_bbox((struct release_evaluator *)expr->left, llf, urb))
return 1;
}
if (expr->right == NULL) {
if (expr->op & REXP_NO_OP)
return 0;
else
mcell_internal_error(
"Right subtree of release expression is unexpectedly NULL.");
}
if (expr->op & REXP_SUBTRACTION)
return 0;
else {
struct vector3 llf2;
struct vector3 urb2;
if (expr->op & REXP_RIGHT_REGION) {
r = (struct region *)(expr->right);
if (r->manifold_flag == MANIFOLD_UNCHECKED) {
if (is_manifold(r, count_regions_flag))
r->manifold_flag = IS_MANIFOLD;
else
mcell_error(
"Cannot release a 3D molecule inside the unclosed region '%s'.",
r->sym->name);
}
if (r->bbox == NULL)
r->bbox = create_region_bbox(r);
llf2.x = r->bbox[0].x;
llf2.y = r->bbox[0].y;
llf2.z = r->bbox[0].z;
urb2.x = r->bbox[1].x;
urb2.y = r->bbox[1].y;
urb2.z = r->bbox[1].z;
} else {
if (eval_rel_region_bbox((struct release_evaluator *)expr->right, &llf2, &urb2))
return 1;
}
if (expr->op & REXP_UNION) {
if (llf->x > llf2.x)
llf->x = llf2.x;
if (llf->y > llf2.y)
llf->y = llf2.y;
if (llf->z > llf2.z)
llf->z = llf2.z;
if (urb->x < urb2.x)
urb->x = urb2.x;
if (urb->y < urb2.y)
urb->y = urb2.y;
if (urb->z < urb2.z)
urb->z = urb2.z;
} else if (expr->op & (REXP_INTERSECTION)) {
if (llf->x < llf2.x)
llf->x = llf2.x;
if (llf->y < llf2.y)
llf->y = llf2.y;
if (llf->z < llf2.z)
llf->z = llf2.z;
if (urb->x > urb2.x)
urb->x = urb2.x;
if (urb->y > urb2.y)
urb->y = urb2.y;
if (urb->z > urb2.z)
urb->z = urb2.z;
} else
mcell_internal_error("Release expression contains an unknown or "
"unexpected operator: (%d).",
expr->op);
}
} else
mcell_internal_error(
"Left subtree of release expression is unexpectedly NULL.");
return 0;
}
/***************************************************************************
init_rel_region_data_3d:
In: release region data structure
Out: 0 on success, 1 on failure, -1 if there is no volume contained
in the release (user error). The release must be for a 3D release
of molecules. eval_rel_region_bbox is called to perform the
initialization.
***************************************************************************/
static int init_rel_region_data_3d(struct release_region_data *rrd) {
rrd->n_walls_included = 0;
if (eval_rel_region_bbox(rrd->expression, &(rrd->llf), &(rrd->urb)))
return 1;
if (rrd->llf.x >= rrd->urb.x || rrd->llf.y >= rrd->urb.y ||
rrd->llf.z >= rrd->urb.z) {
return -1; /* Special signal to print out "nothing in here" error msg */
}
return 0;
}
/***************************************************************************
output_regrel_eval_tree:
In: file to print tree on
prefix string to put before the current branch of the tree
prefix character for left half of current branch
prefix character for right half of current branch
release expression
Out: no return value. The tree is printed to the file.
***************************************************************************/
static void output_relreg_eval_tree(FILE *f, const char *prefix, char cA, char cB,
struct release_evaluator *expr) {
size_t l = strlen(prefix);
char my_op;
if (expr->op & REXP_NO_OP) {
fprintf(f, "%s >%s\n", prefix, ((struct region *)(expr->left))->sym->name);
} else {
char* prefixA = new char[l + 3];
char* prefixB = new char[l + 3];
// l+1 is only to silence warning output truncated before terminating nul copying as many
// bytes from a string as its length [-Wstringop-truncation], l woudl suffice
strncpy(prefixA, prefix, l+1);
strncpy(prefixB, prefix, l+1);
prefixA[l] = cA;
prefixB[l] = cB;
prefixA[l + 1] = prefixB[l + 1] = ' ';
prefixA[l + 2] = prefixB[l + 2] = 0;
if (expr->op & REXP_LEFT_REGION) {
fprintf(f, "%s >%s\n", prefix,
((struct region *)(expr->left))->sym->name);
} else {
output_relreg_eval_tree(f, prefixA, ' ', '|', (struct release_evaluator *)expr->left);
}
my_op = '?';
if (expr->op & REXP_UNION)
my_op = '+';
else if (expr->op & REXP_INTERSECTION)
my_op = '*';
else if (expr->op & REXP_SUBTRACTION)
my_op = '-';
fprintf(f, "%s%c\n", prefix, my_op);
if (expr->op & REXP_RIGHT_REGION) {
fprintf(f, "%s >%s\n", prefix,
((struct region *)(expr->left))->sym->name);
} else {
output_relreg_eval_tree(f, prefixA, '|', ' ', (struct release_evaluator *)expr->right);
}
delete prefixA;
delete prefixB;
}
}
/***************************************************************************
init_dynamic_geometry:
In: state: MCell state
Out: 0 on success, 1 on failure. Dynamic geometry scheduler is created.
***************************************************************************/
int init_dynamic_geometry(struct volume *state) {
state->dynamic_geometry_scheduler = create_scheduler(1.0, 100.0, 100, 0.0);
if (state->dynamic_geometry_scheduler == NULL) {
mcell_allocfailed_nodie("Failed to create geometry scheduler.");
return 1;
}
return 0;
}
/***************************************************************************
schedule_dynamic_geometry:
In: state: MCell state
Out: 0 on success, 1 on failure. Dynamic geometry "events" that were parsed
are now scheduled. In other words, if the geometry was specified to
change in the MDL, we schedule all changes now.
***************************************************************************/
int schedule_dynamic_geometry(struct mdlparse_vars *parse_state) {
struct volume *state = parse_state->vol;
// Process the DG text file (e.g. times and corresponding geometry) and store
// it in state->dynamic_geometry_events_mem. Then preliminary parse each
// geometry file (mainly to check for added or removed objects).
if ((state->dynamic_geometry_filename != NULL) &&
(add_dynamic_geometry_events(
parse_state,
state->dynamic_geometry_filename,
state->time_unit,
state->dynamic_geometry_events_mem,
&state->dynamic_geometry_head))) {
mcell_error("Failed to load dynamic geometry from file '%s'.",
state->dynamic_geometry_filename);
free(state->dynamic_geometry_filename);
state->dynamic_geometry_filename = NULL;
return 1;
}
// we can free up the
free(state->dynamic_geometry_filename);
state->dynamic_geometry_filename = NULL;
// This is the actual scheduling.
struct dg_time_filename *dg_time_fname, *dg_time_fname_next;
for (dg_time_fname = state->dynamic_geometry_head; dg_time_fname != NULL;
dg_time_fname = dg_time_fname_next) {
dg_time_fname_next = dg_time_fname->next; /* schedule_add overwrites 'next' */
if (schedule_add(state->dynamic_geometry_scheduler, dg_time_fname)) {
mcell_allocfailed(
"Failed to add item to schedule for dynamic geometry.");
}
}
return 0;
}
/***************************************************************************
init_releases:
In: nothing
Out: 0 on success, 1 on failure. All release sites are initialized.
Right now, the only release sites that need to be initialized are
releases on regions.
***************************************************************************/
int init_releases(struct schedule_helper *releaser) {
struct release_event_queue *req;
struct abstract_element *ae;
struct schedule_helper *sh;
int i;
for (sh = releaser; sh != NULL; sh = sh->next_scale) {
for (i = -1; i < sh->buf_len; i++) {
for (ae = (i == -1) ? sh->current : sh->circ_buf_head[i]; ae != NULL;
ae = ae->next) {
req = (struct release_event_queue *)ae;
switch ((int)req->release_site->release_shape) {
case SHAPE_REGION:
if (req->release_site->mol_type == NULL)
mcell_error("Molecule type was not specified for the region "
"release site '%s'.",
req->release_site->name);
if ((req->release_site->mol_type->flags & NOT_FREE) == 0) {
switch (init_rel_region_data_3d(req->release_site->region_data)) {
case 0:
break;
case -1:
mcell_warn("Region release site '%s' is empty! Ignoring! "
"Evaluation tree:\n",
req->release_site->name);
output_relreg_eval_tree(
mcell_get_error_file(), " ", ' ', ' ',
req->release_site->region_data->expression);
req->release_site->release_number_method = CONSTNUM;
req->release_site->release_number = 0;
break;
default:
mcell_error("Unexpected error while initializing 3-D region "
"releases for release site '%s'.",
req->release_site->name);
/*break;*/
}
} else {
if (init_rel_region_data_2d(req->release_site,
req->release_site->region_data))
mcell_error("Unexpected error while initializing 2-D region "
"releases for release site '%s'.",
req->release_site->name);
}
break;
case SHAPE_LIST:
if (req->release_site->mol_list == NULL)
mcell_error("Molecule positions for the LIST release site '%s' are "
"not specified.",
req->release_site->name);
break;
case SHAPE_SPHERICAL:
case SHAPE_CUBIC:
case SHAPE_ELLIPTIC:
case SHAPE_RECTANGULAR:
case SHAPE_SPHERICAL_SHELL:
/* geometrical release sites */
if (req->release_site->mol_type == NULL)
mcell_error(
"Molecule type for the release site '%s' is not specified.",
req->release_site->name);
if (req->release_site->diameter == NULL)
mcell_error("Diameter for the geometrical shape release site '%s' "
"is not specified.",
req->release_site->name);
break;
case SHAPE_UNDEFINED:
default:
UNHANDLED_CASE(req->release_site->release_shape);
}
}
}
}
return 0;
}
/***************************************************************************
publish_special_reactions_report:
In: species that is a SURFACE_CLASS
lists of names of volume and surface molecules
Out: None. If species is a surface (surface class) and special reactions
like TRANSPARENT, REFLECTIVE or ABSORPTIVE are defined for it,
the reactions report is printed out.
***************************************************************************/
void publish_special_reactions_report(struct species *sp,
struct name_list *vol_species_name_list,
struct name_list *surf_species_name_list,
int n_species,
struct species **species_list) {
struct name_orient *no;
FILE *log_file;
struct species *spec;
/* orientation of ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES
*/
int all_mol_orient = INT_MIN;
int all_volume_mol_orient = INT_MIN;
int all_surface_mol_orient = INT_MIN;
/* flags */
int refl_mols_all_volume_mol = 0;
int refl_mols_all_surface_mol = 0;
int refl_mols_all_mol = 0;
int transp_mols_all_volume_mol = 0;
int transp_mols_all_surface_mol = 0;
int transp_mols_all_mol = 0;
int absorb_mols_all_volume_mol = 0;
int absorb_mols_all_surface_mol = 0;
int absorb_mols_all_mol = 0;
struct name_list *nl;
int surf_refl_title_printed; /*flag*/
int borders_refl_title_printed; /*flag*/
int surf_transp_title_printed; /*flag*/
int borders_transp_title_printed; /*flag*/
int surf_absorb_title_printed; /*flag*/
int borders_absorb_title_printed; /*flag*/
/* Below I will employ following set of rules for printing out
the relative orientations of surface classes and molecules;
1. The orientation of surface class is always printed out as {1}.
2. The orientation of molecule is printed out
as {1} when it is positive, {-1} when it is negative,
and {0} when it is zero, or absent.
*/
log_file = mcell_get_log_file();
if (sp->refl_mols != NULL) {
/* search for ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES */
for (no = sp->refl_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
refl_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
refl_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
refl_mols_all_mol = 1;
}
}
if ((refl_mols_all_volume_mol || refl_mols_all_mol) &&
(vol_species_name_list != NULL)) {
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are REFLECTIVE "
"for volume molecules ",
sp->sym->name);
for (nl = vol_species_name_list; nl != NULL; nl = nl->next) {
if (refl_mols_all_volume_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_volume_mol_orient);
} else if (refl_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
if ((refl_mols_all_surface_mol || refl_mols_all_mol) &&
(surf_species_name_list != NULL)) {
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" are "
"REFLECTIVE for surface molecules ",
sp->sym->name);
for (nl = surf_species_name_list; nl != NULL; nl = nl->next) {
if (refl_mols_all_surface_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_surface_mol_orient);
} else if (refl_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
surf_refl_title_printed = 0;
borders_refl_title_printed = 0;
/* First go through all volume molecules */
if ((!refl_mols_all_mol) && (!refl_mols_all_volume_mol)) {
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!surf_refl_title_printed) {
surf_refl_title_printed = 1;
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are "
"REFLECTIVE for volume molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (surf_refl_title_printed)
fprintf(log_file, ".\n");
}
/* Now go through all surface molecules */
if ((!refl_mols_all_mol) && (!refl_mols_all_surface_mol)) {
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!borders_refl_title_printed) {
borders_refl_title_printed = 1;
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" "
"are REFLECTIVE for surface molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (borders_refl_title_printed)
fprintf(log_file, ".\n");
}
}
if (sp->transp_mols != NULL) {
/* search for ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES */
for (no = sp->transp_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
transp_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
transp_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
transp_mols_all_mol = 1;
}
}
if ((transp_mols_all_volume_mol || transp_mols_all_mol) &&
(vol_species_name_list != NULL)) {
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are TRANSPARENT "
"for volume molecules ",
sp->sym->name);
for (nl = vol_species_name_list; nl != NULL; nl = nl->next) {
if (transp_mols_all_volume_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_volume_mol_orient);
} else if (transp_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
if ((transp_mols_all_surface_mol || transp_mols_all_mol) &&
(surf_species_name_list != NULL)) {
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" are "
"TRANSPARENT for surface molecules ",
sp->sym->name);
for (nl = surf_species_name_list; nl != NULL; nl = nl->next) {
if (transp_mols_all_surface_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_surface_mol_orient);
} else if (transp_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
surf_transp_title_printed = 0;
borders_transp_title_printed = 0;
/* First go through all volume molecules */
if ((!transp_mols_all_mol) && (!transp_mols_all_volume_mol)) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!surf_transp_title_printed) {
surf_transp_title_printed = 1;
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are "
"TRANSPARENT for volume molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (surf_transp_title_printed)
fprintf(log_file, ".\n");
}
/* Now go through all surface molecules */
if ((!transp_mols_all_mol) && (!transp_mols_all_surface_mol)) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!borders_transp_title_printed) {
borders_transp_title_printed = 1;
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" "
"are TRANSPARENT for surface molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (borders_transp_title_printed)
fprintf(log_file, ".\n");
}
}
if (sp->absorb_mols != NULL) {
/* search for ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES */
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
absorb_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
absorb_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
absorb_mols_all_mol = 1;
}
}
if ((absorb_mols_all_volume_mol || absorb_mols_all_mol) &&
(vol_species_name_list != NULL)) {
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are ABSORPTIVE "
"for volume molecules ",
sp->sym->name);
for (nl = vol_species_name_list; nl != NULL; nl = nl->next) {
if (absorb_mols_all_volume_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_volume_mol_orient);
} else if (absorb_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
if ((absorb_mols_all_surface_mol || absorb_mols_all_mol) &&
(surf_species_name_list != NULL)) {
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" are "
"ABSORPTIVE for surface molecules ",
sp->sym->name);
for (nl = surf_species_name_list; nl != NULL; nl = nl->next) {
if (absorb_mols_all_surface_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_surface_mol_orient);
} else if (absorb_mols_all_mol) {
fprintf(log_file, "%s{%d}", nl->name, all_mol_orient);
}
if (nl->next != NULL)
fprintf(log_file, " ");
else
fprintf(log_file, ".");
}
}
fprintf(log_file, "\n");
surf_absorb_title_printed = 0;
borders_absorb_title_printed = 0;
/* First go through all volume molecules */
if ((!absorb_mols_all_mol) && (!absorb_mols_all_volume_mol)) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!surf_absorb_title_printed) {
surf_absorb_title_printed = 1;
fprintf(log_file, "Surfaces with surface class \"%s{1}\" are "
"ABSORPTIVE for volume molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (surf_absorb_title_printed)
fprintf(log_file, ".\n");
}
/* Now go through all surface molecules */
if ((!absorb_mols_all_mol) && (!absorb_mols_all_surface_mol)) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if (strcmp(no->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (!borders_absorb_title_printed) {
borders_absorb_title_printed = 1;
fprintf(log_file, "Borders of regions with surface class \"%s{1}\" "
"are ABSORPTIVE for surface molecules ",
sp->sym->name);
}
fprintf(log_file, "%s{%d}", no->name, no->orient);
if (no->next != NULL)
fprintf(log_file, " ");
}
if (borders_absorb_title_printed)
fprintf(log_file, ".\n");
}
}
if ((sp->refl_mols != NULL) || (sp->transp_mols != NULL) ||
(sp->absorb_mols != NULL)) {
fprintf(log_file, "\n");
}
}
/***************************************************************************
check_for_conflicts_in_surface_class:
In: species that is a SURFACE_CLASS
Out: None. If species is a SURFACE_CLASS we check for conflicting
properties, like ABSORPTIVE/TRANSPARENT for the same molecule.
Also we search for conflicts like combination of
TRANSPARENT=A and REFLECTIVE=ALL_MOLECULES.
The combination of regular reaction declared through
DEFINE_REACTIONS and special reaction (TRANSPARENT/ABSORPTIVE)
is not allowed for volume molecule.
If we find the conflicts, the fatal error is generated.
***************************************************************************/
void check_for_conflicts_in_surface_class(struct volume *world,
struct species *sp) {
struct name_orient *no, *no1, *no2;
/* orientation of ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES
*/
int all_mol_orient = INT_MIN;
int all_volume_mol_orient = INT_MIN;
int all_surface_mol_orient = INT_MIN;
/* flags */
int refl_mols_all_volume_mol = 0;
int refl_mols_all_surface_mol = 0;
int refl_mols_all_mol = 0;
int transp_mols_all_volume_mol = 0;
int transp_mols_all_surface_mol = 0;
int transp_mols_all_mol = 0;
int absorb_mols_all_volume_mol = 0;
int absorb_mols_all_surface_mol = 0;
int absorb_mols_all_mol = 0;
struct species *spec;
if ((sp->flags & IS_SURFACE) == 0)
return;
/* search for ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES */
if (sp->refl_mols != NULL) {
for (no = sp->refl_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
refl_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
refl_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
refl_mols_all_mol = 1;
}
}
}
if (refl_mols_all_mol && refl_mols_all_volume_mol) {
mcell_error(
"REFLECTIVE properties are specified through the use of both"
" ALL_MOLECULES and ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
sp->sym->name);
}
if (refl_mols_all_mol && refl_mols_all_surface_mol) {
mcell_error(
"REFLECTIVE properties are specified through the use of both"
" ALL_MOLECULES and ALL_SURFACE_MOLECULES within the surface class "
"'%s'.",
sp->sym->name);
}
if (sp->transp_mols != NULL) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
transp_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
transp_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
transp_mols_all_mol = 1;
}
}
}
if (transp_mols_all_mol && transp_mols_all_volume_mol) {
mcell_error(
"TRANSPARENT properties are specified through the use of both "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
sp->sym->name);
}
if (transp_mols_all_mol && transp_mols_all_surface_mol) {
mcell_error(
"TRANSPARENT properties are specified through the use of both "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES within the surface class "
"'%s'.",
sp->sym->name);
}
if (sp->absorb_mols != NULL) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
all_volume_mol_orient = no->orient;
absorb_mols_all_volume_mol = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
all_surface_mol_orient = no->orient;
absorb_mols_all_surface_mol = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
all_mol_orient = no->orient;
absorb_mols_all_mol = 1;
}
}
}
if (absorb_mols_all_mol && absorb_mols_all_volume_mol) {
mcell_error("ABSORPTIVE properties are specified through the use of both"
" ALL_MOLECULES and ALL_VOLUME_MOLECULES within the surface "
"class '%s'.",
sp->sym->name);
}
if (absorb_mols_all_mol && absorb_mols_all_surface_mol) {
mcell_error("ABSORPTIVE properties are specified through the use of both"
" ALL_MOLECULES and ALL_SURFACE_MOLECULES within the surface"
" class '%s'.",
sp->sym->name);
}
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if (transp_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_SURFACE_MOLECULES within the surface class"
" '%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_SURFACE_MOLECULES within the surface class"
" '%s'.",
no->name, sp->sym->name);
}
}
}
for (no = sp->transp_mols; no != NULL; no = no->next) {
if (absorb_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (absorb_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (absorb_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_SURFACE_MOLECULES within the surface class"
" '%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_SURFACE_MOLECULES within the surface class"
" '%s'.",
no->name, sp->sym->name);
}
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
if (absorb_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (absorb_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (absorb_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_SURFACE_MOLECULES within the surface class"
" '%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_surface_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((all_surface_mol_orient == no->orient) ||
(all_surface_mol_orient == 0) || (no->orient == 0)) {
mcell_error("REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified for molecule %s through "
"the use of ALL_SURFACE_MOLECULES within the surface "
"class '%s'.",
no->name, sp->sym->name);
}
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if (absorb_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("CLAMP and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (absorb_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("CLAMP and ABSORPTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("CLAMP and TRANSPARENT properties "
"are simultaneously specified for molecule %s through "
"the use of ALL_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (transp_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("CLAMP and TRANSPARENT properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_mol) {
if ((all_mol_orient == no->orient) || (all_mol_orient == 0) ||
(no->orient == 0)) {
mcell_error("CLAMP and REFLECTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_MOLECULES within the surface class '%s'.",
no->name, sp->sym->name);
}
}
if (refl_mols_all_volume_mol) {
spec =
get_species_by_name(no->name, world->n_species, world->species_list);
if (spec == NULL)
mcell_internal_error("Cannot find molecule name %s", no->name);
if (spec->flags & ON_GRID)
continue;
if ((all_volume_mol_orient == no->orient) ||
(all_volume_mol_orient == 0) || (no->orient == 0)) {
mcell_error("CLAMP and REFLECTIVE properties are "
"simultaneously specified for molecule %s through the "
"use of ALL_VOLUME_MOLECULES within the surface class "
"'%s'.",
no->name, sp->sym->name);
}
}
}
for (no1 = sp->transp_mols; no1 != NULL; no1 = no1->next) {
for (no2 = sp->absorb_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error("TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified for the same molecule %s "
"within the surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
for (no2 = sp->refl_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error("TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified for the same molecule %s "
"within the surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
for (no2 = sp->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error("TRANSPARENT and CLAMP properties are "
"simultaneously specified for the same molecule %s "
"within the surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
}
for (no1 = sp->refl_mols; no1 != NULL; no1 = no1->next) {
for (no2 = sp->absorb_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error(
"REFLECTIVE and ABSORPTIVE properties are "
"simultaneously specified for the same molecule %s within the "
"surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
for (no2 = sp->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error(
"REFLECTIVE and CLAMP properties are "
"simultaneously specified for the same molecule %s within the "
"surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
}
for (no1 = sp->absorb_mols; no1 != NULL; no1 = no1->next) {
for (no2 = sp->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no1->name, no2->name) == 0) {
if ((no1->orient == no2->orient) || (no1->orient == 0) ||
(no2->orient == 0)) {
mcell_error(
"ABSORPTIVE and CLAMP properties are "
"simultaneously specified for the same molecule %s within the "
"surface class '%s'.",
no1->name, sp->sym->name);
}
}
}
}
/* Check for combinations of ALL_MOLECULES or ALL_VOLUME_MOLECULES
with regular reactions that involve volume molecules. */
/* We will check for volume molecules only
since special reactions with surface molecules
have a meaning as reactions on the region border
and should be allowed. */
// JAC: The wording is a little odd here, but I'm assuming this means we are
// checking for something like this:
// sc { TRANSPARENT = ALL_MOLECULES; }
// combined with this:
// a; @ sc; -> b; [1e6]
u_int hash_value, hashW, hashM;
struct species *mol_sp;
struct rxn *inter;
/* flags */
int special_rx_same_orient, regular_rx_same_orient;
int count_sim_orient_rxns, i0, i1;
hashW = sp->hashval;
for (int i = 0; i < world->n_species; i++) {
if (world->species_list[i]->flags & IS_SURFACE)
continue;
mol_sp = world->species_list[i];
if (strcmp(mol_sp->sym->name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(mol_sp->sym->name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(mol_sp->sym->name, "ALL_SURFACE_MOLECULES") == 0)
continue;
if (mol_sp->flags & ON_GRID)
continue;
hashM = mol_sp->hashval;
hash_value = (hashM + hashW) & (world->rx_hashsize - 1);
/* Are there regular reactions with volume molecules? */
for (inter = world->reaction_hash[hash_value]; inter != NULL;
inter = inter->next) {
if ((inter->players[0]->flags & ON_GRID) != 0)
continue;
if (strcmp(inter->players[0]->sym->name, mol_sp->sym->name) != 0)
continue;
if (transp_mols_all_mol) {
if ((all_mol_orient == inter->geometries[0]) || (all_mol_orient == 0) ||
(inter->geometries[0] == 0)) {
if ((inter->n_reactants == 2) && (strcmp(inter->players[1]->sym->name, sp->sym->name) == 0)) {
mcell_error(
"Combination of similarly oriented TRANSPARENT reaction "
"using ALL_MOLECULES and regular reaction for molecule '%s' "
"for the same surface class '%s' is not allowed.",
inter->players[0]->sym->name, sp->sym->name);
}
}
}
if (absorb_mols_all_mol) {
if ((all_mol_orient == inter->geometries[0]) || (all_mol_orient == 0) ||
(inter->geometries[0] == 0)) {
if ((inter->n_reactants == 2) && (strcmp(inter->players[1]->sym->name, sp->sym->name) == 0)) {
mcell_error(
"Combination of similarly oriented ABSORPTIVE reaction "
"using ALL_MOLECULES and regular reaction for molecule '%s' "
"for the same surface class '%s' is not allowed.",
inter->players[0]->sym->name, sp->sym->name);
}
}
}
if (transp_mols_all_volume_mol) {
if ((all_volume_mol_orient == inter->geometries[0]) ||
(all_volume_mol_orient == 0) || (inter->geometries[0] == 0)) {
if ((inter->n_reactants == 2) && (strcmp(inter->players[1]->sym->name, sp->sym->name) == 0)) {
mcell_error(
"Combination of similarly oriented TRANSPARENT reaction "
"using ALL_VOLUME_MOLECULES and regular reaction for molecule "
"'%s' for the same surface class '%s' is not allowed.",
inter->players[0]->sym->name, sp->sym->name);
}
}
}
if (absorb_mols_all_volume_mol) {
if ((all_volume_mol_orient == inter->geometries[0]) ||
(all_volume_mol_orient == 0) || (inter->geometries[0] == 0)) {
if ((inter->n_reactants == 2) && (strcmp(inter->players[1]->sym->name, sp->sym->name) == 0)) {
mcell_error(
"Combination of similarly oriented ABSORPTIVE reaction "
"using ALL_VOLUME_MOLECULES and regular reaction for molecule "
"'%s' for the same surface class '%s' is not allowed.",
inter->players[0]->sym->name, sp->sym->name);
}
}
}
}
}
/* Below we will check for the conflicting reactions, like
A; @ surf_class; -> TRANSPARENT and
A; @ surf_class -> B[some_rate]
*/
/* We will check for volume molecules only
since special reactions with surface molecules
have a meaning as reactions on the region border
and should be allowed. */
for (no = sp->transp_mols; no != NULL; no = no->next) {
/* surface_class always has orientation {1} */
if (no->orient == 1)
special_rx_same_orient = 1;
else
special_rx_same_orient = 0;
char *mol_name = no->name;
if (strcmp(mol_name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_SURFACE_MOLECULES") == 0)
continue;
mol_sp =
get_species_by_name(mol_name, world->n_species, world->species_list);
if (mol_sp == NULL)
mcell_error("Cannot find '%s' among molecules.", mol_name);
if ((mol_sp->flags & ON_GRID) != 0)
continue;
hashM = mol_sp->hashval;
hash_value = (hashM + hashW) & (world->rx_hashsize - 1);
/* below we will compare TRANSP reaction only with
regular reaction for the same molecule. */
for (inter = world->reaction_hash[hash_value]; inter != NULL;
inter = inter->next) {
if (inter->n_pathways <= RX_SPECIAL) {
continue;
}
if ((inter->players[0] == mol_sp) && (inter->players[1] == sp)) {
if (inter->geometries[0] == inter->geometries[1]) {
regular_rx_same_orient = 1;
} else {
regular_rx_same_orient = 0;
}
if ((no->orient == 0) || (inter->geometries[0] == 0)) {
mcell_error("Combination of similarly oriented TRANSPARENT and "
"regular reactions for molecule '%s' on the same "
"surface class '%s' is not allowed.",
mol_sp->sym->name, sp->sym->name);
}
if (special_rx_same_orient && regular_rx_same_orient) {
mcell_error("Combination of similarly oriented TRANSPARENT and "
"regular reactions for molecule '%s' on the same "
"surface class '%s' is not allowed.",
mol_sp->sym->name, sp->sym->name);
}
if (!special_rx_same_orient && !regular_rx_same_orient) {
mcell_error("Combination of similarly oriented TRANSPARENT and "
"regular reactions for molecule '%s' on the same "
"surface class '%s' is not allowed.",
mol_sp->sym->name, sp->sym->name);
}
}
}
}
/* Below we will compare ABSORPTIVE reaction only with
regular reaction. The difficulty is that internally
ABSORPTIVE reaction is implemented as regular reaction
with no products. */
for (no = sp->absorb_mols; no != NULL; no = no->next) {
char *mol_name = no->name;
if (strcmp(mol_name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_SURFACE_MOLECULES") == 0)
continue;
mol_sp =
get_species_by_name(mol_name, world->n_species, world->species_list);
if (mol_sp == NULL)
mcell_error("Cannot find '%s' among molecules.", mol_name);
/* we will check for volume molecules only
since special reactions with surface molecules
have a meaning as reactions on the region border
and should be allowed. */
if ((mol_sp->flags & ON_GRID) != 0)
continue;
if (no->orient == 1)
special_rx_same_orient = 1;
else
special_rx_same_orient = 0;
hashM = mol_sp->hashval;
hash_value = (hashM + hashW) & (world->rx_hashsize - 1);
/* count similar oriented ABSORPTIVE reactions */
count_sim_orient_rxns = 0;
for (inter = world->reaction_hash[hash_value]; inter != NULL;
inter = inter->next) {
if (inter->n_pathways <= RX_SPECIAL) {
continue;
}
if ((inter->players[0] == mol_sp) && (inter->players[1] == sp)) {
if ((no->orient == inter->geometries[0]) &&
(inter->geometries[1] == 1) && (inter->n_pathways == 1)) {
i0 = inter->product_idx[0];
i1 = inter->product_idx[1];
if (((i1 - i0) == 2) && (inter->players[2] == NULL) &&
(inter->players[3] == NULL)) {
/* this is an original ABSORPTIVE reaction */
continue;
}
}
if (inter->geometries[0] == inter->geometries[1]) {
regular_rx_same_orient = 1;
} else {
regular_rx_same_orient = 0;
}
if ((no->orient == 0) || (inter->geometries[0] == 0)) {
count_sim_orient_rxns++;
} else if (special_rx_same_orient && regular_rx_same_orient) {
count_sim_orient_rxns++;
} else if (!special_rx_same_orient && !regular_rx_same_orient) {
count_sim_orient_rxns++;
}
}
if (count_sim_orient_rxns > 0) {
mcell_error("Combination of similarly oriented ABSORPTIVE reaction "
"and regular reaction for molecule '%s' on the same "
"surface class '%s' is not allowed.",
mol_name, sp->sym->name);
}
}
}
/* Internally CLAMP reaction is implemented as regular reaction */
for (no = sp->clamp_mols; no != NULL; no = no->next) {
char *mol_name = no->name;
if (strcmp(mol_name, "ALL_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_VOLUME_MOLECULES") == 0)
continue;
if (strcmp(mol_name, "ALL_SURFACE_MOLECULES") == 0)
continue;
mol_sp =
get_species_by_name(mol_name, world->n_species, world->species_list);
if (mol_sp == NULL)
mcell_error("Cannot find '%s' among molecules.", mol_name);
/* we will check for volume molecules only
since special reactions with surface molecules
have a meaning as reactions on the region border
and should be allowed. */
if ((mol_sp->flags & ON_GRID) != 0)
continue;
if (no->orient == 1)
special_rx_same_orient = 1;
else
special_rx_same_orient = 0;
hashM = mol_sp->hashval;
hash_value = (hashM + hashW) & (world->rx_hashsize - 1);
/* count similar oriented CLAMP and regular reactions */
count_sim_orient_rxns = 0;
for (inter = world->reaction_hash[hash_value]; inter != NULL;
inter = inter->next) {
if (inter->n_pathways <= RX_SPECIAL) {
continue;
}
if ((inter->players[0] == mol_sp) && (inter->players[1] == sp)) {
if ((no->orient == inter->geometries[0]) &&
(inter->geometries[1] == 1)) {
i0 = inter->product_idx[0];
i1 = inter->product_idx[1];
if (((i1 - i0) == 2) && (inter->players[2] == NULL) &&
(inter->players[3] == NULL)) {
/* this is an original CLAMP_CONC reaction */
continue;
}
if (((i1 - i0) == 2) && (inter->players[0] == inter->players[2]) &&
(inter->players[3] == NULL)) {
/* this is an original CLAMP_FLUX reaction */
continue;
}
}
if (inter->geometries[0] == inter->geometries[1]) {
regular_rx_same_orient = 1;
} else {
regular_rx_same_orient = 0;
}
if ((no->orient == 0) || (inter->geometries[0] == 0)) {
count_sim_orient_rxns++;
} else if (special_rx_same_orient && regular_rx_same_orient) {
count_sim_orient_rxns++;
} else if (!special_rx_same_orient && !regular_rx_same_orient) {
count_sim_orient_rxns++;
}
}
if (count_sim_orient_rxns > 0) {
mcell_error("Combination of similarly oriented CLAMP "
"reaction and regular reaction for molecule '%s' on the "
"same surface class '%s' is not allowed.",
mol_name, sp->sym->name);
}
}
}
}
/***************************************************************************
check_for_conflicting_surface_classes:
In: wall
Out: The wall has a linked list of surface classes. Here we check for
conflicts, like ABSORPTIVE/TRANSPARENT for the same molecule
between different surface classes. Possible application -
overlapping regions.
If we find the conflicts, the fatal error is generated.
***************************************************************************/
void check_for_conflicting_surface_classes(struct wall *w, int n_species,
struct species **species_list) {
struct surf_class_list *scl, *scl2;
struct species *sp, *sp2;
struct name_orient *no, *no2;
/* orientation of ALL_MOLECULES, ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES
*/
int sp_refl_all_mols_orient, sp_transp_all_mols_orient,
sp_absorb_all_mols_orient;
int sp_refl_all_volume_mols_orient, sp_transp_all_volume_mols_orient,
sp_absorb_all_volume_mols_orient;
int sp_refl_all_surface_mols_orient, sp_transp_all_surface_mols_orient,
sp_absorb_all_surface_mols_orient;
int sp2_refl_all_mols_orient, sp2_transp_all_mols_orient,
sp2_absorb_all_mols_orient;
int sp2_refl_all_volume_mols_orient, sp2_transp_all_volume_mols_orient,
sp2_absorb_all_volume_mols_orient;
int sp2_refl_all_surface_mols_orient, sp2_transp_all_surface_mols_orient,
sp2_absorb_all_surface_mols_orient;
/* flags */
int sp_refl_all_mols, sp_transp_all_mols, sp_absorb_all_mols;
int sp_refl_all_volume_mols, sp_transp_all_volume_mols,
sp_absorb_all_volume_mols;
int sp_refl_all_surface_mols, sp_transp_all_surface_mols,
sp_absorb_all_surface_mols;
int sp2_refl_all_mols, sp2_transp_all_mols, sp2_absorb_all_mols;
int sp2_refl_all_volume_mols, sp2_transp_all_volume_mols,
sp2_absorb_all_volume_mols;
int sp2_refl_all_surface_mols, sp2_transp_all_surface_mols,
sp2_absorb_all_surface_mols;
struct species *spec;
/* check for conflicts like TRANSPARENT/ABSORPTIVE type for the same molecule
*/
for (scl = w->surf_class_head; scl != NULL; scl = scl->next) {
sp = scl->surf_class;
for (scl2 = scl->next; scl2 != NULL; scl2 = scl2->next) {
sp2 = scl2->surf_class;
for (no = sp->transp_mols; no != NULL; no = no->next) {
for (no2 = sp2->absorb_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->refl_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and CLAMP "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
for (no2 = sp2->absorb_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->transp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and CLAMP "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
}
for (no = sp->absorb_mols; no != NULL; no = no->next) {
for (no2 = sp2->transp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->refl_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties "
"are simultaneously specified for the same molecule "
"'%s' on the same wall through the surface classes "
"'%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->clamp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and CLAMP "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
for (no2 = sp2->transp_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting CLAMP and TRANSPARENT "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->refl_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting CLAMP and REFLECTIVE "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
for (no2 = sp2->absorb_mols; no2 != NULL; no2 = no2->next) {
if (strcmp(no->name, no2->name) == 0) {
if ((no->orient == no2->orient) || (no->orient == 0) ||
(no2->orient == 0)) {
mcell_error("Conflicting CLAMP and ABSORPTIVE "
"properties are simultaneously specified for the "
"same molecule '%s' on the same wall through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
}
}
}
/* check for conflicts resulting from ALL_MOLECULES,
ALL_VOLUME_MOLECULES, ALL_SURFACE_MOLECULES keywords */
for (scl = w->surf_class_head; scl != NULL; scl = scl->next) {
sp = scl->surf_class;
sp_transp_all_mols = 0;
sp_absorb_all_mols = 0;
sp_refl_all_mols = 0;
sp_transp_all_volume_mols = 0;
sp_absorb_all_volume_mols = 0;
sp_refl_all_volume_mols = 0;
sp_transp_all_surface_mols = 0;
sp_absorb_all_surface_mols = 0;
sp_refl_all_surface_mols = 0;
sp_transp_all_mols_orient = INT_MIN;
sp_absorb_all_mols_orient = INT_MIN;
sp_refl_all_mols_orient = INT_MIN;
sp_transp_all_volume_mols_orient = INT_MIN;
sp_absorb_all_volume_mols_orient = INT_MIN;
sp_refl_all_volume_mols_orient = INT_MIN;
sp_transp_all_surface_mols_orient = INT_MIN;
sp_absorb_all_surface_mols_orient = INT_MIN;
sp_refl_all_surface_mols_orient = INT_MIN;
if (sp->refl_mols != NULL) {
for (no = sp->refl_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp_refl_all_volume_mols_orient = no->orient;
sp_refl_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp_refl_all_surface_mols_orient = no->orient;
sp_refl_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp_refl_all_mols_orient = no->orient;
sp_refl_all_mols = 1;
}
}
}
if (sp->transp_mols != NULL) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp_transp_all_volume_mols_orient = no->orient;
sp_transp_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp_transp_all_surface_mols_orient = no->orient;
sp_transp_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp_transp_all_mols_orient = no->orient;
sp_transp_all_mols = 1;
}
}
}
if (sp->absorb_mols != NULL) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp_absorb_all_volume_mols_orient = no->orient;
sp_absorb_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp_absorb_all_surface_mols_orient = no->orient;
sp_absorb_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp_absorb_all_mols_orient = no->orient;
sp_absorb_all_mols = 1;
}
}
}
for (scl2 = scl->next; scl2 != NULL; scl2 = scl2->next) {
sp2 = scl2->surf_class;
sp2_transp_all_mols = 0;
sp2_absorb_all_mols = 0;
sp2_refl_all_mols = 0;
sp2_transp_all_volume_mols = 0;
sp2_absorb_all_volume_mols = 0;
sp2_refl_all_volume_mols = 0;
sp2_transp_all_surface_mols = 0;
sp2_absorb_all_surface_mols = 0;
sp2_refl_all_surface_mols = 0;
sp2_transp_all_mols_orient = INT_MIN;
sp2_absorb_all_mols_orient = INT_MIN;
sp2_refl_all_mols_orient = INT_MIN;
sp2_transp_all_volume_mols_orient = INT_MIN;
sp2_absorb_all_volume_mols_orient = INT_MIN;
sp2_refl_all_volume_mols_orient = INT_MIN;
sp2_transp_all_surface_mols_orient = INT_MIN;
sp2_absorb_all_surface_mols_orient = INT_MIN;
sp2_refl_all_surface_mols_orient = INT_MIN;
if (sp2->refl_mols != NULL) {
for (no = sp2->refl_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp2_refl_all_volume_mols_orient = no->orient;
sp2_refl_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp2_refl_all_surface_mols_orient = no->orient;
sp2_refl_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp2_refl_all_mols_orient = no->orient;
sp2_refl_all_mols = 1;
}
}
}
if (sp2->transp_mols != NULL) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp2_transp_all_volume_mols_orient = no->orient;
sp2_transp_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp2_transp_all_surface_mols_orient = no->orient;
sp2_transp_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp2_transp_all_mols_orient = no->orient;
sp2_transp_all_mols = 1;
}
}
}
if (sp2->absorb_mols != NULL) {
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
if (strcmp(no->name, "ALL_VOLUME_MOLECULES") == 0) {
sp2_absorb_all_volume_mols_orient = no->orient;
sp2_absorb_all_volume_mols = 1;
}
if (strcmp(no->name, "ALL_SURFACE_MOLECULES") == 0) {
sp2_absorb_all_surface_mols_orient = no->orient;
sp2_absorb_all_surface_mols = 1;
}
if (strcmp(no->name, "ALL_MOLECULES") == 0) {
sp2_absorb_all_mols_orient = no->orient;
sp2_absorb_all_mols = 1;
}
}
}
/* Below we will check for conflicts when two surface classes
both have specified ALL_MOLECULES, or ALL_VOLUME_MOLECULES,
or ALL_SURFACE_MOLECULES keywords in different combinations */
if (sp_transp_all_mols) {
if (sp2_absorb_all_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_absorb_all_mols_orient == 0) ||
(sp_transp_all_mols_orient == sp2_absorb_all_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_volume_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_absorb_all_volume_mols_orient == 0) ||
(sp_transp_all_mols_orient ==
sp2_absorb_all_volume_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_surface_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_absorb_all_surface_mols_orient == 0) ||
(sp_transp_all_mols_orient ==
sp2_absorb_all_surface_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_refl_all_mols_orient == 0) ||
(sp_transp_all_mols_orient == sp2_refl_all_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_volume_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_refl_all_volume_mols_orient == 0) ||
(sp_transp_all_mols_orient == sp2_refl_all_volume_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_surface_mols) {
if ((sp_transp_all_mols_orient == 0) ||
(sp2_refl_all_surface_mols_orient == 0) ||
(sp_transp_all_mols_orient == sp2_refl_all_surface_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_mols) {
if (sp2_transp_all_mols) {
if ((sp2_transp_all_mols_orient == 0) ||
(sp_absorb_all_mols_orient == 0) ||
(sp2_transp_all_mols_orient == sp_absorb_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_transp_all_volume_mols) {
if ((sp2_transp_all_volume_mols_orient == 0) ||
(sp_absorb_all_mols_orient == 0) ||
(sp2_transp_all_volume_mols_orient ==
sp_absorb_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_transp_all_surface_mols) {
if ((sp2_transp_all_surface_mols_orient == 0) ||
(sp_absorb_all_mols_orient == 0) ||
(sp2_transp_all_surface_mols_orient ==
sp_absorb_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_mols) {
if ((sp_absorb_all_mols_orient == 0) ||
(sp2_refl_all_mols_orient == 0) ||
(sp_absorb_all_mols_orient == sp2_refl_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_volume_mols) {
if ((sp_absorb_all_mols_orient == 0) ||
(sp2_refl_all_volume_mols_orient == 0) ||
(sp_absorb_all_mols_orient == sp2_refl_all_volume_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_surface_mols) {
if ((sp_absorb_all_mols_orient == 0) ||
(sp2_refl_all_surface_mols_orient == 0) ||
(sp_absorb_all_mols_orient == sp2_refl_all_surface_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_mols) {
if (sp2_transp_all_mols) {
if ((sp2_transp_all_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_transp_all_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_transp_all_volume_mols) {
if ((sp2_transp_all_volume_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_transp_all_volume_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_transp_all_surface_mols) {
if ((sp2_transp_all_surface_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_transp_all_surface_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_mols) {
if ((sp2_absorb_all_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_absorb_all_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_volume_mols) {
if ((sp2_absorb_all_volume_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_absorb_all_volume_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_VOLUME_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_surface_mols) {
if ((sp2_absorb_all_surface_mols_orient == 0) ||
(sp_refl_all_mols_orient == 0) ||
(sp2_absorb_all_surface_mols_orient == sp_refl_all_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and ALL_SURFACE_MOLECULES through the "
"surface classes '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_transp_all_volume_mols) {
if (sp2_absorb_all_volume_mols) {
if ((sp_transp_all_volume_mols_orient == 0) ||
(sp2_absorb_all_volume_mols_orient == 0) ||
(sp_transp_all_volume_mols_orient ==
sp2_absorb_all_volume_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_volume_mols) {
if ((sp_transp_all_volume_mols_orient == 0) ||
(sp2_refl_all_volume_mols_orient == 0) ||
(sp_transp_all_volume_mols_orient ==
sp2_refl_all_volume_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_volume_mols) {
if (sp2_transp_all_volume_mols) {
if ((sp2_transp_all_volume_mols_orient == 0) ||
(sp_absorb_all_volume_mols_orient == 0) ||
(sp2_transp_all_volume_mols_orient ==
sp_absorb_all_volume_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_volume_mols) {
if ((sp_absorb_all_volume_mols_orient == 0) ||
(sp2_refl_all_volume_mols_orient == 0) ||
(sp_absorb_all_volume_mols_orient ==
sp2_refl_all_volume_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_volume_mols) {
if (sp2_transp_all_volume_mols) {
if ((sp2_transp_all_volume_mols_orient == 0) ||
(sp_refl_all_volume_mols_orient == 0) ||
(sp2_transp_all_volume_mols_orient ==
sp_refl_all_volume_mols_orient)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_volume_mols) {
if ((sp2_absorb_all_volume_mols_orient == 0) ||
(sp_refl_all_volume_mols_orient == 0) ||
(sp2_absorb_all_volume_mols_orient ==
sp_refl_all_volume_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_transp_all_surface_mols) {
if (sp2_absorb_all_surface_mols) {
if ((sp_transp_all_surface_mols_orient == 0) ||
(sp2_absorb_all_surface_mols_orient == 0) ||
(sp_transp_all_surface_mols_orient ==
sp2_absorb_all_surface_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_surface_mols) {
if ((sp_transp_all_surface_mols_orient == 0) ||
(sp2_refl_all_surface_mols_orient == 0) ||
(sp_transp_all_surface_mols_orient ==
sp2_refl_all_surface_mols_orient)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_surface_mols) {
if (sp2_transp_all_surface_mols) {
if ((sp2_transp_all_surface_mols_orient == 0) ||
(sp_absorb_all_surface_mols_orient == 0) ||
(sp2_transp_all_surface_mols_orient ==
sp_absorb_all_surface_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_refl_all_surface_mols) {
if ((sp_absorb_all_surface_mols_orient == 0) ||
(sp2_refl_all_surface_mols_orient == 0) ||
(sp_absorb_all_surface_mols_orient ==
sp2_refl_all_surface_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_surface_mols) {
if (sp2_transp_all_surface_mols) {
if ((sp2_transp_all_surface_mols_orient == 0) ||
(sp_refl_all_surface_mols_orient == 0) ||
(sp2_transp_all_surface_mols_orient ==
sp_refl_all_surface_mols_orient)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
if (sp2_absorb_all_surface_mols) {
if ((sp2_absorb_all_surface_mols_orient == 0) ||
(sp_refl_all_surface_mols_orient == 0) ||
(sp2_absorb_all_surface_mols_orient ==
sp_refl_all_surface_mols_orient)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
/* Below we will check for the conflicts in combination of
ALL_MOLECULES (or ALL_VOLUME_MOLECULES, or ALL_SURFACE_MOLECULES)
with regular molecule */
if (sp_transp_all_mols) {
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
if ((sp_transp_all_mols_orient == no->orient) ||
(sp_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
if ((sp_transp_all_mols_orient == no->orient) ||
(sp_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_transp_all_mols_orient == no->orient) ||
(sp_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_transp_all_volume_mols) {
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp_transp_all_volume_mols_orient == no->orient) ||
(sp_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties are "
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp_transp_all_volume_mols_orient == no->orient) ||
(sp_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
" ALL_VOLUME_MOLECULES and molecule %s through the "
" surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_transp_all_volume_mols_orient == no->orient) ||
(sp_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_transp_all_surface_mols) {
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_transp_all_surface_mols_orient == no->orient) ||
(sp_transp_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_transp_all_surface_mols_orient == no->orient) ||
(sp_transp_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_transp_all_mols) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if ((sp2_transp_all_mols_orient == no->orient) ||
(sp2_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
if ((sp2_transp_all_mols_orient == no->orient) ||
(sp2_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_transp_all_mols_orient == no->orient) ||
(sp2_transp_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_transp_all_volume_mols) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp2_transp_all_volume_mols_orient == no->orient) ||
(sp2_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp2_transp_all_volume_mols_orient == no->orient) ||
(sp2_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_transp_all_volume_mols_orient == no->orient) ||
(sp2_transp_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_transp_all_surface_mols) {
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_transp_all_surface_mols_orient == no->orient) ||
(sp2_transp_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and ABSORPTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_transp_all_surface_mols_orient == no->orient) ||
(sp2_transp_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting TRANSPARENT and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
" ALL_SURFACE_MOLECULES and molecule %s through the "
" surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
if ((sp_absorb_all_mols_orient == no->orient) ||
(sp_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using"
"ALL_MOLECULES through the surface classes '%s' and "
"'%s'.",
sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
if ((sp_absorb_all_mols_orient == no->orient) ||
(sp_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
" ALL_MOLECULES through the surface classes '%s' and"
" '%s'.",
sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_absorb_all_mols_orient == no->orient) ||
(sp_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES through the surface classes '%s' "
"and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_volume_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp_absorb_all_volume_mols_orient == no->orient) ||
(sp_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using"
" ALL_VOLUME_MOLECULES through the surface classes "
" '%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if (spec->flags & ON_GRID)
continue;
if ((sp_absorb_all_volume_mols_orient == no->orient) ||
(sp_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_VOLUME_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_absorb_all_volume_mols_orient == no->orient) ||
(sp_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES through the surface classes "
"'%s' and '%s'.",
sp->sym->name, sp2->sym->name);
}
}
}
if (sp_absorb_all_surface_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_absorb_all_surface_mols_orient == no->orient) ||
(sp_absorb_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using"
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL) {
mcell_error("Cannot find species %s in simulation", no->name);
}
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_absorb_all_surface_mols_orient == no->orient) ||
(sp_absorb_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties "
"are simultaneously specified on the same wall using"
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_absorb_all_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
if ((sp2_absorb_all_mols_orient == no->orient) ||
(sp2_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
if ((sp2_absorb_all_mols_orient == no->orient) ||
(sp2_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are"
" simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_absorb_all_mols_orient == no->orient) ||
(sp2_absorb_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_absorb_all_volume_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp2_absorb_all_volume_mols_orient == no->orient) ||
(sp2_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp2_absorb_all_volume_mols_orient == no->orient) ||
(sp2_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are"
" simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_absorb_all_volume_mols_orient == no->orient) ||
(sp2_absorb_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_absorb_all_surface_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_absorb_all_surface_mols_orient == no->orient) ||
(sp2_absorb_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->refl_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_absorb_all_surface_mols_orient == no->orient) ||
(sp2_absorb_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting ABSORPTIVE and REFLECTIVE properties are"
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
if ((sp_refl_all_mols_orient == no->orient) ||
(sp_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
if ((sp_refl_all_mols_orient == no->orient) ||
(sp_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
"simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_refl_all_mols_orient == no->orient) ||
(sp_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_volume_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp_refl_all_volume_mols_orient == no->orient) ||
(sp_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp_refl_all_volume_mols_orient == no->orient) ||
(sp_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
" simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->clamp_mols; no != NULL; no = no->next) {
if ((sp_refl_all_volume_mols_orient == no->orient) ||
(sp_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp_refl_all_surface_mols) {
for (no = sp2->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_refl_all_surface_mols_orient == no->orient) ||
(sp_refl_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp2->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp_refl_all_surface_mols_orient == no->orient) ||
(sp_refl_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
"simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_refl_all_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
if ((sp2_refl_all_mols_orient == no->orient) ||
(sp2_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->absorb_mols; no != NULL; no = no->next) {
if ((sp2_refl_all_mols_orient == no->orient) ||
(sp2_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
" simultaneously specified on the same wall using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_refl_all_mols_orient == no->orient) ||
(sp2_refl_all_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_MOLECULES and molecule %s through the surface "
"classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_refl_all_volume_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp2_refl_all_volume_mols_orient == no->orient) ||
(sp2_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using"
" ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if (spec->flags & ON_GRID)
continue;
if ((sp2_refl_all_volume_mols_orient == no->orient) ||
(sp2_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
"simultaneously specified on the same wall using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->clamp_mols; no != NULL; no = no->next) {
if ((sp2_refl_all_volume_mols_orient == no->orient) ||
(sp2_refl_all_volume_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and CLAMP "
"properties are simultaneously specified using "
"ALL_VOLUME_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
if (sp2_refl_all_surface_mols) {
for (no = sp->transp_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_refl_all_surface_mols_orient == no->orient) ||
(sp2_refl_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and TRANSPARENT properties "
"are simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
for (no = sp->absorb_mols; no != NULL; no = no->next) {
spec = get_species_by_name(no->name, n_species, species_list);
if (spec == NULL)
mcell_error("Cannot find species %s in simulation", no->name);
if ((spec->flags & NOT_FREE) == 0)
continue;
if ((sp2_refl_all_surface_mols_orient == no->orient) ||
(sp2_refl_all_surface_mols_orient == 0) || (no->orient == 0)) {
mcell_error("Conflicting REFLECTIVE and ABSORPTIVE properties are"
" simultaneously specified on the same wall using "
"ALL_SURFACE_MOLECULES and molecule %s through the "
"surface classes '%s' and '%s'.",
no->name, sp->sym->name, sp2->sym->name);
}
}
}
}
}
}
/***************************************************************************
get_species_by_name:
In: name of species
Out: Species object or NULL if we can't find one.
***************************************************************************/
struct species *get_species_by_name(const char *name, int n_species,
struct species **species_list) {
for (int i = 0; i < n_species; i++) {
struct species *sp = species_list[i];
if (strcmp(sp->sym->name, name) == 0)
return sp;
}
return NULL;
}
/***************************************************************************
create_name_lists_of_volume_and_surface_mols:
In: pointer to the empty linked lists.
Out: none. Two linked lists of volume molecules names and surface molecules
names are created.
***************************************************************************/
void create_name_lists_of_volume_and_surface_mols(
struct volume *world, struct name_list **vol_species_name_list,
struct name_list **surf_species_name_list) {
struct species *spec;
struct name_list *nl, *nl_vol_head = NULL, *nl_surf_head = NULL;
int i;
/* create name lists of volume and surface species */
for (i = 0; i < world->n_species; i++) {
spec = world->species_list[i];
if (spec == NULL)
mcell_internal_error("Cannot find molecule name");
if (spec == world->all_mols)
continue;
if ((spec == world->all_volume_mols) || (spec == world->all_surface_mols))
continue;
if (spec->flags & IS_SURFACE)
continue;
if (spec->flags & ON_GRID) {
nl = CHECKED_MALLOC_STRUCT(struct name_list, "name_list");
nl->name = CHECKED_STRDUP(spec->sym->name, "species name");
nl->prev = NULL; /* we will use only FORWARD feature */
if (nl_surf_head == NULL) {
nl->next = NULL;
nl_surf_head = nl;
} else {
nl->next = nl_surf_head;
nl_surf_head = nl;
}
} else {
nl = CHECKED_MALLOC_STRUCT(struct name_list, "name_list");
nl->name = CHECKED_STRDUP(spec->sym->name, "species name");
nl->prev = NULL; /* we will use only FORWARD feature */
if (nl_vol_head == NULL) {
nl->next = NULL;
nl_vol_head = nl;
} else {
nl->next = nl_vol_head;
nl_vol_head = nl;
}
}
}
if (nl_vol_head != NULL)
*vol_species_name_list = nl_vol_head;
if (nl_surf_head != NULL)
*surf_species_name_list = nl_surf_head;
}
/***************************************************************************
remove_molecules_name_list:
In: none
Out: none. Global linked list of molecules names is memory
deallocated.
***************************************************************************/
void remove_molecules_name_list(struct name_list **nlist) {
struct name_list *nnext, *nl_head;
nl_head = *nlist;
/* remove name list */
while (nl_head != NULL) {
nnext = nl_head->next;
if (nl_head->name != NULL)
free(nl_head->name);
free(nl_head);
nl_head = nnext;
}
nl_head = NULL;
*nlist = NULL;
}
/*****************************************************************
check_for_overlapped_walls:
In: rng: random number generator
n_subvols: number of subvolumes
subvol: a subvolume
Out: 0 if no errors, the world geometry is successfully checked for
overlapped walls.
1 if there are any overlapped walls.
******************************************************************/
int check_for_overlapped_walls(
struct rng_state *rng, int n_subvols, struct subvolume *subvol) {
/* pick up a random vector */
struct vector3 rand_vector;
rand_vector.x = rng_dbl(rng);
rand_vector.y = rng_dbl(rng);
rand_vector.z = rng_dbl(rng);
for (int i = 0; i < n_subvols; i++) {
struct subvolume *sv = &(subvol[i]);
struct wall_aux_list *head = NULL;
for (struct wall_list *wlp = sv->wall_head; wlp != NULL; wlp = wlp->next) {
double d_prod = dot_prod(&rand_vector, &(wlp->this_wall->normal));
/* we want to place walls with opposite normals into
neighboring positions in the sorted linked list */
if (d_prod < 0)
d_prod = -d_prod;
struct wall_aux_list *newNode;
newNode = CHECKED_MALLOC_STRUCT(struct wall_aux_list, "wall_aux_list");
newNode->this_wall = wlp->this_wall;
newNode->d_prod = d_prod;
sorted_insert_wall_aux_list(&head, newNode);
}
for (struct wall_aux_list *curr = head; curr != NULL; curr = curr->next) {
struct wall *w1 = curr->this_wall;
struct wall_aux_list *next_curr = curr->next;
while ((next_curr != NULL) &&
(!distinguishable(curr->d_prod, next_curr->d_prod, EPS_C))) {
/* there may be several walls with the same (or mirror)
oriented normals */
struct wall *w2 = next_curr->this_wall;
if (are_walls_coplanar(w1, w2, MESH_DISTINCTIVE)) {
if ((are_walls_coincident(w1, w2, MESH_DISTINCTIVE) ||
coplanar_tri_overlap(w1, w2))) {
mcell_error(
"walls are overlapped: wall %d from '%s' and wall "
"%d from '%s'.",
w1->side, w1->parent_object->sym->name, w2->side,
w2->parent_object->sym->name);
}
}
next_curr = next_curr->next;
}
}
/* free memory */
if (head != NULL)
delete_wall_aux_list(head);
}
return 0;
}
/* this function checks if obj is contained in the linked list of objects
* which have the passed-in concentration clamp */
struct clamp_data* find_clamped_object_in_list(struct clamp_data *cdp,
struct geom_object *obj) {
struct clamp_data *c = cdp;
while (c->next_obj != NULL) {
if (c->next_obj->objp == obj) {
return c->next_obj;
}
c = c->next_obj;
}
return NULL;
}
| C |
3D | mcellteam/mcell | src/mcell_misc.c | .c | 8,106 | 251 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "config.h"
#include "mcell_structs.h"
#include "argparse.h"
#include "version_info.h"
#include "logging.h"
#include "version_info.h"
#include "mcell_misc.h"
#include "dump_state.h"
/* declaration of static functions */
static void swap_double(double *x, double *y);
/************************************************************************
*
* mcell_print_version prints the version string
*
************************************************************************/
void mcell_print_version() { print_version(mcell_get_log_file()); }
/************************************************************************
*
* mcell_print_usage prints the usage information
*
************************************************************************/
void mcell_print_usage(const char *executable_name) {
print_usage(mcell_get_log_file(), executable_name);
}
/************************************************************************
*
* mcell_print_stats prints the simulation stats
*
************************************************************************/
void mcell_print_stats() { mem_dump_stats(mcell_get_log_file()); }
/************************************************************************
*
* function for printing a string
*
* XXX: This is a temporary hack to be able to print in mcell.c
* since mcell disables regular printf
*
************************************************************************/
void mcell_print(const char *message) { mcell_log("%s", message); }
void mcell_dump_state(MCELL_STATE *state) {
dump_volume(state, "", DUMP_EVERYTHING);
}
/************************************************************************
*
* mcell_argparse parses the commandline and sets the
* corresponding parts of the state (seed #, logging, ...)
*
************************************************************************/
int mcell_argparse(int argc, char **argv, MCELL_STATE *state) {
return argparse_init(argc, argv, state);
}
/*************************************************************************
mcell_copysort_numeric_list:
Copy and sort a num_expr_list in ascending numeric order.
In: parse_state: parser state
head: the list to sort
Out: list is sorted
*************************************************************************/
struct num_expr_list *mcell_copysort_numeric_list(struct num_expr_list *head) {
struct num_expr_list_head new_head;
if (mcell_generate_range_singleton(&new_head, head->value))
return NULL;
head = head->next;
while (head != NULL) {
struct num_expr_list *insert_pt, **prev;
for (insert_pt = new_head.value_head, prev = &new_head.value_head;
insert_pt != NULL;
prev = &insert_pt->next, insert_pt = insert_pt->next) {
if (insert_pt->value >= head->value)
break;
}
struct num_expr_list *new_item =
CHECKED_MALLOC_STRUCT(struct num_expr_list, "numeric array");
if (new_item == NULL) {
mcell_free_numeric_list(new_head.value_head);
return NULL;
}
new_item->next = insert_pt;
new_item->value = head->value;
*prev = new_item;
if (insert_pt == NULL)
new_head.value_tail = new_item;
head = head->next;
}
return new_head.value_head;
}
/*************************************************************************
mcell_sort_numeric_list:
Sort a num_expr_list in ascending numeric order. N.B. This uses bubble
sort, which is O(n^2). Don't use it if you expect your list to be very
long. The list is sorted in-place.
In: head: the list to sort
Out: list is sorted
*************************************************************************/
void mcell_sort_numeric_list(struct num_expr_list *head) {
struct num_expr_list *curr, *next;
int done = 0;
while (!done) {
done = 1;
curr = head;
while (curr != NULL) {
next = curr->next;
if (next != NULL) {
if (curr->value > next->value) {
done = 0;
swap_double(&curr->value, &next->value);
}
}
curr = next;
}
}
}
/*************************************************************************
mcell_free_numeric_list:
Free a num_expr_list.
In: nel: the list to free
Out: all elements are freed
*************************************************************************/
void mcell_free_numeric_list(struct num_expr_list *nel) {
free_numeric_list(nel);
}
/*************************************************************************
mcell_generate_range:
Generate a num_expr_list containing the numeric values from start to end,
incrementing by step.
In: state: the simulation state
list: destination to receive list of values
start: start of range
end: end of range
step: increment
Out: 0 on success, 1 on failure. On success, list is filled in.
*************************************************************************/
MCELL_STATUS mcell_generate_range(struct num_expr_list_head *list, double start,
double end, double step) {
if (generate_range(list, start, end, step)) {
return MCELL_FAIL;
} else {
return MCELL_SUCCESS;
}
}
/*************************************************************************
mcell_generate_range_singleton:
Generate a numeric list containing a single value.
In: lh: list to receive value
value: value for list
Out: 0 on success, 1 on failure
*************************************************************************/
int mcell_generate_range_singleton(struct num_expr_list_head *lh,
double value) {
struct num_expr_list *nel =
CHECKED_MALLOC_STRUCT(struct num_expr_list, "numeric array");
if (nel == NULL)
return 1;
lh->value_head = lh->value_tail = nel;
lh->value_count = 1;
lh->shared = 0;
lh->value_head->value = value;
lh->value_head->next = NULL;
lh->start_end_step_set = false;
return 0;
}
/************************************************************************
swap_double:
In: x, y: doubles to swap
Out: Swaps references to two double values.
***********************************************************************/
void swap_double(double *x, double *y) {
double temp;
temp = *x;
*x = *y;
*y = temp;
}
/************************************************************************
mcell_find_include_file:
Find the path for an include file. For an absolute include path, the
file path is unmodified, but for a relative path, the resultant path will
be relative to the currently parsed file.
In: path: path from include statement
cur_path: path of current include file
Out: allocated buffer containing path of the include file, or NULL if the file
path couldn't be allocated. If we ever use a more complex mechanism for
locating include files, we may also return NULL if no file could be
located.
***********************************************************************/
char *mcell_find_include_file(char const *path, char const *cur_path) {
char *candidate = NULL;
if (path[0] == '/')
candidate = strdup(path);
else {
const char *last_slash = strrchr(cur_path, '/');
#ifdef _WIN64
const char *last_bslash = strrchr(cur_path, '\\');
if (last_bslash > last_slash)
last_slash = last_bslash;
#endif
if (last_slash == NULL)
candidate = strdup(path);
else
candidate = CHECKED_SPRINTF("%.*s/%s", (int)(last_slash - cur_path),
cur_path, path);
}
return candidate;
}
| C |
3D | mcellteam/mcell | src/react_output.c | .c | 41,417 | 1,259 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifndef _MSC_VER
#include <unistd.h>
#endif
#include <signal.h>
#include <errno.h>
#include "logging.h"
#include "sched_util.h"
#include "mcell_structs.h"
#include "react_output.h"
#include "mdlparse_util.h"
#include "strfunc.h"
// XXX: This global state should be removed. Currently
// we need it for cleanup via signals.
static struct volume *global_state;
/**************************************************************************
truncate_output_file:
In: filename string
value that we will start outputting to the file
Out: 0 if file preparation is successful, 1 if not. The file is
truncated at start of the line containing the first entry
greater than or equal to the value to be printed out.
**************************************************************************/
int truncate_output_file(char *name, double start_value) {
FILE *f = NULL;
/* Check if the file exists */
struct stat fs;
int i = stat(name, &fs);
if (i == -1) {
mcell_perror(errno, "Failed to stat reaction data output file '%s' in "
"preparation for truncation.",
name);
}
if (fs.st_size == 0)
return 0; /* File already is empty */
/* Set the buffer size */
off_t bsize;
if (fs.st_size < (1 << 20)) {
bsize = fs.st_size;
} else
bsize = (1 << 20);
/* Allocate a buffer for the file */
char *buffer= CHECKED_MALLOC_ARRAY_NODIE(
char, bsize + 1, "reaction data file scan buffer");
if (buffer == NULL)
goto failure;
/* Open the file */
f = fopen(name, "r+");
if (!f) {
mcell_perror(
errno, "Failed to open reaction data output file '%s' for truncation.",
name);
/*goto failure;*/
}
{
/* Iterate over the entire file */
int where = 0; /* Byte offset in file */
int start = 0; /* Byte offset in buffer */
while (ftell(f) != fs.st_size) {
/* Refill the buffer */
long long n = (long long)fread(buffer + start, 1, bsize - start, f);
/* Until the current buffer runs dry */
int ran_out = 0;
i = 0;
n += start;
int lf = 0;
while (!ran_out) {
/* Skip leading horizontal whitespace */
while (i < n && (buffer[i] == ' ' || buffer[i] == '\t'))
i++;
/* Scan over leading numeric characters */
int j = i;
for (;
j < n && (isdigit(buffer[j]) || strchr("eE-+.", buffer[j]) != NULL);
j++) {
}
/* If we had a leading number... */
if (j > i && j < (n - 1)) {
char *done = NULL;
/* Parse and validate the number */
buffer[j] = '\0';
double my_value = strtod(buffer + i, &done) + EPS_C;
/* If it was a valid number and it was >= our start time */
if (done != buffer + i && my_value >= start_value) {
if (fseek(f, 0, SEEK_SET)) {
mcell_perror(
errno,
"Failed to seek to beginning of reaction data output file '%s'",
name);
/*goto failure;*/
}
#ifndef _MSC_VER
if (ftruncate(fileno(f), where + lf)) {
mcell_perror(errno,
"Failed to truncate reaction data output file '%s'",
name);
/*goto failure;*/
}
#else
mcell_error("TODO: ftruncate is not supported on windows");
#endif
fclose(f);
free(buffer);
return 0;
}
}
/* We will keep this line. Scan until we hit a newline */
for (i = j; i < n && buffer[i] != '\n' && buffer[i] != '\r'; i++) {
}
/* If we're not at the end of the buffer, scan over all crs/lfs. */
if (i < n) {
for (j = i; j < n && (buffer[j] == '\n' || buffer[j] == '\r'); j++) {
}
lf = j;
i = j; /* If we have run out, we'll catch it next time through */
}
/* If we hit 'n' and the last read was only partial (i.e. EOF), break out
*/
else if (n < bsize) {
ran_out = 1;
}
/* Last read was a full read and we've scanned the whole buffer */
else {
/* If we need to keep some data, resituate it in the buffer */
if (lf > start) {
/* discard all but n - lf bytes */
memmove(buffer, buffer + lf, n - lf);
where += lf;
start = n - lf;
} else {
/* discard all bytes */
where += n;
start = 0;
}
lf = 0;
ran_out = 1;
}
}
}
fclose(f);
free(buffer);
return 0;
}
failure:
if (f != NULL)
fclose(f);
if (buffer != NULL)
free(buffer);
return 1;
}
/**************************************************************************
emergency_output:
In: No arguments.
Out: Number of errors encountered while trying to make an emergency
dump of output buffers (0 indicates emergency save went fine).
The code assumes a memory error, dumps any memory it can to
try to make enough room to create a file to save results held
in buffers.
Note: The simulation is COMPLETELY TRASHED after this function is
called. Do NOT use this in normal operation. Do NOT try to
continue running after this function is called. This function
will deallocate all molecules, walls, etc. to try to recover
memory! You should only print messages and exit after running
this function.
**************************************************************************/
static int emergency_output(struct volume *world) {
struct storage_list *mem;
/* PANIC--delete everything we can get our pointers on! */
delete_mem(world->coll_mem);
delete_mem(world->exdv_mem);
for (mem = world->storage_head; mem != NULL; mem = mem->next) {
delete_mem(mem->store->list);
delete_mem(mem->store->mol);
delete_mem(mem->store->smol);
delete_mem(mem->store->face);
delete_mem(mem->store->join);
delete_mem(mem->store->grids);
delete_mem(mem->store->regl);
}
delete_mem(world->storage_allocator);
return flush_reaction_output(world);
}
/**************************************************************************
emergency_output_hook_enabled:
Flag to disable emergency output hook when the program exits successfully.
**************************************************************************/
int emergency_output_hook_enabled = 1;
/**************************************************************************
emergency_output_hook:
This is an atexit hook to flush reaction output to disk in case an error is
occurred. Set emergency_output_hook_enabled to 0 to prevent it from being
called (say, on successful exit).
In: No arguments.
Out: None.
**************************************************************************/
static void emergency_output_hook(void) {
if (emergency_output_hook_enabled) {
/* Disable the emergency output hook in case a signal is received while
* producing emergency output. */
emergency_output_hook_enabled = 0;
int n_errors = emergency_output(global_state);
if (n_errors == 0)
mcell_warn("Emergency output hook triggered:\n Reaction output was successfully flushed to disk.");
else if (n_errors == 1)
mcell_warn("An error occurred while flushing reaction output to disk.");
else
mcell_warn("%d errors occurred while flushing reaction output to disk.",
n_errors);
}
}
/**************************************************************************
emergency_output_signal_handler:
This is a signal handler to catch any abnormal termination signals, and
flush the reaction output data (and anything else which should be flushed).
In: No arguments.
Out: None.
**************************************************************************/
static void emergency_output_signal_handler(int signo)
__attribute__((noreturn));
static void emergency_output_signal_handler(int signo) {
if (emergency_output_hook_enabled) {
emergency_output_hook_enabled = 0;
int n_errors = flush_reaction_output(global_state);
if (n_errors == 0)
mcell_error_raw("Emergency output signal handler triggered by signal %d:\n Reaction output was successfully flushed to disk.\n", signo);
else if (n_errors == 1)
mcell_error_raw(
"An error occurred while flushing reaction output to disk.\n");
else
mcell_error_raw(
"%d errors occurred while flushing reaction output to disk.\n",
n_errors);
}
raise(signo);
/* We shouldn't get here, but we might if, for instance, SA_NODEFER is
* unsupported. */
_exit(128 + signo);
}
/**************************************************************************
install_emergency_output_signal_handler:
This installs a handler for a single signal which will print out a sensible
message, then try to flush as much output data to disk as possible before
dying.
In: No arguments.
Out: None.
**************************************************************************/
static void install_emergency_output_signal_handler(int signo) {
#ifdef _WIN64 /* fixme: for Windows do a better job than just signal(), need \
to find out what other things the *nix version is doing */
signal(signo, &emergency_output_signal_handler);
#else
struct sigaction sa, saPrev;
sa.sa_sigaction = NULL;
sa.sa_handler = &emergency_output_signal_handler;
sa.sa_flags = SA_RESTART | SA_RESETHAND | SA_NODEFER;
sigfillset(&sa.sa_mask);
if (sigaction(signo, &sa, &saPrev) != 0)
mcell_warn("Failed to install emergency output signal handler.");
#endif
}
/**************************************************************************
install_emergency_output_hooks:
Installs all relevant hooks for catching invalid program termination and
flushing output to disk, where possible.
In: No arguments.
Out: None.
**************************************************************************/
void install_emergency_output_hooks(struct volume *world) {
global_state = world;
if (atexit(&emergency_output_hook) != 0)
mcell_warn("Failed to install emergency output hook.");
install_emergency_output_signal_handler(
SIGILL); /* not generated on Windows but can be raised manually */
install_emergency_output_signal_handler(SIGABRT);
install_emergency_output_signal_handler(SIGFPE);
install_emergency_output_signal_handler(SIGSEGV);
#ifdef SIGBUS
install_emergency_output_signal_handler(SIGBUS);
#endif
}
/*************************************************************************
add_trigger_output:
In: counter of thing that just happened (trigger of some sort)
request structure saying who wanted to know that it happened
number of times that thing happened
Out: The event is added to the buffer of the requester, and the
buffer is written and flushed if the buffer is full.
Note: Hits are assumed to happen with only one molecule; positive
means the front face was hit, negative means the back was hit.
This is reported as orientation instead.
*************************************************************************/
void add_trigger_output(struct volume *world, struct counter *c,
struct output_request *ear, int n, short flags,
u_long id) {
struct output_column *first_column;
first_column = ear->requester->column->set->column_head;
int idx = (int)first_column->initial_value;
struct output_trigger_data *otd;
otd = first_column->buffer[idx].val.tval;
if (first_column->set->block->timer_type == OUTPUT_BY_ITERATION_LIST)
otd->t_iteration = world->current_iterations;
else
otd->t_iteration = world->current_iterations * world->time_unit;
otd->event_time = c->data.trig.t_event * world->time_unit;
otd->loc.x = c->data.trig.loc.x * world->length_unit;
otd->loc.y = c->data.trig.loc.y * world->length_unit;
otd->loc.z = c->data.trig.loc.z * world->length_unit;
if (flags & TRIG_IS_HIT) {
otd->how_many = 1;
if (n > 0)
otd->orient = 1;
else
otd->orient = -1;
} else {
otd->how_many = n;
otd->orient = c->data.trig.orient;
}
otd->flags = flags;
otd->name = ear->requester->column->expr->title;
otd->id = id;
first_column->initial_value += 1.0;
idx = (int)first_column->initial_value;
if (idx >= (int)first_column->set->block->trig_bufsize) {
if (write_reaction_output(world, first_column->set))
mcell_error("Failed to write triggered count output to file '%s'.",
first_column->set->outfile_name);
first_column->initial_value = 0;
}
}
/*************************************************************************
flush_reaction_output:
In: nothing
Out: 0 on success, 1 on error (memory allocation or file I/O).
Writes all remaining trigger events in buffers to disk.
(Do this before ending the simulation.)
*************************************************************************/
int flush_reaction_output(struct volume *world) {
struct schedule_helper *sh;
struct output_block *ob;
struct output_set *os;
int i;
int n_errors = 0;
for (sh = world->count_scheduler; sh != NULL; sh = sh->next_scale) {
for (i = 0; i <= sh->buf_len; i++) {
if (i == sh->buf_len)
ob = (struct output_block *)sh->current;
else
ob = (struct output_block *)sh->circ_buf_head[i];
for (; ob != NULL; ob = ob->next) {
for (os = ob->data_set_head; os != NULL; os = os->next) {
if (write_reaction_output(world, os))
n_errors++;
}
}
}
}
return n_errors;
}
/**************************************************************************
update_reaction_output:
In: the output_block we want to update
Out: 0 on success, 1 on failure.
The counters in this block are updated, and the block is
rescheduled for the next output time. The counters are saved
to an internal buffer, and written out when full.
**************************************************************************/
int update_reaction_output(struct volume *world, struct output_block *block) {
int report_as_non_trigger = 1;
int i = block->buf_index;
if (block->data_set_head != NULL &&
block->data_set_head->column_head != NULL &&
block->data_set_head->column_head->buffer[i].data_type == COUNT_TRIG_STRUCT)
report_as_non_trigger = 0;
if (report_as_non_trigger) {
switch (world->notify->reaction_output_report) {
case NOTIFY_NONE:
break;
case NOTIFY_BRIEF:
mcell_log(
"Updating reaction output scheduled at time %.15g on iteration %lld.",
block->t, world->current_iterations);
break;
case NOTIFY_FULL:
mcell_log("Updating reaction output scheduled at time %.15g on iteration"
" %lld.\n Buffer fill level is at %u/%u.",
block->t, world->current_iterations, block->buf_index,
block->buffersize);
break;
default:
UNHANDLED_CASE(world->notify->reaction_output_report);
}
}
/* update all counters */
block->t /= (1. + EPS_C);
if (world->chkpt_seq_num == 1) {
if (block->timer_type == OUTPUT_BY_ITERATION_LIST)
block->time_array[i] = block->t;
else
block->time_array[i] = block->t * world->time_unit;
} else {
if (block->timer_type == OUTPUT_BY_ITERATION_LIST) {
block->time_array[i] = block->t;
} else if (block->timer_type == OUTPUT_BY_TIME_LIST) {
if (block->time_now == NULL) {
return 0;
} else {
block->time_array[i] = block->time_now->value;
}
} else {
/* OUTPUT_BY_STEP */
block->time_array[i] = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, block->t);
}
}
struct output_set *set;
struct output_column *column;
// Each file
for (set = block->data_set_head; set != NULL; set = set->next)
{
if (report_as_non_trigger) {
if (world->notify->reaction_output_report == NOTIFY_FULL)
mcell_log(" Processing reaction output file '%s'.", set->outfile_name);
}
// Each column
for (column = set->column_head; column != NULL; column = column->next)
{
if (column->buffer[i].data_type != COUNT_TRIG_STRUCT) {
eval_oexpr_tree(column->expr, 1);
switch (column->buffer[i].data_type) {
case COUNT_INT:
column->buffer[i].val.ival = (int)column->expr->value;
break;
case COUNT_DBL:
column->buffer[i].val.dval = (double)column->expr->value;
break;
case COUNT_UNSET:
column->buffer[i].val.cval = 'X';
break;
case COUNT_TRIG_STRUCT:
default:
UNHANDLED_CASE(column->buffer[i].data_type);
}
}
}
}
block->buf_index++;
int final_chunk_flag = 0; // flag signaling an end to the scheduled
// reaction outputs. Takes values {0,1}.
// 0 - end not reached yet,
// 1 - end reached.
/* Pick time of next output, if any */
if (block->timer_type == OUTPUT_BY_STEP)
block->t += block->step_time / world->time_unit;
else if (block->time_now != NULL) {
block->time_now = block->time_now->next;
if (block->time_now == NULL)
final_chunk_flag = 1;
else {
if (block->timer_type == OUTPUT_BY_ITERATION_LIST)
block->t = block->time_now->value;
else {
/* OUTPUT_BY_TIME_LIST */
if (world->chkpt_seq_num == 1) {
block->t = block->time_now->value / world->time_unit;
} else {
block->t = world->start_iterations +
(block->time_now->value - world->simulation_start_seconds) /
world->time_unit;
}
}
}
} else
final_chunk_flag = 1;
/* Schedule next output event--even if we're at the end, since triggers may
* not yet be written */
double actual_t;
if (final_chunk_flag == 1) {
actual_t = block->t;
block->t = FOREVER;
} else
actual_t = -1;
block->t *= (1. + EPS_C);
if (schedule_add(world->count_scheduler, block)) {
mcell_allocfailed_nodie("Failed to add count to scheduler.");
return 1;
}
if (distinguishable(actual_t, -1, EPS_C))
block->t = actual_t; /* Fix time for output */
if (report_as_non_trigger &&
world->notify->reaction_output_report == NOTIFY_FULL) {
mcell_log(" Next output for this block scheduled at time %.15g.",
block->t);
}
if (block->t >= world->iterations + 1)
final_chunk_flag = 1;
/* write data to outfile */
if (block->buf_index == block->buffersize || final_chunk_flag) {
for (set = block->data_set_head; set != NULL; set = set->next) {
if (set->column_head->buffer[i].data_type == COUNT_TRIG_STRUCT)
continue;
if (write_reaction_output(world, set)) {
mcell_error_nodie("Failed to write reaction output to file '%s'.",
set->outfile_name);
return 1;
}
}
block->buf_index = 0;
no_printf("Done updating reaction output\n");
}
if (distinguishable(actual_t, -1, EPS_C))
block->t = FOREVER; /* Back to infinity if we're done */
return 0;
}
/**************************************************************************
check_reaction_output_file:
Check that the reaction output file is writable within the policy set by
the user. Creates and/or truncates the file to 0 bytes, as appropriate.
Note that for SUBSTITUTE, the truncation is done later on, during
initialization.
In: parse_state: parser state
os: output set containing file details
Out: 0 if file preparation is successful, 1 if not. The file named will be
created and emptied or truncated as requested.
**************************************************************************/
int check_reaction_output_file(struct output_set *os) {
FILE *f;
char *name;
struct stat fs;
int i;
name = os->outfile_name;
if (make_parent_dir(name)) {
// mdlerror_fmt(parse_state,
// "Directory for %s does not exist and could not be
// created.",
// name);
return 1;
}
switch (os->file_flags) {
case FILE_OVERWRITE:
f = fopen(name, "w"); // TODO: this might clear mcell3 file when mcell4 mode is used but there is no easy way how to pass information on the mode
if (!f) {
switch (errno) {
case EACCES:
// mdlerror_fmt(parse_state, "Access to %s denied.", name);
return 1;
case ENOENT:
// mdlerror_fmt(parse_state, "Directory for %s does not exist",
// name);
return 1;
case EISDIR:
// mdlerror_fmt(parse_state, "%s already exists and is a
// directory", name);
return 1;
default:
// mdlerror_fmt(parse_state, "Unable to open %s for writing",
// name);
return 1;
}
}
fclose(f);
break;
case FILE_SUBSTITUTE:
f = fopen(name, "a+");
if (!f) {
switch (errno) {
case EACCES:
// mdlerror_fmt(parse_state, "Access to %s denied.", name);
return 1;
case ENOENT:
// mdlerror_fmt(parse_state, "Directory for %s does not exist",
// name);
return 1;
case EISDIR:
// mdlerror_fmt(parse_state, "%s already exists and is a
// directory", name);
return 1;
default:
// mdlerror_fmt(parse_state, "Unable to open %s for writing",
// name);
return 1;
}
}
i = fstat(fileno(f), &fs);
if (!i && fs.st_size == 0)
os->file_flags = FILE_OVERWRITE;
fclose(f);
break;
case FILE_APPEND:
case FILE_APPEND_HEADER:
f = fopen(name, "a");
if (!f) {
switch (errno) {
case EACCES:
// mdlerror_fmt(parse_state, "Access to %s denied.", name);
return 1;
case ENOENT:
// mdlerror_fmt(parse_state, "Directory for %s does not exist",
// name);
return 1;
case EISDIR:
// mdlerror_fmt(parse_state, "%s already exists and is a
// directory", name);
return 1;
default:
// mdlerror_fmt(parse_state, "Unable to open %s for writing",
// name);
return 1;
}
}
i = fstat(fileno(f), &fs);
if (!i && fs.st_size == 0)
os->file_flags = FILE_APPEND_HEADER;
fclose(f);
break;
case FILE_CREATE:
#ifndef _MSC_VER
i = access(name, F_OK);
if (!i) {
i = stat(name, &fs);
if (!i && fs.st_size > 0) {
// mdlerror_fmt(parse_state,
// "Cannot create new file %s: it already exists",
// name);
return 1;
}
}
#endif
f = fopen(name, "w");
if (f == NULL) {
switch (errno) {
case EEXIST:
// mdlerror_fmt(parse_state, "Cannot create %s because it already
// exists",
// name);
return 1;
case EACCES:
// mdlerror_fmt(parse_state, "Access to %s denied.", name);
return 1;
case ENOENT:
// mdlerror_fmt(parse_state, "Directory for %s does not exist",
// name);
return 1;
case EISDIR:
// mdlerror_fmt(parse_state, "%s already exists and is a
// directory", name);
return 1;
default:
// mdlerror_fmt(parse_state, "Unable to open %s for writing",
// name);
return 1;
}
}
fclose(f);
break;
default:
UNHANDLED_CASE(os->file_flags);
}
return 0;
}
/**************************************************************************
write_reaction_output:
In: the output_set we want to write to disk
the flag that signals an end to the scheduled reaction outputs
Out: 0 on success, 1 on failure.
The reaction output buffer is flushed and written to disk.
Indices are not reset; that's the job of the calling function.
**************************************************************************/
int write_reaction_output(struct volume *world, struct output_set *set) {
FILE *fp;
struct output_column *column;
const char *mode;
u_int n_output;
u_int i;
switch (set->file_flags) {
case FILE_OVERWRITE:
case FILE_CREATE:
if (set->chunk_count == 0)
mode = "w";
else
mode = "a";
break;
case FILE_SUBSTITUTE:
if (world->chkpt_seq_num == 1 && set->chunk_count == 0)
mode = "w";
else
mode = "a";
break;
case FILE_APPEND:
case FILE_APPEND_HEADER:
mode = "a";
break;
default:
mcell_internal_error(
"Bad file output code %d for reaction data output file '%s'.",
set->file_flags, set->outfile_name);
}
fp = open_file(set->outfile_name, mode);
if (fp == NULL)
return 1;
/*int idx = set->block->buf_index;*/
if (set->column_head->buffer[0].data_type != COUNT_TRIG_STRUCT) {
n_output = set->block->buffersize;
if (set->block->buf_index < set->block->buffersize)
n_output = set->block->buf_index;
if (world->notify->file_writes == NOTIFY_FULL)
mcell_log("Writing %d lines to output file %s.", n_output,
set->outfile_name);
/* Write headers */
if (set->chunk_count == 0 && set->header_comment != NULL &&
set->file_flags != FILE_APPEND &&
(world->chkpt_seq_num == 1 || set->file_flags == FILE_APPEND_HEADER ||
set->file_flags == FILE_CREATE || set->file_flags == FILE_OVERWRITE)) {
if (set->block->timer_type == OUTPUT_BY_ITERATION_LIST)
fprintf(fp, "%sIteration_#", set->header_comment);
else
fprintf(fp, "%sSeconds", set->header_comment);
for (column = set->column_head; column != NULL; column = column->next) {
if (column->expr->title == NULL)
fprintf(fp, " untitled");
else
fprintf(fp, " %s", column->expr->title);
}
fprintf(fp, "\n");
}
/* Write data */
for (i = 0; i < n_output; i++) {
fprintf(fp, "%.15g", set->block->time_array[i]);
for (column = set->column_head; column != NULL; column = column->next) {
switch (column->buffer[i].data_type) {
case COUNT_INT:
fprintf(fp, " %d", (column->buffer[i].val.ival));
break;
case COUNT_DBL:
fprintf(fp, " %.9g", (column->buffer[i].val.dval));
break;
case COUNT_UNSET:
fprintf(fp, " X");
break;
case COUNT_TRIG_STRUCT:
default:
if (column->expr->title != NULL)
mcell_warn(
"Unexpected data type in column titled '%s' -- skipping.",
column->expr->title);
else
mcell_warn("Unexpected data type in untitled column -- skipping.");
break;
}
}
fprintf(fp, "\n");
}
} else /* Write accumulated trigger data */
{
struct output_trigger_data *trig;
char event_time_string[1024]; /* Wouldn't run out of space even if we
printed out DBL_MAX in non-exponential
notation! */
n_output = (u_int)set->column_head->initial_value;
for (i = 0; i < n_output; i++) {
trig = set->column_head->buffer[i].val.tval;
if (set->exact_time_flag)
sprintf(event_time_string, "%.12g ", trig->event_time);
else
strcpy(event_time_string, "");
if (trig->flags & TRIG_IS_RXN) /* Just need time, pos, name */
{
fprintf(fp, "%.15g %s%.9g %.9g %.9g %s\n",
trig->t_iteration,
event_time_string,
trig->loc.x,
trig->loc.y,
trig->loc.z,
(trig->name == NULL) ? "" : trig->name);
} else if (trig->flags & TRIG_IS_HIT) /* Need orientation also */
{
fprintf(fp, "%.15g %s%.9g %.9g %.9g %d %s\n",
trig->t_iteration,
event_time_string,
trig->loc.x,
trig->loc.y,
trig->loc.z,
trig->orient,
(trig->name == NULL) ? "" : trig->name);
} else /* Molecule count -- need both number and orientation */
{
fprintf(fp, "%.15g %s%.9g %.9g %.9g %d %d %s %lu\n",
trig->t_iteration,
event_time_string,
trig->loc.x,
trig->loc.y,
trig->loc.z,
trig->orient,
trig->how_many,
(trig->name == NULL) ? "" : trig->name,
trig->id);
}
}
}
set->chunk_count++;
fclose(fp);
return 0;
}
/*************************************************************************
new_output_expr:
In: mem_helper used to allocate output_expressions
Out: New, initialized output_expression, or NULL if out of memory.
*************************************************************************/
struct output_expression *new_output_expr(struct mem_helper *oexpr_mem) {
struct output_expression *oe;
oe = (struct output_expression *)mem_get(oexpr_mem);
if (oe == NULL)
return NULL;
oe->column = NULL;
oe->expr_flags = 0;
oe->up = NULL;
oe->left = NULL;
oe->right = NULL;
oe->oper = '\0';
oe->value = 0;
oe->title = NULL;
return oe;
}
/*************************************************************************
set_oexpr_column:
In: output_expression who needs to have its column set (recursively)
output_column that owns this expression
Out: No return value. Every output_expression in the tree gets its
column set.
*************************************************************************/
void set_oexpr_column(struct output_expression *oe, struct output_column *oc) {
for (; oe != NULL;
oe = ((oe->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_OEXPR)
? (struct output_expression *)oe->right
: NULL) {
oe->column = oc;
if ((oe->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_OEXPR)
set_oexpr_column((struct output_expression *)oe->left, oc);
}
}
/*************************************************************************
learn_oexpr_oexpr:
In: output_expression whose flags may not reflect its children properly
Out: No return value. Flags are updated for output_expression passed
in. (Not recursive.)
*************************************************************************/
void learn_oexpr_flags(struct output_expression *oe) {
struct output_expression *oel, *oer;
oel = (struct output_expression *)oe->left;
oer = (struct output_expression *)oe->right;
if (oer == NULL) {
if (oel == NULL)
oe->expr_flags = OEXPR_TYPE_CONST | OEXPR_TYPE_DBL;
else {
oe->expr_flags =
(oel->expr_flags & (OEXPR_TYPE_MASK | OEXPR_TYPE_CONST)) |
OEXPR_LEFT_OEXPR;
if (oel->expr_flags & OEXPR_TYPE_CONST)
oe->expr_flags |= OEXPR_LEFT_CONST;
}
} else {
oer = (struct output_expression *)oe->right;
oe->expr_flags = OEXPR_LEFT_OEXPR | OEXPR_RIGHT_OEXPR;
if (oel->expr_flags & OEXPR_TYPE_CONST)
oe->expr_flags |= OEXPR_LEFT_CONST;
if (oer->expr_flags & OEXPR_TYPE_CONST)
oe->expr_flags |= OEXPR_RIGHT_CONST;
if (oel->expr_flags & oer->expr_flags & OEXPR_TYPE_CONST)
oe->expr_flags |= OEXPR_TYPE_CONST;
if ((oel->expr_flags & OEXPR_TYPE_MASK) ==
(oer->expr_flags & OEXPR_TYPE_MASK))
oe->expr_flags |= oel->expr_flags & OEXPR_TYPE_MASK;
else {
if ((oel->expr_flags & OEXPR_TYPE_MASK) == OEXPR_TYPE_TRIG)
oe->expr_flags |= OEXPR_TYPE_TRIG;
else if ((oer->expr_flags & OEXPR_TYPE_MASK) == OEXPR_TYPE_TRIG)
oe->expr_flags |= OEXPR_TYPE_TRIG;
else if ((oel->expr_flags & OEXPR_TYPE_MASK) == OEXPR_TYPE_DBL)
oe->expr_flags |= OEXPR_TYPE_DBL;
else if ((oer->expr_flags & OEXPR_TYPE_MASK) == OEXPR_TYPE_DBL)
oe->expr_flags |= OEXPR_TYPE_DBL;
else
oe->expr_flags |= OEXPR_TYPE_INT;
}
}
}
/*************************************************************************
first_oexpr_tree:
In: expression tree
Out: leftmost stem in that tree (joined by ',' operator)
*************************************************************************/
struct output_expression *first_oexpr_tree(struct output_expression *root) {
while (root->oper == ',')
root = (struct output_expression *)root->left;
return root;
}
/*************************************************************************
next_oexpr_tree:
In: stem in an expression tree that is joined by ',' operator
Out: next stem to the right joined by ',' operator, or NULL if the
current stem is the rightmost
*************************************************************************/
struct output_expression *next_oexpr_tree(struct output_expression *leaf) {
for (; leaf->up != NULL; leaf = leaf->up) {
if (leaf->up->left == leaf)
return first_oexpr_tree((struct output_expression *)leaf->up->right);
}
return NULL;
}
/*************************************************************************
dupl_oexpr_tree:
In: output_expression tree
place to allocate new output_expressions
Out: a copy of the tree, or NULL if there was a memory error.
Note: leaves are not copied, just the expression structure.
*************************************************************************/
struct output_expression *dupl_oexpr_tree(struct output_expression *root,
struct mem_helper *oexpr_mem) {
struct output_expression *sprout;
sprout = (struct output_expression *)mem_get(oexpr_mem);
if (sprout == NULL)
return NULL;
memcpy(sprout, root, sizeof(struct output_expression));
if (root->left != NULL &&
(root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_OEXPR) {
sprout->left = dupl_oexpr_tree((struct output_expression *)root->left, oexpr_mem);
if (sprout->left == NULL)
return NULL;
}
if (root->right != NULL &&
(root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_OEXPR) {
sprout->right = dupl_oexpr_tree((struct output_expression *)root->right, oexpr_mem);
if (sprout->right == NULL)
return NULL;
}
return sprout;
}
/*************************************************************************
eval_oexpr_tree:
In: root of an output_expression tree
flag indicating whether to recalculate values marked CONST
Out: no return value. The value member variable of each
output_expression in the tree is updated to be accurate given
current leaf values.
*************************************************************************/
void eval_oexpr_tree(struct output_expression *root, int skip_const) {
double lval = 0.0;
double rval = 0.0;
if ((root->expr_flags & OEXPR_TYPE_CONST) && skip_const)
return;
if (root->left != NULL) {
if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_INT)
lval = (double)*((int *)root->left);
else if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_DBL)
lval = *((double *)root->left);
else if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_OEXPR) {
eval_oexpr_tree((struct output_expression *)root->left, skip_const);
lval = ((struct output_expression *)root->left)->value;
}
}
if (root->right != NULL) {
if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_INT)
rval = (double)*((int *)root->right);
else if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_DBL)
rval = *((double *)root->right);
else if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_OEXPR) {
eval_oexpr_tree((struct output_expression *)root->right, skip_const);
rval = ((struct output_expression *)root->right)->value;
}
}
switch (root->oper) {
case '=':
break;
case '(':
case '#':
case '@':
if (root->right != NULL)
root->value = lval + rval;
else
root->value = lval;
break;
case '_':
root->value = -lval;
break;
case '+':
root->value = lval + rval;
break;
case '-':
root->value = lval - rval;
break;
case '*':
root->value = lval * rval;
break;
case '/':
root->value = (!distinguishable(rval, 0, EPS_C)) ? 0 : lval / rval;
break;
default:
break;
}
}
/*************************************************************************
oexpr_flood_convert
In: root of an expression tree
operator that we don't want any more
operator that we want to replace it
Out: no return value. The old operator is replaced with the new
one recursively, but only as deep as the old operator remains
unbroken (so it's like a flood fill starting with the root).
*************************************************************************/
void oexpr_flood_convert(struct output_expression *root, char old_oper,
char new_oper) {
for (; root != NULL;
root = ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_OEXPR)
? (struct output_expression *)root->right
: NULL) {
if (root->oper != old_oper)
return;
root->oper = new_oper;
if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_OEXPR)
oexpr_flood_convert((struct output_expression *)root->left, old_oper,
new_oper);
}
}
/*************************************************************************
oexpr_title:
In: root of an expression tree
Out: text string that describes what is in that tree, or NULL if
there is a memory error.
Note: the value is recursively generated, but title member variables
of the expression are not set. The function keeps track of
them on the fly.
*************************************************************************/
char *oexpr_title(struct output_expression *root) {
struct output_request *orq;
char *lstr, *rstr, *str;
lstr = rstr = NULL;
if (root->expr_flags & OEXPR_TYPE_CONST) {
if ((root->expr_flags & OEXPR_TYPE_MASK) == OEXPR_LEFT_INT)
return alloc_sprintf("%d", (int)root->value);
else if ((root->expr_flags & OEXPR_TYPE_MASK) == OEXPR_TYPE_DBL)
return alloc_sprintf("%.8g", root->value);
else
return NULL;
}
if (root->left != NULL) {
if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_INT)
lstr = alloc_sprintf("%d", *((int *)root->left));
else if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_DBL)
lstr = alloc_sprintf("%.8g", *((double *)root->left));
else if ((root->expr_flags & OEXPR_LEFT_MASK) == OEXPR_LEFT_OEXPR)
lstr = oexpr_title((struct output_expression *)root->left);
}
if (root->right != NULL) {
if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_INT)
rstr = alloc_sprintf("%d", *((int *)root->right));
else if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_DBL)
rstr = alloc_sprintf("%.8g", *((double *)root->right));
else if ((root->expr_flags & OEXPR_RIGHT_MASK) == OEXPR_RIGHT_OEXPR)
rstr = oexpr_title((struct output_expression *)root->right);
}
switch (root->oper) {
case '=':
free(rstr);
return lstr;
case '@':
free(lstr);
free(rstr);
return CHECKED_STRDUP("(complex)", NULL);
case '#':
if ((root->expr_flags & OEXPR_LEFT_MASK) != OEXPR_LEFT_REQUEST ||
root->left == NULL) {
free(lstr);
free(rstr);
return NULL;
}
orq = (struct output_request *)root->left;
free(lstr);
free(rstr);
return strdup(orq->count_target->name);
case '_':
if (lstr == NULL) {
free(rstr);
return NULL;
}
str = alloc_sprintf("-%s", lstr);
free(lstr);
free(rstr);
return str;
case '(':
if (lstr == NULL) {
free(rstr);
return NULL;
}
str = alloc_sprintf("(%s)", lstr);
free(lstr);
free(rstr);
return str;
case '+':
case '-':
case '*':
case '/':
if (lstr == NULL || rstr == NULL) {
free(lstr);
free(rstr);
return NULL;
}
str = alloc_sprintf("%s%c%s", lstr, root->oper, rstr);
free(lstr);
free(rstr);
return str;
default:
free(lstr);
free(rstr);
return NULL;
}
return NULL;
}
| C |
3D | mcellteam/mcell | src/version.sh | .sh | 4,701 | 153 | #!/bin/sh
ESCAPESCRIPT='s/\([\\"]\)/\\\\\1/g'
####################
### Gather flex info
if test -z "${LEX}"; then
LEX="flex"
fi
LEX_PATH=`which "${LEX}" 2>/dev/null`
if test -z "${LEX_PATH}"; then
LEX="(missing)"
LEX_PATH="(flex not found)"
elif test -x "${LEX_PATH}"; then
LEX_VERSION=`${LEX} --version`
else
LEX_LEXER_PREBUILT=`dirname $0`/mdllex.flex.c
if test -r "${LEX_LEXER_PREBUILT}"; then
LEX_VERSION="not installed - using pregenerated lexer"
else
LEX_VERSION="not installed"
fi
fi
LFLAGS="-Crema ${LFLAGS}"
LFLAGS=`echo $LFLAGS | sed "${ESCAPESCRIPT}"`
####################
### Gather bison info
if test -z "${YACC}"; then
YACC="bison"
elif test "${YACC}" = "bison -y"; then
YACC="bison"
fi
YACC_PATH=`which "${YACC}" 2>/dev/null`
if test -z "${YACC_PATH}"; then
YACC="(missing)"
YACC_PATH="(bison not found)"
elif test -x "${YACC_PATH}"; then
YACC_VERSION=`${YACC} --version | head -1`
else
YACC_PARSER_PREBUILT=`dirname $0`/mdlparse.bison.c
if test -r "${YACC_PARSER_PREBUILT}"; then
YACC_VERSION=`head -1 ${YACC_PARSER_PREBUILT} | sed 's/^.*GNU Bison \(.*\)\. .*/not installed - using parser pregenerated by GNU Bison \1/'`
else
YACC_VERSION="not installed - build should fail"
fi
fi
if test -z "${YFLAGS}"; then
YFLAGS=""
fi
YFLAGS=`echo $YFLAGS | sed "${ESCAPESCRIPT}"`
####################
### Gather cc info
if test -z "${CC}"; then
CC="cc"
fi
CC_PATH=`which ${CC} 2>/dev/null`
if test -x "${CC_PATH}"; then
CC_VERSION=`${CC} --version | head -1`
fi
if test -z "${CFLAGS}"; then
CFLAGS=""
fi
CFLAGS=`echo $CFLAGS | sed "${ESCAPESCRIPT}"`
if test -z "${LD}"; then
LD="ld"
fi
####################
### Gather ld info
LD_PATH=`which ${LD} 2>/dev/null`
if test -x "${LD_PATH}"; then
LD_VERSION=`${LD} --version | head -1`
fi
if test -z "${LDFLAGS}"; then
LDFLAGS=""
fi
LDFLAGS=`echo $LDFLAGS | sed "${ESCAPESCRIPT}"`
####################
### Gather buildhost info
BUILD_USER=`id -un`
BUILD_HOST=`hostname -f`
SRC_DIR=`dirname $0`
SRC_DIR=`sh -c "cd ${SRC_DIR} && pwd"`
BUILD_DIR=`pwd`
BUILD_DATE=`date`
BUILD_UNAME=`uname -a`
####################
### Gather program version info
repo_dir=`dirname $0`
version_path=${repo_dir}/version.txt
#version_path=`dirname $0`/version.txt
MCELL_VERSION=`cat "${version_path}"`
MCELL_HAVE_REVISION_INFO=0
GIT=`which git 2>/dev/null`
if test -x "${GIT}"; then
if ( cd ${repo_dir} ; "${GIT}" describe --all --abbrev=4 HEAD >/dev/null 2>&1; ) then
MCELL_HAVE_REVISION_INFO=1
fi
fi
echo "/****************************************************************"
echo " * This file is automatically generated. Do not edit it."
echo " * version.h updated at ${BUILD_DATE} on ${BUILD_HOST} by ${BUILD_USER}"
echo " ****************************************************************/"
echo
echo "/* Program version info */"
echo "#define MCELL_VERSION \"${MCELL_VERSION}\""
if test "$MCELL_HAVE_REVISION_INFO" = "1"; then
echo "#define MCELL_REVISION $(cd ${repo_dir} ; git show -s --format=\"%h\") "
echo "#define MCELL_REVISION_DATE $(cd ${repo_dir} ; git show -s --format=\"%aD\")"
echo "#define MCELL_REVISION_COMMITTED 1"
echo "#define MCELL_REVISION_BRANCH \"$(cd ${repo_dir} ; git rev-parse --abbrev-ref HEAD)\""
else
echo "#define MCELL_REVISION \"\""
echo "#define MCELL_REVISION_DATE \"\""
echo "#define MCELL_REVISION_COMMITTED 0"
echo "#define MCELL_REVISION_BRANCH \"not in VCS\""
fi
echo
echo "/* Build info */"
echo "#define MCELL_BUILDDATE \"${BUILD_DATE}\""
echo "#define MCELL_BUILDUSER \"${BUILD_USER}\""
echo "#define MCELL_BUILDHOST \"${BUILD_HOST}\""
echo "#define MCELL_SRCDIR \"${SRC_DIR}\""
echo "#define MCELL_BUILDDIR \"${BUILD_DIR}\""
echo "#define MCELL_BUILDUNAME \"${BUILD_UNAME}\""
echo
echo "/* Tool identity and version info */"
echo "#define MCELL_FLEX \"${LEX}\""
echo "#define MCELL_FLEX_PATH \"${LEX_PATH}\""
echo "#define MCELL_FLEX_VERSION \"${LEX_VERSION}\""
echo "#define MCELL_FLEX_FLAGS \"${LFLAGS}\""
echo "#define MCELL_BISON \"${YACC}\""
echo "#define MCELL_BISON_PATH \"${YACC_PATH}\""
echo "#define MCELL_BISON_VERSION \"${YACC_VERSION}\""
echo "#define MCELL_BISON_FLAGS \"${YFLAGS}\""
echo "#define MCELL_CC \"${CC}\""
echo "#define MCELL_CC_PATH \"${CC_PATH}\""
echo "#define MCELL_CC_VERSION \"${CC_VERSION}\""
echo "#define MCELL_LD \"${LD}\""
echo "#define MCELL_LD_PATH \"${LD_PATH}\""
echo "#define MCELL_LD_VERSION \"${LD_VERSION}\""
echo
echo "/* Build options */"
echo "#define MCELL_LFLAGS \"${LFLAGS}\""
echo "#define MCELL_YFLAGS \"${YFLAGS}\""
echo "#define MCELL_CFLAGS \"${CFLAGS}\""
echo "#define MCELL_LDFLAGS \"${LDFLAGS}\""
| Shell |
3D | mcellteam/mcell | src/config-win.h | .h | 23,541 | 739 | /******************************************************************************
*
* Copyright (C) 2006-2025 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/* Windows-specific includes and defines */
/*
This file has includes, declarations, and function definitions to make the code
compile on Windows.
The functions where problems may exist are noted below with their caveats.
Some caveats could be addressed with additional code if necessary.
Wrapped Functions: (the function is available in Windows but certain features
are not available)
strerror_r - return value is POSIX-like (not GCC-like) [strerror_s is used]
ctime_r - must be given a fixed-sized on-stack char buffer [ctime_s is
used]
strftime - [adds support for many of the additional format string]
gethostname - [adds special initialization during the first call]
stat/fstat - [adds support for symlink detection]
rename - [adds support for atomic rename]
mkdir - mode argument is ignored [adds the mode argument to the
declaration]
Emulated functions:
getrusage - only supports RUSAGE_SELF, output struct only has ru_utime and
ru_stime, errno not always set, cannot include <sys/resource.h>
symlink - always fails on XP
alarm - return value is not correct, must use set_alarm_handler instead
of sigaction
*/
#ifndef MCELL_CONFIG_WIN_H
#define MCELL_CONFIG_WIN_H
#ifdef _MSC_VER
typedef unsigned int mode_t;
#pragma warning( disable : 4996 )
#endif
#ifndef MINGW_HAS_SECURE_API
#define MINGW_HAS_SECURE_API /* required for MinGW to expose _s functions */
#endif
#undef __USE_MINGW_ANSI_STDIO
#define __USE_MINGW_ANSI_STDIO \
1 /* allows use of GNU-style printf format strings */
#define PRINTF_FORMAT(arg) \
__attribute__((__format__( \
gnu_printf, arg, arg + 1))) /* for functions that use printf-like \ \ \ \
arguments this corrects warnings */
#define PRINTF_FORMAT_V(arg) __attribute__((__format__(gnu_printf, arg, 0)))
#define WIN32_LEAN_AND_MEAN /* removes many unneeded Windows definitions */
#undef _WIN32_WINNT
#define _WIN32_WINNT 0x0502
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <stdlib.h>
#include <direct.h> /* many POSIX-like functions */
#include <errno.h>
#include <stdio.h> /* _snprintf */
#include <stdint.h>
#include <time.h>
typedef unsigned short u_short;
typedef unsigned int u_int;
typedef unsigned long u_long;
// typedef int errno_t;
/* Remove some windows.h definitions that may cause problems */
#undef TRUE
#undef FALSE
#undef ERROR
#undef TRANSPARENT
#undef FILE_OVERWRITE
#undef FILE_CREATE
#ifdef _MSC_VER
#define getcwd _getcwd
#define strdup _strdup
#define va_copy(d, s) ((d) = (s))
#endif
/* Macro for eliminating "unused variable" or "unused parameter" warnings. */
#define UNUSED(p) ((void)(p))
#ifndef __GNUC__
#ifndef __attribute__
#define __attribute__(x) /* empty */
#define __restrict__
#endif
#endif
/* MinGW does not include this in any header but has it in the libraries */
#include <string.h> /* include this to make sure we have definitions for the \ \
\ \
\ \ \
declaration below */
_CRTIMP errno_t __cdecl strerror_s(char *_Buf, size_t _SizeInBytes, int errnum);
inline static int strerror_r(int errnum, char *buf, size_t buflen) {
errno_t err = strerror_s(buf, buflen, errnum);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
/* ctime_r wrapped function */
inline static char *_ctime_r_helper(const time_t *timep, char *buf,
size_t buflen) {
#if defined(_WIN64) || defined(_MSC_VER)
errno_t err = _ctime64_s(buf, buflen, timep);
#else
errno_t err = _ctime32_s(buf, buflen, timep);
#endif
if (err != 0) {
errno = err;
return NULL;
}
return buf;
}
#define ctime_r(timep, buf) \
_ctime_r_helper(timep, buf, sizeof(buf)) // char *ctime_r(const time_t *timep,
// char *buf) { }
/* strftime function with many additional format codes supported on *nix
* machines */
inline static int _is_leap_year(int y) {
return (y & 3) == 0 && ((y % 25) != 0 || (y & 15) == 0);
}
inline static int _iso8061_weeknum(const struct tm *timeptr) {
int Y = timeptr->tm_year, M = timeptr->tm_mon;
int T = timeptr->tm_mday + 4 -
(timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday); // nearest Thursday
if (M == 12 && T > 31) {
return 1;
}
if (M == 1 && T < 1) {
--Y;
M = 12;
T += 31;
}
int D = 275 * M / 9 + T - 31 +
(M > 2 ? (_is_leap_year(Y) - 2) : 0); // day of year
return 1 + D / 7;
}
inline static int _iso8061_wn_year(const struct tm *timeptr) {
int T = timeptr->tm_mday + 4 -
(timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday); // nearest Thursday
return timeptr->tm_year + 1900 +
((timeptr->tm_mon == 11 && T > 31)
? +1
: ((timeptr->tm_mon == 0 && T < 1) ? -1 : 0));
}
inline static void _strnlwr(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = tolower(*str);
}
}
inline static void _strnupr(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = toupper(*str);
}
}
inline static void _strnchcase(char *str, size_t count) {
for (char *end = str + count; str < end; ++str) {
*str = isupper(*str) ? tolower(*str) : toupper(*str);
}
}
__attribute__((__format__(
gnu_strftime, 3,
0))) inline static size_t _win_strftime(char *strDest, size_t maxsize,
const char *format,
const struct tm *timeptr) {
/* TODO: verify against *nix version, including edge cases */
struct tm t = *timeptr;
const char *f2, *f1 = format;
char *out = strDest, *out_end = strDest + maxsize;
char fbuf[3] = "%%", buf[64];
while ((f2 = strchr(f1, '%')) != NULL) {
if (f2 - f1 > out_end - out) {
return 0;
}
strncpy(out, f1, f2 - f1);
out += f2 - f1;
++f2;
/* Flag */
char flag;
if (*f2 == '_' || *f2 == '-' || *f2 == '0' || *f2 == '^' || *f2 == '#') {
flag = *(f2++);
} else {
flag = 0;
}
/* Width */
size_t width = 0;
while (isdigit(*f2)) {
width = 10 * (width - '0') + *(f2++);
}
if ((ptrdiff_t)width > out_end - out) {
return 0;
}
/* Modifier */
/* TODO: support modifiers, currently they are read but never used */
// char modifier = 0;
if (*f2 == 'E') {
f2++;
// if (*f2 == 'c' || *f2 == 'C' || *f2 == 'x' || *f2 == 'X' || *f2 == 'y'
// || *f2 == 'Y')
// modifier = 'E'; /* E only before: c, C, x, X, y, Y */
} else if (*f2 == 'O') {
f2++;
// if (*f2 == 'd' || *f2 == 'e' || *f2 == 'H' || *f2 == 'I' || *f2 == 'm'
// || *f2 == 'M' || *f2 == 'S' || *f2 == 'u' || *f2 == 'U' || *f2 == 'V'
// || *f2 == 'w' || *f2 == 'W' || *f2 == 'Y')
// modifier = 'O'; /* O only before: d, e, H, I, m, M, S, u, U, V, w,
// W, y */
}
/* Get content */
size_t count;
int is_numeric = 0, is_num_space_padded = 0;
switch (*f2) {
/* single character formats */
case 0:
buf[0] = '%';
count = 1;
break;
case 'n':
buf[0] = '\n';
count = 1;
break;
case 't':
buf[0] = '\t';
count = 1;
break;
/* simple format equivalences */
case 'h':
count = strftime(buf, ARRAYSIZE(buf), "%b", timeptr);
break;
case 'D':
count = strftime(buf, ARRAYSIZE(buf), "%m/%d/%y", timeptr);
break;
case 'F':
count = strftime(buf, ARRAYSIZE(buf), "%Y-%m-%d", timeptr);
break;
case 'r':
count = strftime(buf, ARRAYSIZE(buf), "%I:%M:%S %p", timeptr);
break; /* TODO: this is actually supposed to be locale dependent? */
case 'R':
count = strftime(buf, ARRAYSIZE(buf), "%H:%M", timeptr);
break;
case 'T':
count = strftime(buf, ARRAYSIZE(buf), "%H:%M:%S", timeptr);
break;
case '+':
count = strftime(buf, ARRAYSIZE(buf), "%a %b %d %H:%M:%S %Z %Y", timeptr);
break;
/* lower-case conversions */
case 'P':
_strnlwr(buf, count = strftime(buf, ARRAYSIZE(buf), "%p", timeptr));
break;
/* pad with leading spaces instead of 0s */
case 'e':
count = strftime(buf, ARRAYSIZE(buf), "%d", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
case 'k':
count = strftime(buf, ARRAYSIZE(buf), "%H", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
case 'l':
count = strftime(buf, ARRAYSIZE(buf), "%I", timeptr);
is_num_space_padded = 1;
is_numeric = 1;
break;
/* sprintf conversions */
case 'C':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u",
(timeptr->tm_year + 1900) / 100);
is_numeric = 1;
break;
case 'u':
count = _snprintf(buf, ARRAYSIZE(buf), "%1u",
timeptr->tm_wday == 0 ? 7 : timeptr->tm_wday);
is_numeric = 1;
break;
#if defined(_WIN64) || defined(_MSC_VER)
case 's':
count = _snprintf(buf, ARRAYSIZE(buf), "%08Iu", mktime(&t));
is_numeric = 1;
break;
#else
case 's':
count = _snprintf(buf, ARRAYSIZE(buf), "%04Iu", mktime(&t));
is_numeric = 1;
break;
#endif
/* ISO 8601 week formats */
case 'V':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u", _iso8061_weeknum(timeptr));
is_numeric = 1;
break;
case 'G':
count = _snprintf(buf, ARRAYSIZE(buf), "%04u", _iso8061_wn_year(timeptr));
is_numeric = 1;
break;
case 'g':
count = _snprintf(buf, ARRAYSIZE(buf), "%02u",
_iso8061_wn_year(timeptr) % 100);
is_numeric = 1;
break;
/* supported by Windows natively (or a character that can't be converted,
* which will be converted to empty string) */
/* make sure is_numeric is set appropriately */
case 'd':
case 'H':
case 'I':
case 'j':
case 'm':
case 'M':
case 'S':
case 'U':
case 'w':
case 'W':
case 'y':
case 'Y':
is_numeric = 1;
fbuf[1] = *f2;
count = strftime(buf, ARRAYSIZE(buf), fbuf, timeptr);
break;
default:
fbuf[1] = *f2;
count = strftime(buf, ARRAYSIZE(buf), fbuf, timeptr);
break;
/* TODO: not sure if Windows' %z is the same as POSIX */
}
/* Write output */
size_t trim = 0;
char padding =
(flag == '_')
? ' '
: ((flag == '0')
? '0'
: (is_numeric ? (is_num_space_padded ? ' ' : '0') : ' '));
if (is_numeric) {
if (flag == '-') {
while (trim < count - 1 && buf[trim] == '0') {
++trim;
}
count -= trim;
} else if (padding == ' ') {
for (size_t i = 0; i < count - 1 && buf[i] == '0'; ++i) {
buf[i] = ' ';
}
}
} else if (flag == '^') {
_strnupr(buf, count);
} /* convert alphabetic characters in result string to upper case */
else if (flag == '#') {
_strnchcase(buf, count);
} /* swap the case of the result string */
if ((ptrdiff_t)count > out_end - out) {
return 0;
}
if (count < width) {
memset(out, padding, width - count);
out += width - count;
}
strncpy(out, buf + trim, count);
out += count;
f1 = f2 + 1;
}
/* copy remaining */
size_t len = strlen(f1);
strncpy(out, f1, len);
out[len] = 0;
return out - strDest + len;
}
#define strftime _win_strftime
#if 0
/* gethostname wrapped function */
#define WSADESCRIPTION_LEN 256
#define WSASYS_STATUS_LEN 128
#define SOCKET_ERROR -1
typedef struct WSAData {
WORD wVersion;
WORD wHighVersion;
#ifdef _WIN64
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char *lpVendorInfo;
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
#else
char szDescription[WSADESCRIPTION_LEN + 1];
char szSystemStatus[WSASYS_STATUS_LEN + 1];
unsigned short iMaxSockets;
unsigned short iMaxUdpDg;
char *lpVendorInfo;
#endif
} WSADATA, *LPWSADATA;
#endif
#if 0
typedef long long int(WINAPI *FUNC_WSAStartup)(WORD wVersionRequested,
LPWSADATA lpWSAData);
typedef long long int(WINAPI *FUNC_WSAGetLastError)(void);
typedef long long int(WINAPI *FUNC_gethostname)(char *name, int namelen);
static FUNC_WSAStartup WSAStartup = NULL;
static FUNC_WSAGetLastError WSAGetLastError = NULL;
static FUNC_gethostname win32gethostname = NULL;
inline static int gethostname(char *name, size_t len) {
if (len > INT_MAX) {
errno = EINVAL;
return -1;
}
/* dynamically load the necessary function and initialize the Winsock DLL */
if (win32gethostname == NULL) {
HMODULE ws2 = LoadLibraryA("ws2_32");
WSADATA wsaData;
WSAStartup = (FUNC_WSAStartup)GetProcAddress(ws2, "WSAStartup");
WSAGetLastError =
(FUNC_WSAGetLastError)GetProcAddress(ws2, "WSAGetLastError");
win32gethostname = (FUNC_gethostname)GetProcAddress(ws2, "gethostname");
if (ws2 == NULL || WSAStartup == NULL || WSAGetLastError == NULL ||
win32gethostname == NULL || WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
if (ws2) {
FreeLibrary(ws2);
}
win32gethostname = NULL;
errno = EPERM;
return -1;
}
}
/* call the Win32 gethostname() */
if (win32gethostname(name, (int)len) == SOCKET_ERROR) {
/* error */
switch (WSAGetLastError()) {
case WSAEFAULT:
errno = name ? ENAMETOOLONG : EFAULT;
break;
case WSANOTINITIALISED:
case WSAENETDOWN:
case WSAEINPROGRESS:
errno = EAGAIN;
break;
}
return -1;
}
return 0;
}
#endif
/* getrusage emulated function, normally in <sys/resources.h> */
#if !defined(_TIMEVAL_DEFINED) // && !defined(_MSC_VER)
#define _TIMEVAL_DEFINED
struct timeval {
long tv_sec;
long tv_usec;
};
#endif
struct rusage {
struct timeval ru_utime; /* user CPU time used */
struct timeval ru_stime; /* system CPU time used */
};
#define RUSAGE_SELF 0
inline static int getrusage(int who, struct rusage *usage) {
if (who != RUSAGE_SELF) {
errno = EINVAL;
return -1;
}
if (usage == NULL) {
errno = EFAULT;
return -1;
}
FILETIME ftCreation, ftExit, ftKernel, ftUser;
if (GetProcessTimes(GetCurrentProcess(), &ftCreation, &ftExit, &ftKernel,
&ftUser) == 0) {
/* error */
/* FIXME: set errno based on GetLastError() */
return -1;
}
ULONGLONG user =
(((ULONGLONG)ftUser.dwHighDateTime) << 32) + ftUser.dwLowDateTime;
ULONGLONG kernel =
(((ULONGLONG)ftKernel.dwHighDateTime) << 32) + ftKernel.dwLowDateTime;
/* Value is in 100 nanosecond intervals */
/* t / 10000000 => timeval.sec */
/* (t % 10000000) / 10 => timeval.usec */
usage->ru_utime.tv_usec = (long)((user % 10000000) / 10);
usage->ru_utime.tv_sec = (long)(user / 10000000);
usage->ru_stime.tv_usec = (long)((kernel % 10000000) / 10);
usage->ru_stime.tv_sec = (long)(kernel / 10000000);
return 0;
}
static int gettimeofday(struct timeval * tp, void*)
{
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
// This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
// until 00:00:00 January 1, 1970
const uint64_t EPOCH = ((uint64_t) 116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime( &system_time );
SystemTimeToFileTime( &system_time, &file_time );
time = ((uint64_t)file_time.dwLowDateTime ) ;
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long) ((time - EPOCH) / 10000000L);
tp->tv_usec = (long) (system_time.wMilliseconds * 1000);
return 0;
}
#if 0
/* symlink emulated function, normally in <unistd.h> */
#define SYMBOLIC_LINK_FLAG_FILE 0x0
#define SYMBOLIC_LINK_FLAG_DIRECTORY 0x1
typedef long long int (WINAPI *FUNC_CreateSymbolicLink)(LPCSTR lpSymlinkFileName,
LPCSTR lpTargetFileName,
DWORD dwFlags);
static FUNC_CreateSymbolicLink CreateSymbolicLink = NULL;
inline static int _win_is_dir(const char *path) {
DWORD attr = GetFileAttributesA(path);
return attr != INVALID_FILE_ATTRIBUTES &&
(attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
}
inline static int symlink(const char *oldpath, const char *newpath) {
/* dynamically load the CreateSymbolicLink function */
if (CreateSymbolicLink == NULL) {
/* requires Windows Vista or newer */
CreateSymbolicLink = (FUNC_CreateSymbolicLink)GetProcAddress(
GetModuleHandleA("kernel32"), "CreateSymbolicLinkA");
if (CreateSymbolicLink == NULL) {
errno = EPERM;
return -1;
}
}
if (!CreateSymbolicLink(newpath, oldpath, _win_is_dir(oldpath))) {
/* error */
char buf[MAX_PATH + 1];
switch (GetLastError()) {
case ERROR_INVALID_FUNCTION:
errno = EPERM;
break;
case ERROR_INVALID_REPARSE_DATA: /* when oldpath == "" */
case ERROR_PATH_NOT_FOUND:
errno = strlen(getcwd(buf, sizeof(buf))) + strlen(newpath) >= MAX_PATH
? ENAMETOOLONG
: ENOENT;
break; /* or ENOTDIR or ELOOP(?) */
case ERROR_ACCESS_DENIED:
errno = _win_is_dir(newpath) ? EEXIST : EACCES;
break; /* reports ERROR_ACCESS_DENIED when newpath already exists as a
directory */
case ERROR_NOT_ENOUGH_MEMORY:
errno = ENOMEM;
break;
case ERROR_WRITE_PROTECT:
errno = EROFS;
break;
case ERROR_INVALID_PARAMETER:
errno = EFAULT;
break;
case ERROR_DISK_FULL:
errno = ENOSPC;
break;
case ERROR_ALREADY_EXISTS:
errno = EEXIST;
break;
default:
errno = EIO;
break;
}
return -1;
}
return 0;
}
#endif
/* stat and fstat wrapped function */
/* adds S_IFLNK support to stat(path, &s) - necessary since Windows' stat does
* not set S_IFLNK (or even define S_IFLNK) */
#include <sys/stat.h>
#ifndef FSCTL_GET_REPARSE_POINT
#define FSCTL_GET_REPARSE_POINT \
(0x00000009 << 16) | (42 << 2) | 0 | \
(0 << 14) // CTL_CODE(FILE_DEVICE_FILE_SYSTEM, 42, METHOD_BUFFERED,
// FILE_ANY_ACCESS) // REPARSE_DATA_BUFFER
#endif
#define S_IFLNK 0120000
#define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK)
inline static int _is_symlink(const char *path) {
HANDLE hFile = CreateFileA(
path, GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
return 0;
}
DWORD *data = (DWORD *)malloc(MAXIMUM_REPARSE_DATA_BUFFER_SIZE), size;
if (data == NULL) {
CloseHandle(hFile);
return 0;
}
BOOL success = DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, data,
MAXIMUM_REPARSE_DATA_BUFFER_SIZE, &size, NULL);
DWORD tag = *data;
free(data);
CloseHandle(hFile);
return success && tag == IO_REPARSE_TAG_SYMLINK;
}
#ifdef stat
/*
we have a version of MinGW that uses a #define to map stat to _stat64
this introduces a ton of problems
to make this work we need to do something similar
since the stat structure is "changing" we also need an fstat...
*/
#undef stat
#undef fstat
#define stat _win_stat
#define fstat _win_fstat
struct stat { // equivalent to _stat64
_dev_t st_dev;
_ino_t st_ino;
unsigned short st_mode;
short st_nlink;
short st_uid;
short st_gid;
_dev_t st_rdev;
__MINGW_EXTENSION __int64 st_size;
__time64_t st_atime;
__time64_t st_mtime;
__time64_t st_ctime;
};
inline static int stat(const char *path, struct stat *buf) {
int retval = _stat64(path, (struct _stat64 *)buf);
if (retval == 0 && _is_symlink(path)) {
buf->st_mode |= S_IFLNK;
}
return retval;
}
inline static int fstat(int fd, struct stat *buf) {
return _fstat64(fd, (struct _stat64 *)buf);
}
#else
// we just use the normal forwarding setup
// no need to treat fstat special
inline static int _win_stat(const char *path, struct stat *buf) {
int retval = stat(path, buf);
if (retval == 0 && _is_symlink(path)) {
buf->st_mode |= S_IFLNK;
}
return retval;
}
#define stat(path, buf) _win_stat(path, buf)
#endif
/* alarm emulated function, normally in <unistd.h> */
/* sigaction(SIGALRM, ...) replaced by set_alarm_handler() */
#define SIGALRM 14
typedef void(__cdecl *ALARM_CB)(int);
static ALARM_CB _alarm_cb = NULL;
static HANDLE _timer = NULL;
inline static void _win_alarm_cb(PVOID lpParameter, BOOLEAN TimerOrWaitFired) {
_timer = NULL;
_alarm_cb(SIGALRM);
}
inline static void set_alarm_handler(ALARM_CB handler) { _alarm_cb = handler; }
inline static unsigned alarm(unsigned seconds) {
unsigned retval = 0;
if (_timer) {
retval = 1; /* fixme: get actual time left in the timer and return that */
DeleteTimerQueueTimer(NULL, _timer, NULL);
_timer = NULL;
}
if (!CreateTimerQueueTimer(&_timer, NULL, (WAITORTIMERCALLBACK)_win_alarm_cb,
NULL, seconds * 1000, 0, WT_EXECUTEONLYONCE)) {
retval = (unsigned)-1;
}
return retval;
}
/* atomic rename wrapped function */
/* Windows rename is not atomic, but there is ReplaceFile (only when actually
* replacing though) */
int _win_rename(const char *old, const char *new_name);
//#define rename _win_rename
/* mkdir wrapped function */
inline static int _win_mkdir(const char *pathname, mode_t mode) {
/* TODO: do something with the mode argument */
UNUSED(mode);
return mkdir(pathname);
}
#define mkdir _win_mkdir
// some annoying macros from windows.h
#undef IGNORE
#undef DIFFERENCE
#endif
| Unknown |
3D | mcellteam/mcell | src/volume_output.c | .c | 11,006 | 362 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include "volume_output.h"
#include "logging.h"
#include "mcell_structs.h"
#include "sched_util.h"
#include "vol_util.h"
#include "strfunc.h"
#include "util.h"
#include <errno.h>
#include <math.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
static int produce_item_header(FILE *out_file, struct volume_output_item *vo);
static int produce_mol_counts(struct volume *wrld, FILE *out_file,
struct volume_output_item *vo);
static int find_species_in_array(struct species **mols, int num_mols,
struct species *ptr);
static int reschedule_volume_output_item(struct volume *wrld,
struct volume_output_item *vo);
/*
* Output a block of volume data as requested by the 'vo' object.
*/
int update_volume_output(struct volume *wrld, struct volume_output_item *vo) {
int failure = 0;
char *filename;
switch (wrld->notify->volume_output_report) {
case NOTIFY_NONE:
break;
case NOTIFY_BRIEF:
case NOTIFY_FULL:
mcell_log("Updating volume output '%s' scheduled at time %.15g on "
"iteration %lld.",
vo->filename_prefix, vo->t, wrld->current_iterations);
break;
default:
UNHANDLED_CASE(wrld->notify->volume_output_report);
}
/* build the filename */
filename = CHECKED_SPRINTF("%s.%lld.dat", vo->filename_prefix, wrld->current_iterations);
/* Try to make the directory if it doesn't exist */
if (make_parent_dir(filename)) {
free(filename);
return 1;
}
/* Output the volume item */
failure = output_volume_output_item(wrld, filename, vo);
free(filename);
/* Reschedule this volume item, if appropriate */
if (!failure)
failure = reschedule_volume_output_item(wrld, vo);
/* Should we return failure if we can't create the file? Doing so will bring
* down the entire sim...
*/
return failure;
}
/*
* Produce the output for a volume item.
*/
int output_volume_output_item(struct volume *wrld, char const *filename,
struct volume_output_item *vo) {
FILE *f = fopen(filename, "w");
if (f == NULL) {
mcell_perror_nodie(errno, "Couldn't open volume output file '%s'.",
filename);
return 1;
}
if (produce_item_header(f, vo))
goto failure;
if (produce_mol_counts(wrld, f, vo))
goto failure;
fclose(f);
return 0;
failure:
fclose(f);
return 1;
}
/*
* Write the molecule counts to the file.
*
* XXX: Update this code to be smarter about the tradeoff between large slab
* size (= large mem usage) and small slab size (= worse cache usage).
*/
static int produce_mol_counts(struct volume *wrld, FILE *out_file,
struct volume_output_item *vo) {
struct volume_molecule *curmol;
int *counters, *countersptr;
int k, u, v;
double z = vo->location.z, y = vo->location.y, x = vo->location.x;
double x_lim = x + vo->voxel_size.x * (double)vo->nvoxels_x;
double y_lim = y + vo->voxel_size.y * (double)vo->nvoxels_y;
struct subvolume *cur_partition_z;
double z_lim_part;
/* Allocate memory for counters. */
counters =
CHECKED_MALLOC_ARRAY(int, vo->nvoxels_x * vo->nvoxels_y, "voxel slab");
cur_partition_z = find_subvolume(wrld, &vo->location, NULL);
if (cur_partition_z == NULL) {
free(counters);
mcell_internal_error(
"While counting at [%g, %g, %g]: point isn't within a partition.", x, y,
z);
/*return 1;*/
}
z_lim_part = wrld->z_fineparts[cur_partition_z->urb.z];
/* For each slab: */
double r_voxsz_x = 1.0 / vo->voxel_size.x;
double r_voxsz_y = 1.0 / vo->voxel_size.y;
for (k = 0; k < vo->nvoxels_z; ++k) {
double z_lim_slab = z + vo->voxel_size.z;
struct subvolume *cur_partition_y;
/* reset counters for this slab */
memset(counters, 0, sizeof(int) * vo->nvoxels_x * vo->nvoxels_y);
/* Loop over relevant partitions */
keep_counting:
cur_partition_y = cur_partition_z;
while (cur_partition_y != NULL &&
wrld->y_fineparts[cur_partition_y->llf.y] < y_lim) {
struct subvolume *cur_partition = cur_partition_y;
while (cur_partition != NULL &&
wrld->x_fineparts[cur_partition->llf.x] < x_lim) {
/* Count molecules */
struct per_species_list *psl;
int check_nonreacting = 0;
int i = 0;
for (i = 0; i < vo->num_molecules; ++i) {
if (!(vo->molecules[i]->flags & CAN_VOLVOL)) {
check_nonreacting = 1;
break;
}
}
for (psl = cur_partition->species_head; psl != NULL; psl = psl->next) {
if (psl->properties == NULL) {
if (!check_nonreacting)
continue;
else {
for (curmol = psl->head; curmol != NULL;
curmol = curmol->next_v) {
/* See if we're interested in this molecule */
if (vo->num_molecules == 1) {
if (*vo->molecules != curmol->properties)
continue;
} else {
if ((find_species_in_array(vo->molecules, vo->num_molecules,
curmol->properties)) == -1)
continue;
}
/* Skip molecules not in our slab */
if (curmol->pos.z < z || curmol->pos.z >= z_lim_slab)
continue;
/* Skip molecules outside our domain */
if (curmol->pos.x < x || curmol->pos.x >= x_lim ||
curmol->pos.y < y || curmol->pos.y >= y_lim)
continue;
/* We've got a winner! Add one to the appropriate voxel. */
++counters[((int)floor((curmol->pos.y - y) * r_voxsz_y)) *
vo->nvoxels_x +
(int)floor((curmol->pos.x - x) * r_voxsz_x)];
}
}
} else {
/* See if we're interested in this molecule */
if (vo->num_molecules == 1) {
if (*vo->molecules != psl->properties)
continue;
} else {
if ((find_species_in_array(vo->molecules, vo->num_molecules,
psl->properties)) == -1)
continue;
}
for (curmol = psl->head; curmol != NULL; curmol = curmol->next_v) {
/* Skip molecules not in our slab */
if (curmol->pos.z < z || curmol->pos.z >= z_lim_slab)
continue;
/* Skip molecules outside our domain */
if (curmol->pos.x < x || curmol->pos.x >= x_lim ||
curmol->pos.y < y || curmol->pos.y >= y_lim)
continue;
/* We've got a winner! Add one to the appropriate voxel. */
++counters[((int)floor((curmol->pos.y - y) * r_voxsz_y)) *
vo->nvoxels_x +
(int)floor((curmol->pos.x - x) * r_voxsz_x)];
}
}
}
/* Advance to next x-partition */
cur_partition =
traverse_subvol(cur_partition, X_POS, wrld->ny_parts,
wrld->nz_parts);
}
/* Advance to next y-partition */
cur_partition_y =
traverse_subvol(cur_partition_y, Y_POS, wrld->ny_parts,
wrld->nz_parts);
}
/* If the slab crosses a Z boundary, keep on truckin' */
if (z_lim_slab >= z_lim_part) {
/* If we can get to the next partition, don't update slab and don't
* spill!
*/
cur_partition_z =
traverse_subvol(cur_partition_z, Z_POS, wrld->ny_parts,
wrld->nz_parts);
if (cur_partition_z != NULL) {
z_lim_part = wrld->z_fineparts[cur_partition_z->urb.z];
goto keep_counting;
}
} else {
z = z_lim_slab;
/* z_lim_slab will be updated on the next pass through the loop. */
}
/* Spill our counts */
countersptr = counters;
for (u = 0; u < vo->nvoxels_y; ++u) {
for (v = 0; v < vo->nvoxels_x; ++v)
fprintf(out_file, "%d ", *countersptr++);
fprintf(out_file, "\n");
}
/* Extra newline to put visual separation between slabs */
fprintf(out_file, "\n");
}
free(counters);
return 0;
}
/*
* Binary search for a pointer in an array of pointers.
*/
static int find_species_in_array(struct species **mols, int num_mols,
struct species *ptr) {
int lo = 0, hi = num_mols;
while (hi - lo > 1) {
int mid = (hi + lo) / 2;
if (mols[mid] > ptr)
hi = mid;
else if (mols[mid] < ptr)
lo = mid;
else
return mid;
}
if (mols[lo] == ptr)
return lo;
else
return -1;
}
/*
* Write the item header to the file.
*/
static int produce_item_header(FILE *out_file, struct volume_output_item *vo) {
if (fprintf(out_file, "# nx=%d ny=%d nz=%d time=%g\n", vo->nvoxels_x,
vo->nvoxels_y, vo->nvoxels_z, vo->t) < 0) {
mcell_perror_nodie(errno, "Couldn't write header of volume output file.");
return 1;
}
return 0;
}
/*
* Reschedule a volume output item, if necessary.
*/
static int reschedule_volume_output_item(struct volume *wrld,
struct volume_output_item *vo) {
/* Find the next time */
if (vo->timer_type == OUTPUT_BY_STEP)
vo->t += (vo->step_time / wrld->time_unit);
else {
double time_scale = 0.0;
/* Check if we're done */
if (vo->next_time == vo->times + vo->num_times) {
free(vo->filename_prefix);
free(vo->molecules);
free(vo->times);
free(vo);
return 0;
}
/* Compute the next time and advance the next_time ptr */
if (vo->timer_type == OUTPUT_BY_ITERATION_LIST)
time_scale = 1.0;
else
time_scale = 1.0 / wrld->time_unit;
vo->t = (*vo->next_time++) * time_scale;
}
switch (wrld->notify->volume_output_report) {
case NOTIFY_NONE:
case NOTIFY_BRIEF:
break;
case NOTIFY_FULL:
mcell_log(" Next output scheduled for time %.15g.",
vo->t * wrld->time_unit);
break;
default:
UNHANDLED_CASE(wrld->notify->volume_output_report);
}
/* Add to the schedule */
if (schedule_add(wrld->volume_output_scheduler, vo))
mcell_allocfailed("Failed to add volume output request to scheduler.");
return 0;
}
| C |
3D | mcellteam/mcell | src/strfunc.h | .h | 774 | 23 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdarg.h>
/* Header file for character string handling functions */
char *alloc_vsprintf(char const *fmt, va_list args) PRINTF_FORMAT_V(1);
char *alloc_sprintf(char const *fmt, ...) PRINTF_FORMAT(1);
char *my_strcat(char const *s1, char const *s2);
char *strip_quotes(char const *s);
| Unknown |
3D | mcellteam/mcell | src/mcell.c | .c | 3,961 | 120 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <stdlib.h>
#include "../src4/mcell4_iface_for_mcell3.h"
#include "mcell_init.h"
#include "mcell_misc.h"
#include "mcell_run.h"
#include "init.h"
#include "dump_state.h"
#define CHECKED_CALL_EXIT(function, error_message) \
{ \
if (function) { \
mcell_print(error_message); \
exit(1); \
} \
}
int main(int argc, char **argv) {
u_int procnum = 0;
// initialize the mcell simulation
MCELL_STATE *state = mcell_create();
CHECKED_CALL_EXIT(!state, "Failed to initialize MCell simulation.");
// Parse the command line arguments and print out errors if necessary.
if (mcell_argparse(argc, argv, state)) {
if (procnum == 0) {
mcell_print("\n\n***************\nArgument error.\n***************\n\n");
mcell_print_version();
mcell_print_usage(argv[0]);
}
exit(1);
}
// Somehow these variables are correct here, but become 0 in mcell_init_state, so save and restore.
long saved_dump_level = state->dump_level;
long saved_viz_options = state->viz_options;
double saved_bond_angle = state->bond_angle; // Might as well do the same for the bond angle!!
CHECKED_CALL_EXIT(
mcell_init_state(state),
"An error occured during set up of the initial simulation state");
// Restore variables that were set to 0 by mcell_init_state.
state->dump_level = saved_dump_level;
state->viz_options = saved_viz_options;
state->bond_angle = saved_bond_angle;
if (state->notify->progress_report != NOTIFY_NONE) {
mcell_print_version();
}
CHECKED_CALL_EXIT(parse_input(state),
"An error occured during parsing of the mdl file.");
// full checkpoint read must be done after full initialization,
// however some values from it are already needed earlier
CHECKED_CALL_EXIT(
mcell_init_read_checkpoint_time_and_iteration(state),
"An error occured during initialization and reading of checkpoint.");
CHECKED_CALL_EXIT(mcell_init_simulation(state),
"An error occured during simulation creation.");
// read all data from the checkpoint now
CHECKED_CALL_EXIT(
mcell_init_read_checkpoint(state),
"An error occured during initialization and reading of checkpoint.");
CHECKED_CALL_EXIT(mcell_init_output(state),
"An error occured during setting up of output.");
if (state->dump_mcell3) {
dump_volume(state, "initial", DUMP_EVERYTHING);
}
if (state->use_mcell4 || state->mdl2datamodel4) {
if (!mcell4_convert_mcell3_volume(state)) {
exit(EXIT_FAILURE);
}
if (state->mdl2datamodel4) {
mcell4_convert_to_data_model(state->mdl2datamodel4_only_viz);
mcell4_delete_world();
return 0;
}
mcell4_run_simulation(
state->dump_mcell4 || state->dump_mcell4_with_geometry, state->dump_mcell4_with_geometry);
mcell4_delete_world();
}
else {
CHECKED_CALL_EXIT(mcell_run_simulation(state),
"Error running mcell simulation.");
if (state->notify->progress_report != NOTIFY_NONE) {
mcell_print("Done running.");
}
mcell_print_stats();
}
exit(0);
}
| C |
3D | mcellteam/mcell | src/diffuse_trimol.c | .c | 74,933 | 1,932 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <vector>
#include "diffuse.h"
#include "rng.h"
#include "util.h"
#include "logging.h"
#include "mcell_structs.h"
#include "count_util.h"
#include "grid_util.h"
#include "vol_util.h"
#include "wall_util.h"
#include "react.h"
#include "react_output.h"
/**********************************************************************
ray_trace_trimol:
In: molecule that is moving
linked list of potential collisions with molecules (we could react)
subvolume that we start in
displacement vector from current to new location
wall we have reflected off of and should not hit again
start time of the molecule random walk (local
to the molecule timestep)
Out: collision list of walls and molecules we intersected along our ray
(current subvolume only), plus the subvolume wall. Will always
return at least the subvolume wall--NULL indicates an out of
memory eriror.
Note: This is a version of the "ray_trace()" function adapted for
the case when moving molecule can engage in trimolecular collisions
**********************************************************************/
struct sp_collision *ray_trace_trimol(struct volume *world,
struct volume_molecule *m,
struct sp_collision *c,
struct subvolume *sv, struct vector3 *v,
struct wall *reflectee,
double walk_start_time) {
struct sp_collision *smash, *shead;
struct abstract_molecule *a;
struct wall_list *wlp;
struct wall_list fake_wlp;
double dx, dy, dz;
/* time, in units of of the molecule's time step, at which molecule
will cross the x,y,z partitions, respectively. */
double tx, ty, tz;
int i, j, k;
world->ray_voxel_tests++;
shead = NULL;
smash = (struct sp_collision *)CHECKED_MEM_GET(sv->local_storage->sp_coll,
"collision structure");
fake_wlp.next = sv->wall_head;
for (wlp = sv->wall_head; wlp != NULL; wlp = wlp->next) {
if (wlp->this_wall == reflectee)
continue;
i = collide_wall(&(m->pos), v, wlp->this_wall, &(smash->t), &(smash->loc),
1, world->rng, world->notify, &(world->ray_polygon_tests));
if (i == COLLIDE_REDO) {
if (shead != NULL)
mem_put_list(sv->local_storage->sp_coll, shead);
shead = NULL;
wlp = &fake_wlp;
continue;
} else if (i != COLLIDE_MISS) {
world->ray_polygon_colls++;
smash->what = COLLIDE_WALL + i;
smash->moving = m->properties;
smash->target = (void *)wlp->this_wall;
smash->t_start = walk_start_time;
smash->pos_start.x = m->pos.x;
smash->pos_start.y = m->pos.y;
smash->pos_start.z = m->pos.z;
smash->sv_start = sv;
smash->disp.x = v->x;
smash->disp.y = v->y;
smash->disp.z = v->z;
smash->next = shead;
shead = smash;
smash = (struct sp_collision *)CHECKED_MEM_GET(sv->local_storage->sp_coll,
"collision structure");
}
}
dx = dy = dz = 0.0;
i = -10;
if (v->x < 0.0) {
dx = world->x_fineparts[sv->llf.x] - m->pos.x;
i = 0;
} else if (v->x > 0.0) {
dx = world->x_fineparts[sv->urb.x] - m->pos.x;
i = 1;
}
j = -10;
if (v->y < 0.0) {
dy = world->y_fineparts[sv->llf.y] - m->pos.y;
j = 0;
} else if (v->y > 0.0) {
dy = world->y_fineparts[sv->urb.y] - m->pos.y;
j = 1;
}
k = -10;
if (v->z < 0.0) {
dz = world->z_fineparts[sv->llf.z] - m->pos.z;
k = 0;
} else if (v->z > 0.0) {
dz = world->z_fineparts[sv->urb.z] - m->pos.z;
k = 1;
}
if (i + j + k < 0) /* At least one vector is zero */
{
if (i + j + k < -15) /* Two or three vectors are zero */
{
if (i >= 0) /* X is the nonzero one */
{
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else if (j >= 0) /* Y is nonzero */
{
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else if (k >= 0) /* Z is nonzero */
{
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
} else {
smash->t = FOREVER;
smash->what =
COLLIDE_SUBVOL; /*Wrong, but we'll never hit it, so it's ok*/
}
} else /* One vector is zero; throw out other two */
{
if (i < 0) {
ty = fabs(dy * v->z);
tz = fabs(v->y * dz);
if (ty < tz) {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
} else if (j < 0) {
tx = fabs(dx * v->z);
tz = fabs(v->x * dz);
if (tx < tz) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
} else /* k<0 */
{
tx = fabs(dx * v->y);
ty = fabs(v->x * dy);
if (tx < ty) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
}
}
}
} else /* No vectors are zero--use alternate method */
{
tx = fabs(dx * v->y * v->z);
ty = fabs(v->x * dy * v->z);
tz = fabs(v->x * v->y * dz);
if (tx < ty) {
if (tx < tz) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
} else {
if (ty < tz) {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
}
}
smash->loc.x = m->pos.x + smash->t * v->x;
smash->loc.y = m->pos.y + smash->t * v->y;
smash->loc.z = m->pos.z + smash->t * v->z;
smash->moving = m->properties;
smash->target = (void *)sv;
smash->t_start = walk_start_time;
smash->pos_start.x = m->pos.x;
smash->pos_start.y = m->pos.y;
smash->pos_start.z = m->pos.z;
smash->sv_start = sv;
smash->disp.x = v->x;
smash->disp.y = v->y;
smash->disp.z = v->z;
smash->next = shead;
shead = smash;
for (; c != NULL; c = c->next) {
a = (struct abstract_molecule *)c->target;
if (a->properties == NULL)
continue;
i = collide_mol(&(m->pos), v, a, &(c->t), &(c->loc), world->rx_radius_3d);
if (i != COLLIDE_MISS) {
smash = (struct sp_collision *)CHECKED_MEM_GET(sv->local_storage->sp_coll,
"collision structure");
memcpy(smash, c, sizeof(struct sp_collision));
smash->t_start = walk_start_time;
smash->pos_start.x = m->pos.x;
smash->pos_start.y = m->pos.y;
smash->pos_start.z = m->pos.z;
smash->disp.x = v->x;
smash->disp.y = v->y;
smash->disp.z = v->z;
smash->next = shead;
shead = smash;
}
}
return shead;
}
/****************************************************************************
expand_collision_partner_list:
In: molecule that is moving
displacement to the new location
subvolume that we start in
Out: Returns linked list of molecules from neighbor subvolumes
that are located within "interaction_radius" from the the subvolume
border.
The molecules are added only when the molecule displacement
bounding box intersects with the subvolume bounding box.
Note: This is a version of the function "expand_collision_list()"
adapted for the case when molecule can engage in trimolecular
collisions.
****************************************************************************/
static struct sp_collision *expand_collision_partner_list(
struct volume_molecule *m, struct vector3 *mv, struct subvolume *sv,
double rx_radius_3d, double *x_fineparts, double *y_fineparts,
double *z_fineparts, int nx_parts, int ny_parts, int nz_parts,
int rx_hashsize, struct rxn **reaction_hash) {
struct sp_collision *shead1 = NULL;
/* lower left and upper_right corners of the molecule path
bounding box expanded by R. */
struct vector3 path_llf, path_urb;
double R; /* molecule interaction radius */
R = (rx_radius_3d);
/* find the molecule path bounding box. */
path_bounding_box(&m->pos, mv, &path_llf, &path_urb, rx_radius_3d);
/* Decide which directions we need to go */
int x_neg = 0, x_pos = 0, y_neg = 0, y_pos = 0, z_neg = 0, z_pos = 0;
if (!(sv->world_edge & X_POS_BIT) && path_urb.x + R > x_fineparts[sv->urb.x])
x_pos = 1;
if (!(sv->world_edge & X_NEG_BIT) && path_llf.x - R < x_fineparts[sv->llf.x])
x_neg = 1;
if (!(sv->world_edge & Y_POS_BIT) && path_urb.y + R > y_fineparts[sv->urb.y])
y_pos = 1;
if (!(sv->world_edge & Y_NEG_BIT) && path_llf.y - R < y_fineparts[sv->llf.y])
y_neg = 1;
if (!(sv->world_edge & Z_POS_BIT) && path_urb.z + R > z_fineparts[sv->urb.z])
z_pos = 1;
if (!(sv->world_edge & Z_NEG_BIT) && path_llf.z - R < z_fineparts[sv->llf.z])
z_neg = 1;
/* go +X */
if (x_pos) {
struct subvolume *newsv_x = sv + (nz_parts - 1) * (ny_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x, &path_llf, &path_urb, shead1, R, 0.0, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y */
if (y_pos) {
struct subvolume *newsv_y = newsv_x + (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, R, R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, R, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, R, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +X, -Y */
if (y_neg) {
struct subvolume *newsv_y = newsv_x - (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, R, -R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, R, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, R, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +X, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x + 1, &path_llf, &path_urb, shead1, R, 0.0, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x - 1, &path_llf, &path_urb, shead1, R, 0.0, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -X */
if (x_neg) {
struct subvolume *newsv_x = sv - (nz_parts - 1) * (ny_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x, &path_llf, &path_urb, shead1, -R, 0.0, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y */
if (y_pos) {
struct subvolume *newsv_y = newsv_x + (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, -R, R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, -R, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, -R, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -X, -Y */
if (y_neg) {
struct subvolume *newsv_y = newsv_x - (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, -R, -R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, -R, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, -R, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -X, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x + 1, &path_llf, &path_urb, shead1, -R, 0.0, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_x - 1, &path_llf, &path_urb, shead1, -R, 0.0, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +Y */
if (y_pos) {
struct subvolume *newsv_y = sv + (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, 0.0, R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, 0.0, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, 0.0, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -Y */
if (y_pos) {
struct subvolume *newsv_y = sv - (nz_parts - 1);
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y, &path_llf, &path_urb, shead1, 0.0, -R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -Y, +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y + 1, &path_llf, &path_urb, shead1, 0.0, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -Y, -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, newsv_y - 1, &path_llf, &path_urb, shead1, 0.0, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +Z */
if (z_pos)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, sv + 1, &path_llf, &path_urb, shead1, 0.0, 0.0, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -Z */
if (z_neg)
shead1 = expand_collision_partner_list_for_neighbor(
sv, m, mv, sv - 1, &path_llf, &path_urb, shead1, 0.0, 0.0, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
return shead1;
}
/***************************************************************************
diffuse_3D_big_list:
In: molecule that is moving
maximum time we can spend diffusing
Out: Pointer to the molecule if it still exists (may have been
reallocated), NULL otherwise.
Position and time are updated, but molecule is not rescheduled.
Note: This version takes into account both 2-way and 3-way reactions
***************************************************************************/
struct volume_molecule *diffuse_3D_big_list(struct volume *world,
struct volume_molecule *m,
double max_time) {
struct vector3 displacement; /* Molecule moves along this vector */
struct vector3 displacement2; /* Used for 3D mol-mol unbinding */
double disp_length; /* length of the displacement */
struct sp_collision *smash,
*new_smash; /* Thing we've hit that's under consideration */
struct sp_collision *shead; /* Things we might hit (can interact with) */
struct sp_collision *stail; /* tail of the collision list shead */
struct sp_collision *shead_exp; /* Things we might hit (can interact with)
from neighbor subvolumes */
struct sp_collision *shead2; /* Things that we will hit, given our motion */
struct sp_collision *main_shead2 =
NULL; /* Things that we will hit, given our motion */
struct sp_collision *new_coll = NULL;
struct tri_collision *tentative; /* Things we already hit but haven't yet
counted */
struct tri_collision *tri_smash = NULL; /* potential trimolecular collision */
struct tri_collision *main_tri_shead =
NULL; /* head of the main collision list */
struct subvolume *sv;
struct wall *w;
struct wall *reflectee; /* Bounced off this one, don't hit it again */
struct rxn *rx;
struct volume_molecule *mp, *new_mp;
struct surface_molecule *sm = NULL;
struct abstract_molecule *am1, *am2 = NULL;
double steps = 1.0;
double t_steps = 1.0;
double rate_factor = 1.0, r_rate_factor = 1.0, factor, factor1, factor2;
double t_start = 0; /* allows to account for the collision time after
reflection from a wall or moving to another subvolume */
double f;
double t_confident; /* We're sure we can count things up til this time */
struct vector3 *loc_certain; /* We've counted up to this location */
/* this flag is set to 1 only after reflection from a wall and only with
* expanded lists. */
int redo_expand_collision_list_flag = 0;
int i, j, k;
int calculate_displacement = 1;
/* array of pointers to the possible reactions */
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
int num_matching_rxns = 0;
int is_reflec_flag;
/* Flags that tell whether moving and target molecules
can participate in the MOL_MOL_MOL, MOL_MOL, MOL_MOL_GRID,
or MOL_GRID_GRID interactions. Here MOL means volume molecule
and GRID means surface molecule */
int moving_tri_molecular_flag = 0, moving_bi_molecular_flag = 0,
moving_mol_mol_grid_flag = 0, moving_mol_grid_grid_flag = 0;
/* collision flags */
int col_tri_molecular_flag = 0, col_bi_molecular_flag = 0,
col_mol_mol_grid_flag;
struct species *spec = m->properties;
struct periodic_image *periodic_box = m->periodic_box;
if (spec == NULL)
mcell_internal_error(
"Attempted to take a diffusion step for a defunct molecule.");
if (spec->space_step <= 0.0) {
m->t += max_time;
return m;
}
/* volume_reversibility and surface_reversibility routines are not valid
in case of tri-molecular reactions */
if (world->volume_reversibility || world->surface_reversibility) {
if (world->volume_reversibility &&
m->index <= DISSOCIATION_MAX) /* Only set if volume_reversibility is */
{
m->index = -1;
} else if (!world->surface_reversibility) {
if (m->flags & ACT_CLAMPED) /* Pretend we were already moving */
{
m->birthday -= 5 * spec->time_step; /* Pretend to be old */
}
}
} else {
if (m->flags & ACT_CLAMPED) /* Pretend we were already moving */
{
m->birthday -= 5 * spec->time_step; /* Pretend to be old */
} else if ((m->flags & MATURE_MOLECULE) == 0) {
/* Newly created particles that have long time steps gradually increase */
/* their timestep to the full value */
if (spec->time_step > 1.0) {
double sched_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, m->t);
f = 1 + 0.2 * ((sched_time - m->birthday)/world->time_unit);
if (f < 1)
mcell_internal_error("A %s molecule is scheduled to move before it "
"was born [birthday=%.15g, t=%.15g]",
spec->sym->name, m->birthday,
sched_time);
if (max_time > f)
max_time = f;
if (f > m->subvol->local_storage->max_timestep)
m->flags |= MATURE_MOLECULE;
}
}
}
/* Done housekeeping, now let's do something fun! */
pretend_to_call_diffuse_3D_big_list: /* Label to allow fake recursion */
sv = m->subvol;
shead = NULL;
stail = NULL;
shead_exp = NULL;
shead2 = NULL;
if (calculate_displacement) {
if (m->flags &
ACT_CLAMPED) /* Surface clamping and microscopic reversibility */
{
if (m->index <= DISSOCIATION_MAX) /* Volume microscopic reversibility */
{
pick_release_displacement(&displacement, &displacement2,
spec->space_step, world->r_step_release,
world->d_step, world->radial_subdivisions,
world->directions_mask, world->num_directions,
world->rx_radius_3d, world->rng);
t_steps = 0;
} else /* Clamping or surface microscopic reversibility */
{
pick_clamped_displacement(&displacement, m, world->r_step_surface,
world->rng, world->radial_subdivisions);
t_steps = spec->time_step;
m->previous_wall = NULL;
m->index = -1;
}
m->flags -= ACT_CLAMPED;
r_rate_factor = rate_factor = 1.0;
steps = 1.0;
} else {
/* XXX: I don't think this is safe. We probably need to pass in a list
* of nearby molecules... */
if (max_time > MULTISTEP_WORTHWHILE)
steps = safe_diffusion_step(m, NULL, world->radial_subdivisions,
world->r_step, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
else
steps = 1.0;
t_steps = steps * spec->time_step;
if (t_steps > max_time) {
t_steps = max_time;
steps = max_time / spec->time_step;
}
if (steps < EPS_C) {
steps = EPS_C;
t_steps = EPS_C * spec->time_step;
}
if (steps == 1.0) {
pick_displacement(&displacement, spec->space_step, world->rng);
r_rate_factor = rate_factor = 1.0;
} else {
rate_factor = sqrt(steps);
r_rate_factor = 1.0 / rate_factor;
pick_displacement(&displacement, rate_factor * spec->space_step,
world->rng);
}
}
if (spec->flags & SET_MAX_STEP_LENGTH) {
disp_length = vect_length(&displacement);
if (disp_length > spec->max_step_length) {
/* rescale displacement to the level of MAXIMUM_STEP_LENGTH */
displacement.x *= (spec->max_step_length / disp_length);
displacement.y *= (spec->max_step_length / disp_length);
displacement.z *= (spec->max_step_length / disp_length);
}
}
world->diffusion_number++;
world->diffusion_cumtime += steps;
}
moving_bi_molecular_flag =
((spec->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL);
moving_tri_molecular_flag =
((spec->flags & (CAN_VOLVOLVOL | CANT_INITIATE)) == CAN_VOLVOLVOL);
moving_mol_mol_grid_flag =
((spec->flags & (CAN_VOLVOLSURF | CANT_INITIATE)) == CAN_VOLVOLSURF);
moving_mol_grid_grid_flag =
((spec->flags & CAN_VOLSURFSURF) == CAN_VOLSURFSURF);
if (moving_tri_molecular_flag || moving_bi_molecular_flag ||
moving_mol_mol_grid_flag) {
/* scan molecules from this SV */
struct per_species_list *psl_next, *psl,
**psl_head = &m->subvol->species_head;
for (psl = m->subvol->species_head; psl != NULL; psl = psl_next) {
psl_next = psl->next;
if (psl->properties == NULL) {
psl_head = &psl->next;
continue;
}
/* Garbage collection of empty per-species lists */
if (psl->head == NULL) {
*psl_head = psl->next;
ht_remove(&sv->mol_by_species, psl);
mem_put(sv->local_storage->pslv, psl);
continue;
} else
psl_head = &psl->next;
col_bi_molecular_flag =
moving_bi_molecular_flag &&
((psl->properties->flags & CAN_VOLVOL) == CAN_VOLVOL);
col_tri_molecular_flag =
moving_tri_molecular_flag &&
((psl->properties->flags & CAN_VOLVOLVOL) == CAN_VOLVOLVOL);
col_mol_mol_grid_flag =
moving_mol_mol_grid_flag &&
((psl->properties->flags & CAN_VOLVOLSURF) == CAN_VOLVOLSURF);
if (col_bi_molecular_flag &&
!trigger_bimolecular_preliminary(
world->reaction_hash, world->rx_hashsize, spec->hashval,
psl->properties->hashval, spec, psl->properties))
col_bi_molecular_flag = 0;
/* What types of collisions are we concerned with for this molecule type?
*/
int what = 0;
if (col_bi_molecular_flag)
what |= COLLIDE_VOL;
if (col_tri_molecular_flag)
what |= COLLIDE_VOL_VOL;
if (col_mol_mol_grid_flag)
what |= COLLIDE_VOL_SURF;
/* If we are interested in collisions with this molecule type, add all
* local molecules to our collision list */
if (what != 0) {
for (mp = psl->head; mp != NULL; mp = mp->next_v) {
if (mp == m)
continue;
smash = (struct sp_collision *)CHECKED_MEM_GET(
sv->local_storage->sp_coll, "collision data");
smash->t = 0.0;
smash->t_start = 0.0;
smash->pos_start.x = m->pos.x;
smash->pos_start.y = m->pos.y;
smash->pos_start.z = m->pos.z;
smash->sv_start = sv;
smash->disp.x = displacement.x;
smash->disp.y = displacement.y;
smash->disp.z = displacement.z;
smash->moving = m->properties;
smash->target = (void *)mp;
smash->loc.x = 0.0;
smash->loc.y = 0.0;
smash->loc.z = 0.0;
smash->what = what;
smash->next = shead;
shead = smash;
}
}
}
if (world->use_expanded_list && shead != NULL) {
for (stail = shead; stail->next != NULL; stail = stail->next) {
}
}
if (world->use_expanded_list &&
(moving_tri_molecular_flag || moving_bi_molecular_flag ||
moving_mol_mol_grid_flag)) {
shead_exp = expand_collision_partner_list(
m, &displacement, sv, world->rx_radius_3d, world->x_fineparts,
world->y_fineparts, world->z_fineparts, world->nx_parts,
world->ny_parts, world->nz_parts, world->rx_hashsize,
world->reaction_hash);
if (stail != NULL)
stail->next = shead_exp;
else {
if (shead != NULL) {
mcell_internal_error("Collision lists corrupted. While expanding the "
"collision lists, expected shead to be NULL, "
"but it wasn't.");
}
shead = shead_exp;
}
}
}
reflectee = NULL;
#define TRI_CLEAN_AND_RETURN(x) \
do { \
if (main_tri_shead != NULL) \
mem_put_list(sv->local_storage->tri_coll, main_tri_shead); \
if (main_shead2 != NULL) \
mem_put_list(sv->local_storage->sp_coll, main_shead2); \
return (x); \
} while (0)
do {
if (world->use_expanded_list && redo_expand_collision_list_flag) {
/* split the combined collision list into two original lists
and remove old "shead_exp" */
if (shead_exp != NULL) {
if (shead == shead_exp) {
mem_put_list(sv->local_storage->sp_coll, shead_exp);
shead = NULL;
} else if (shead != NULL) {
stail->next = NULL;
mem_put_list(sv->local_storage->sp_coll, shead_exp);
}
shead_exp = NULL;
}
if (moving_tri_molecular_flag || moving_bi_molecular_flag ||
moving_mol_mol_grid_flag) {
shead_exp = expand_collision_partner_list(
m, &displacement, sv, world->rx_radius_3d, world->x_fineparts,
world->y_fineparts, world->z_fineparts, world->nx_parts,
world->ny_parts, world->nz_parts, world->rx_hashsize,
world->reaction_hash);
/* combine two collision lists */
if (shead_exp != NULL) {
if (shead != NULL)
stail->next = shead_exp;
else
shead = shead_exp;
}
}
/* reset the flag */
redo_expand_collision_list_flag = 0;
}
shead2 = ray_trace_trimol(world, m, shead, sv, &displacement, reflectee,
t_start);
if (shead2 == NULL)
mcell_internal_error("ray_trace_trimol returned NULL.");
if (shead2->next != NULL) {
shead2 = (struct sp_collision *)ae_list_sort(
(struct abstract_element *)shead2);
}
for (smash = shead2; smash != NULL; smash = smash->next) {
if (smash->t >= 1.0 || smash->t < 0.0) {
if ((smash->what &
(COLLIDE_VOL | COLLIDE_VOL_VOL | COLLIDE_VOL_SURF)) != 0)
mcell_internal_error("Detected a mol-mol[-*] collision outside of "
"the 0.0...1.0 time window. Iteration %lld, "
"time of collision %.8e",
world->current_iterations, smash->t);
smash = NULL;
break;
}
/* copy the collision objects of the type COLLIDE_VOL, COLLIDE_VOL_VOL,
COLLIDE_VOL_SURF and COLLIDE_WALL to the main collision list */
if (((smash->what & (COLLIDE_VOL | COLLIDE_VOL_VOL | COLLIDE_VOL_SURF)) !=
0)) {
new_coll = (struct sp_collision *)CHECKED_MEM_GET(
sv->local_storage->sp_coll, "collision data");
memcpy(new_coll, smash, sizeof(struct sp_collision));
new_coll->t += new_coll->t_start;
new_coll->next = main_shead2;
main_shead2 = new_coll;
} else if ((smash->what & COLLIDE_WALL) != 0) {
new_coll = (struct sp_collision *)CHECKED_MEM_GET(
sv->local_storage->sp_coll, "collision data");
memcpy(new_coll, smash, sizeof(struct sp_collision));
new_coll->t += new_coll->t_start;
new_coll->next = main_shead2;
main_shead2 = new_coll;
/* if the wall is reflective - start over new search for collision
* partners*/
w = (struct wall *)smash->target;
if ((smash->what & COLLIDE_MASK) == COLLIDE_FRONT)
k = 1;
else
k = -1;
if ((spec->flags & CAN_VOLWALL) != 0) {
/* m->index = -1; */
is_reflec_flag = 0;
num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols, spec->hashval,
(struct abstract_molecule *)m, k, w, matching_rxns, 1, 1, 0);
if (num_matching_rxns > 0) {
for (int ii = 0; ii < num_matching_rxns; ii++) {
rx = matching_rxns[ii];
if (rx->n_pathways == RX_REFLEC) {
is_reflec_flag = 1;
break;
}
}
}
/* the wall is reflective */
/* if there is no defined reaction between molecule
and this particular wall, it means that this wall is
reflective for this molecule */
if ((num_matching_rxns == 0) || is_reflec_flag) {
m->pos.x = smash->loc.x;
m->pos.y = smash->loc.y;
m->pos.z = smash->loc.z;
m->t += t_steps * smash->t;
reflectee = w;
t_start += t_steps * smash->t;
t_steps *= (1.0 - smash->t);
factor = -2.0 * (displacement.x * w->normal.x +
displacement.y * w->normal.y +
displacement.z * w->normal.z);
displacement.x =
(displacement.x + factor * w->normal.x) * (1.0 - smash->t);
displacement.y =
(displacement.y + factor * w->normal.y) * (1.0 - smash->t);
displacement.z =
(displacement.z + factor * w->normal.z) * (1.0 - smash->t);
redo_expand_collision_list_flag = 1; /* Only useful if we're using
expanded lists, but easier
to always set it */
break;
}
} else {
/* the case when (spec->flags&CAN_VOLWALL) == 0) */
/* the default property of the wall is to be REFLECTIVE.
It works if we do not specifically describe
the properties of the wall */
m->pos.x = smash->loc.x;
m->pos.y = smash->loc.y;
m->pos.z = smash->loc.z;
m->t += t_steps * smash->t;
reflectee = w;
t_start += t_steps * smash->t;
t_steps *= (1.0 - smash->t);
factor = -2.0 * (displacement.x * w->normal.x +
displacement.y * w->normal.y +
displacement.z * w->normal.z);
displacement.x =
(displacement.x + factor * w->normal.x) * (1.0 - smash->t);
displacement.y =
(displacement.y + factor * w->normal.y) * (1.0 - smash->t);
displacement.z =
(displacement.z + factor * w->normal.z) * (1.0 - smash->t);
redo_expand_collision_list_flag =
1; /* Only useful if we're using expanded lists, but easier to
always set it */
break;
}
} else if ((smash->what & COLLIDE_SUBVOL) != 0) {
struct subvolume *nsv;
m->pos.x = smash->loc.x;
m->pos.y = smash->loc.y;
m->pos.z = smash->loc.z;
displacement.x *= (1.0 - smash->t);
displacement.y *= (1.0 - smash->t);
displacement.z *= (1.0 - smash->t);
m->t += t_steps * smash->t;
t_start += t_steps * smash->t;
t_steps *= (1.0 - smash->t);
if (t_steps < EPS_C)
t_steps = EPS_C;
nsv = traverse_subvol(sv, smash->what - COLLIDE_SV_NX - COLLIDE_SUBVOL,
world->ny_parts, world->nz_parts);
if (nsv == NULL) {
mcell_internal_error(
"A %s molecule escaped the world at [%.2f, %.2f, %.2f]",
spec->sym->name, m->pos.x * world->length_unit,
m->pos.y * world->length_unit, m->pos.z * world->length_unit);
// Never get here
/*if (world->place_waypoints_flag && (m->flags & COUNT_ME))*/
/* count_region_from_scratch(world, (struct abstract_molecule *)m,*/
/* NULL, -1, &(m->pos), NULL, m->t);*/
/*spec->population--;*/
/*collect_molecule(m);*/
/*CLEAN_AND_RETURN(NULL);*/
} else {
m = migrate_volume_molecule(m, nsv);
}
if (shead2 != NULL) {
mem_put_list(sv->local_storage->sp_coll, shead2);
shead2 = NULL;
}
if (shead != NULL) {
mem_put_list(sv->local_storage->sp_coll, shead);
shead = NULL;
}
calculate_displacement = 0;
if (m->properties == NULL)
mcell_internal_error("A defunct molecule is diffusing.");
goto pretend_to_call_diffuse_3D_big_list; /* Jump to beginning of
function */
}
} /* end for (smash ...) */
if (shead2 != NULL) {
mem_put_list(sv->local_storage->sp_coll, shead2);
shead2 = NULL;
}
} while (smash != NULL);
if (shead2 != NULL) {
mem_put_list(sv->local_storage->sp_coll, shead2);
shead2 = NULL;
}
if (shead != NULL) {
mem_put_list(sv->local_storage->sp_coll, shead);
shead = NULL;
}
for (smash = main_shead2; smash != NULL; smash = smash->next) {
smash->t += smash->t_start;
}
if (main_shead2 != NULL) {
if (main_shead2->next != NULL) {
main_shead2 = (struct sp_collision *)ae_list_sort(
(struct abstract_element *)main_shead2);
}
}
/* build main_tri_shead list */
for (smash = main_shead2; smash != NULL; smash = smash->next) {
if ((smash->what & (COLLIDE_VOL | COLLIDE_VOL_VOL | COLLIDE_VOL_SURF)) !=
0) {
mp = (struct volume_molecule *)smash->target;
if (moving_bi_molecular_flag && ((smash->what & COLLIDE_VOL) != 0)) {
num_matching_rxns = trigger_bimolecular(
world->reaction_hash, world->rx_hashsize, spec->hashval,
mp->properties->hashval, (struct abstract_molecule *)m,
(struct abstract_molecule *)mp, 0, 0, matching_rxns);
if (num_matching_rxns > 0) {
for (i = 0; i < num_matching_rxns; i++) {
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "tri_collision data");
tri_smash->t = smash->t;
tri_smash->target1 = (void *)mp;
tri_smash->target2 = NULL;
tri_smash->orient = 0; /* default value */
tri_smash->what = 0;
tri_smash->what |= COLLIDE_VOL;
tri_smash->loc = smash->loc;
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = smash->loc;
tri_smash->last_walk_from = smash->pos_start;
tri_smash->intermediate = matching_rxns[i];
tri_smash->factor = exact_disk(
world, &(smash->loc), &(smash->disp), world->rx_radius_3d,
smash->sv_start, m, (struct volume_molecule *)smash->target,
world->use_expanded_list, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
tri_smash->wall = NULL;
tri_smash->factor *= r_rate_factor; /* scaling the reaction rate */
tri_smash->local_prob_factor = 0;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
}
}
}
if (moving_tri_molecular_flag && ((smash->what & COLLIDE_VOL_VOL) != 0)) {
for (new_smash = smash->next; new_smash != NULL;
new_smash = new_smash->next) {
if ((new_smash->what & COLLIDE_VOL_VOL) == 0)
continue;
new_mp = (struct volume_molecule *)new_smash->target;
num_matching_rxns = trigger_trimolecular(
world->reaction_hash, world->rx_hashsize, smash->moving->hashval,
mp->properties->hashval, new_mp->properties->hashval,
smash->moving, mp->properties, new_mp->properties, 0, 0, 0,
matching_rxns);
if (num_matching_rxns > 0) {
for (i = 0; i < num_matching_rxns; i++) {
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "collision data");
tri_smash->loc = new_smash->loc;
tri_smash->t = new_smash->t;
tri_smash->target2 = (void *)new_mp;
tri_smash->loc2 = new_smash->loc;
tri_smash->target1 = (void *)mp;
tri_smash->loc1 = smash->loc;
tri_smash->last_walk_from = new_smash->pos_start;
tri_smash->orient = 0; /* default value */
factor1 = exact_disk(world, &(smash->loc), &(smash->disp),
world->rx_radius_3d, smash->sv_start, m,
(struct volume_molecule *)smash->target,
world->use_expanded_list, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
factor2 = exact_disk(world, &(new_smash->loc), &(new_smash->disp),
world->rx_radius_3d, new_smash->sv_start, m,
(struct volume_molecule *)new_smash->target,
world->use_expanded_list, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
tri_smash->factor = factor1 * factor2;
tri_smash->factor *=
r_rate_factor; /* scaling the reaction rate */
tri_smash->local_prob_factor = 0;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_VOL_VOL;
tri_smash->intermediate = matching_rxns[i];
tri_smash->wall = NULL;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
}
} /* end if (...) */
} /* end for (new_smash...) */
} /* end if (...) */
if (moving_mol_mol_grid_flag && ((smash->what & COLLIDE_VOL_SURF) != 0)) {
for (new_smash = smash->next; new_smash != NULL;
new_smash = new_smash->next) {
if ((new_smash->what & COLLIDE_WALL) == 0)
continue;
w = (struct wall *)new_smash->target;
if ((new_smash->what & COLLIDE_MASK) == COLLIDE_FRONT)
k = 1;
else
k = -1;
if (w->grid != NULL) {
j = xyz2grid(&(new_smash->loc), w->grid);
if (w->grid->sm_list[j] && w->grid->sm_list[j]->sm) {
if (m->index != j || m->previous_wall != w) {
sm = w->grid->sm_list[j]->sm;
num_matching_rxns = trigger_trimolecular(
world->reaction_hash, world->rx_hashsize,
smash->moving->hashval, mp->properties->hashval,
sm->properties->hashval, smash->moving, mp->properties,
sm->properties, k, k, sm->orient, matching_rxns);
if (num_matching_rxns > 0) {
for (i = 0; i < num_matching_rxns; i++) {
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "tri_collision data");
tri_smash->t = new_smash->t;
tri_smash->target1 = (void *)mp;
tri_smash->target2 = (void *)sm;
tri_smash->orient = k;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_VOL_SURF;
tri_smash->loc = new_smash->loc;
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = new_smash->loc;
tri_smash->last_walk_from = new_smash->pos_start;
tri_smash->intermediate = matching_rxns[i];
factor1 =
exact_disk(world, &(smash->loc), &(smash->disp),
world->rx_radius_3d, smash->sv_start, m,
(struct volume_molecule *)smash->target,
world->use_expanded_list, world->x_fineparts,
world->y_fineparts, world->z_fineparts);
factor2 = r_rate_factor / w->grid->binding_factor;
tri_smash->factor = factor1 * factor2;
tri_smash->local_prob_factor = 0;
tri_smash->wall = w;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
}
} /* end if (num_matching_rxns > 0) */
}
/* Matched previous wall and index--don't rebind */
else {
m->index = -1; // Avoided rebinding, but next time it's OK
}
} /* end if (w->grid->mol[j] ...) */
} /* end if (w->grid != NULL ...) */
} /* end for (new_smash...) */
} /* end if (...) */
} /* end if (...) */
else if ((smash->what & COLLIDE_WALL) != 0) {
w = (struct wall *)smash->target;
int wall_was_accounted_for = 0; /* flag */
if ((smash->what & COLLIDE_MASK) == COLLIDE_FRONT)
k = 1;
else
k = -1;
/* first look for the bimolecular reactions between moving and
surface molecules */
if (w->grid != NULL && (spec->flags & CAN_VOLSURF) != 0) {
j = xyz2grid(&(smash->loc), w->grid);
if (w->grid->sm_list[j] && w->grid->sm_list[j]->sm) {
if (m->index != j || m->previous_wall != w) {
sm = w->grid->sm_list[j]->sm;
// look for bimolecular reactions between volume and surface mols
num_matching_rxns = trigger_bimolecular(
world->reaction_hash, world->rx_hashsize, spec->hashval,
sm->properties->hashval, (struct abstract_molecule *)m,
(struct abstract_molecule *)sm, k, sm->orient, matching_rxns);
if (num_matching_rxns > 0) {
for (i = 0; i < num_matching_rxns; i++) {
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "collision data");
tri_smash->t = smash->t;
tri_smash->target1 = (void *)sm;
tri_smash->target2 = NULL;
tri_smash->orient = k;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_SURF;
tri_smash->loc = smash->loc;
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = smash->loc;
tri_smash->last_walk_from = smash->pos_start;
tri_smash->intermediate = matching_rxns[i];
tri_smash->factor = r_rate_factor / w->grid->binding_factor;
tri_smash->local_prob_factor = 0;
tri_smash->wall = w;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
wall_was_accounted_for = 1;
}
} /* end if (num_matching_rxns > 0) */
} else {
m->index = -1; /* Avoided rebinding, but next time it's OK */
}
} /* end if (w->grid->mol[j] ...) */
} /* end if (w->grid != NULL ...) */
/* now look for the trimolecular reactions */
if (moving_mol_grid_grid_flag) {
if (w->grid != NULL) {
j = xyz2grid(&(smash->loc), w->grid);
if (w->grid->sm_list[j] && w->grid->sm_list[j]->sm) {
sm = w->grid->sm_list[j]->sm;
if (m->index != j || m->previous_wall != w) {
/* search for neighbors that can participate
in 3-way reaction */
struct surface_molecule *smp; /* Neighboring molecules */
struct tile_neighbor *tile_nbr_head = NULL, *curr;
int list_length = 0;
/* find neighbor molecules to react with */
find_neighbor_tiles(world, sm, sm->grid, sm->grid_index, 0, 1,
&tile_nbr_head, &list_length);
if (tile_nbr_head != NULL) {
double local_prob_factor; /*local probability factor for the
reaction */
local_prob_factor = 3.0 / list_length;
/* step through the neighbors */
for (curr = tile_nbr_head; curr != NULL; curr = curr->next) {
struct surface_molecule_list *sm_list = curr->grid->sm_list[curr->idx];
if (sm_list == NULL || sm_list->sm == NULL)
continue;
smp = curr->grid->sm_list[curr->idx]->sm;
/* check whether any of potential partners
are behind restrictive (REFLECTIVE/ABSORPTIVE) boundary */
if ((sm->properties->flags & CAN_REGION_BORDER) ||
(smp->properties->flags & CAN_REGION_BORDER)) {
if (sm->grid->surface != smp->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, sm,
smp->grid->surface, smp))
continue;
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, smp,
smp->grid->surface, sm))
continue;
}
}
num_matching_rxns = trigger_trimolecular(
world->reaction_hash, world->rx_hashsize,
smash->moving->hashval, sm->properties->hashval,
smp->properties->hashval, smash->moving, sm->properties,
smp->properties, k, sm->orient, smp->orient,
matching_rxns);
if (num_matching_rxns > 0) {
for (i = 0; i < num_matching_rxns; i++) {
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "collision data");
tri_smash->t = smash->t;
tri_smash->target1 = (void *)sm;
tri_smash->target2 = (void *)smp;
tri_smash->orient = k;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_SURF_SURF;
grid2xyz(curr->grid, curr->idx, &(tri_smash->loc));
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = tri_smash->loc;
tri_smash->last_walk_from = smash->pos_start;
tri_smash->intermediate = matching_rxns[i];
tri_smash->factor = r_rate_factor /
(w->grid->binding_factor) *
(curr->grid->binding_factor);
tri_smash->local_prob_factor = local_prob_factor;
tri_smash->wall = w;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
wall_was_accounted_for = 1;
}
}
}
if (tile_nbr_head != NULL)
delete_tile_neighbor_list(tile_nbr_head);
}
}
}
}
} /* end if (moving_mol_grid_grid_flag) */
/* now look for the mol-wall interactions */
if ((spec->flags & CAN_VOLWALL) != 0) {
/* m->index = -1; */
num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols, spec->hashval,
(struct abstract_molecule *)m, k, w, matching_rxns, 1, 1, 0);
for (i = 0; i < num_matching_rxns; i++) {
rx = matching_rxns[i];
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "tri_collision data");
tri_smash->t = smash->t;
tri_smash->target1 = (void *)w;
tri_smash->target2 = NULL;
tri_smash->orient = k;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_WALL;
tri_smash->loc = smash->loc;
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = smash->loc;
tri_smash->last_walk_from = smash->pos_start;
tri_smash->intermediate = rx;
tri_smash->factor = r_rate_factor;
tri_smash->local_prob_factor = 0;
tri_smash->wall = w;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
wall_was_accounted_for = 1;
} /* end for (i = 0; i < num_matching_rxns; ...) */
} /* end if (spec->flags & CAN_WALLMOL ...) */
if (!wall_was_accounted_for) {
/* This is a simple reflective wall
(default wall behavior).
We want to keep it in the "tri_smash"
list just in order to account for the hits with it */
tri_smash = (struct tri_collision *)CHECKED_MEM_GET(
sv->local_storage->tri_coll, "tri_collision data");
tri_smash->t = smash->t;
tri_smash->target1 = (void *)w;
tri_smash->target2 = NULL;
tri_smash->orient = k;
tri_smash->what = 0;
tri_smash->what |= COLLIDE_WALL;
tri_smash->loc = smash->loc;
tri_smash->loc1 = smash->loc;
tri_smash->loc2 = smash->loc;
tri_smash->last_walk_from = smash->pos_start;
tri_smash->intermediate = NULL;
tri_smash->factor = r_rate_factor;
tri_smash->local_prob_factor = 0;
tri_smash->wall = w;
tri_smash->next = main_tri_shead;
main_tri_shead = tri_smash;
}
} /* end if (smash->what & COLLIDE_WALL)... */
} /* end for (smash ...) */
if (main_tri_shead != NULL) {
if (main_tri_shead->next != NULL) {
main_tri_shead = (struct tri_collision *)ae_list_sort(
(struct abstract_element *)main_tri_shead);
}
}
tentative = main_tri_shead;
loc_certain = NULL;
/* now check for the reactions going through the 'main_tri_shead' list */
for (tri_smash = main_tri_shead; tri_smash != NULL;
tri_smash = tri_smash->next) {
if (world->notify->molecule_collision_report == NOTIFY_FULL) {
if (((tri_smash->what & COLLIDE_VOL) != 0) &&
(world->rxn_flags.vol_vol_reaction_flag)) {
world->vol_vol_colls++;
} else if (((tri_smash->what & COLLIDE_SURF) != 0) &&
(world->rxn_flags.vol_surf_reaction_flag)) {
world->vol_surf_colls++;
} else if (((tri_smash->what & COLLIDE_VOL_VOL) != 0) &&
(world->rxn_flags.vol_vol_vol_reaction_flag)) {
world->vol_vol_vol_colls++;
} else if (((tri_smash->what & COLLIDE_VOL_SURF) != 0) &&
(world->rxn_flags.vol_vol_surf_reaction_flag)) {
world->vol_vol_surf_colls++;
} else if (((tri_smash->what & COLLIDE_SURF_SURF) != 0) &&
(world->rxn_flags.vol_surf_surf_reaction_flag)) {
world->vol_surf_surf_colls++;
}
}
j = INT_MIN;
if (((tri_smash->what & (COLLIDE_VOL | COLLIDE_SURF | COLLIDE_VOL_VOL |
COLLIDE_VOL_SURF | COLLIDE_SURF_SURF)) != 0)) {
if (tri_smash->t < EPS_C)
continue;
if ((tri_smash->factor < 0)) /* one of the targets is blocked by a wall */
continue; /* Reaction blocked by a wall */
am1 = (struct abstract_molecule *)tri_smash->target1;
if (tri_smash->target2 != NULL) {
am2 = (struct abstract_molecule *)tri_smash->target2;
} else
am2 = NULL;
/* if one of the targets was already destroyed
- move on */
if (am1 != NULL && am1->properties == NULL)
continue;
if (am2 != NULL && am2->properties == NULL)
continue;
rx = tri_smash->intermediate;
k = tri_smash->orient;
if ((rx != NULL) && (rx->prob_t != NULL))
update_probs(world, rx, m->t);
/* XXX: Change required here to support macromol+trimol */
i = test_bimolecular(rx, tri_smash->factor, tri_smash->local_prob_factor,
NULL, NULL,
world->rng);
if (i < RX_LEAST_VALID_PATHWAY)
continue;
if ((tri_smash->what & COLLIDE_VOL) != 0) {
j = outcome_bimolecular(world, rx, i, (struct abstract_molecule *)m,
am1, 0, 0, m->t + tri_smash->t,
&(tri_smash->loc), loc_certain);
} else if ((tri_smash->what & COLLIDE_SURF) != 0) {
j = outcome_bimolecular(
world, rx, i, (struct abstract_molecule *)m, am1, k,
((struct surface_molecule *)am1)->orient, m->t + tri_smash->t,
&(tri_smash->loc), &(tri_smash->last_walk_from));
} else if ((tri_smash->what & COLLIDE_VOL_VOL) != 0) {
j = outcome_trimolecular(world, rx, i, (struct abstract_molecule *)m,
am1, am2, 0, 0, 0, m->t + tri_smash->t,
&(tri_smash->loc),
&(tri_smash->last_walk_from));
} else if ((tri_smash->what & COLLIDE_VOL_SURF) != 0) {
short orient_target = 0;
if ((am1->properties->flags & ON_GRID) != 0) {
orient_target = ((struct surface_molecule *)am1)->orient;
} else {
orient_target = ((struct surface_molecule *)am2)->orient;
}
j = outcome_trimolecular(world, rx, i, (struct abstract_molecule *)m,
am1, am2, k, k, orient_target,
m->t + tri_smash->t, &(tri_smash->loc),
&tri_smash->last_walk_from);
} else if ((tri_smash->what & COLLIDE_SURF_SURF) != 0) {
short orient1, orient2;
orient1 = ((struct surface_molecule *)am1)->orient;
orient2 = ((struct surface_molecule *)am2)->orient;
j = outcome_trimolecular(world, rx, i, (struct abstract_molecule *)m,
am1, am2, k, orient1, orient2,
m->t + tri_smash->t, &(tri_smash->loc),
&tri_smash->last_walk_from);
}
if (j != RX_DESTROY)
continue;
else {
/* Count the hits up until we were destroyed */
for (; tentative != NULL && tentative->t <= tri_smash->t;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) & COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 0,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
TRI_CLEAN_AND_RETURN(NULL);
}
}
if ((tri_smash->what & COLLIDE_WALL) != 0) {
k = tri_smash->orient;
w = (struct wall *)tri_smash->target1;
if (tri_smash->next == NULL)
t_confident = tri_smash->t;
else if (tri_smash->next->t * (1.0 - EPS_C) > tri_smash->t)
t_confident = tri_smash->t;
else
t_confident = tri_smash->t * (1.0 - EPS_C);
if ((spec->flags & CAN_VOLWALL) != 0) {
rx = tri_smash->intermediate;
if (rx != NULL) {
if ((rx->n_pathways > RX_SPECIAL) &&
(world->notify->molecule_collision_report == NOTIFY_FULL)) {
if (world->rxn_flags.vol_wall_reaction_flag)
world->vol_wall_colls++;
}
if (rx->n_pathways == RX_TRANSP) {
rx->n_occurred++;
if ((m->flags & COUNT_ME) != 0 &&
(spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
for (; tentative != NULL && tentative->t <= t_confident;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) & COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 1,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
}
continue; /* Ignore this wall and keep going */
} else if (rx->n_pathways != RX_REFLEC) {
if (rx->prob_t != NULL)
update_probs(world, rx, m->t);
i = test_intersect(rx, r_rate_factor, world->rng);
if (i > RX_NO_RX) {
/* Save m flags in case it gets collected in outcome_intersect */
int mflags = m->flags;
j = outcome_intersect(
world, rx, i, w, (struct abstract_molecule *)m, k,
m->t + t_steps * tri_smash->t, &(tri_smash->loc), NULL);
if (j == RX_FLIP) {
if ((m->flags & COUNT_ME) != 0 &&
(spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
for (; tentative != NULL && tentative->t <= t_confident;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) &
COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 1,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
}
continue; /* pass through */
} else if (j == RX_DESTROY) {
if ((mflags & COUNT_ME) != 0 &&
(spec->flags & COUNT_HITS) != 0) {
/* Count the hits up until we were destroyed */
for (; tentative != NULL && tentative->t <= tri_smash->t;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) &
COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 0,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
}
TRI_CLEAN_AND_RETURN(NULL);
}
}
} else if (rx->n_pathways == RX_REFLEC) {
/* We reflected, so we hit but did not cross things we tentatively
* hit earlier */
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_HITS) != 0) {
for (; tentative != NULL && tentative->t <= tri_smash->t;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) & COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 0,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
}
continue;
}
} else { /* (rx == NULL) - simple reflective wall */
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_HITS) != 0) {
for (; tentative != NULL && tentative->t <= tri_smash->t;
tentative = tentative->next) {
if (tentative->wall == NULL)
continue;
if (!(spec->flags & (tentative->wall->flags) & COUNT_SOME_MASK))
continue;
count_region_update(world, m, spec, m->id, periodic_box,
tentative->wall->counting_regions, tentative->orient, 0,
&(tentative->loc), tentative->t);
if (tentative == tri_smash)
break;
}
}
continue;
}
} /* end if (spec->flags & CAN_WALLMOL ...) */
} /* end if ((tri_smash->what & COLLIDE_WALL) ... */
} /* end for (tri_smash ...) */
#undef TRI_CLEAN_AND_RETURN
m->pos.x += displacement.x;
m->pos.y += displacement.y;
m->pos.z += displacement.z;
m->t += t_steps;
m->index = -1;
m->previous_wall = NULL;
if (main_tri_shead != NULL)
mem_put_list(sv->local_storage->tri_coll, main_tri_shead);
if (main_shead2 != NULL)
mem_put_list(sv->local_storage->sp_coll, main_shead2);
return m;
}
/*************************************************************************
react_2D_trimol_all_neighbors:
In: molecule that may react
maximum duration we have to react
Out: Pointer to the molecule if it still exists (may have been
destroyed), NULL otherwise.
Note: Time is not updated--assume that's already taken care of
elsewhere. Only nearest neighbors can react.
PostNote: This function is valid only for the trimolecular reaction
involving all three neighbor surface molecules whose tiles are
connected by edge or vertex
*************************************************************************/
struct surface_molecule *react_2D_trimol_all_neighbors(
struct volume *world, struct surface_molecule *sm, double t,
enum notify_level_t molecule_collision_report,
enum notify_level_t final_summary, int grid_grid_grid_reaction_flag,
long long *surf_surf_surf_colls) {
struct surface_molecule *gm_f, *gm_s; /* Neighboring molecule */
int i; /* points to the pathway of the reaction */
int j; /* points to the the reaction */
int n = 0; /* total number of possible reactions for a given molecules
with all its neighbors */
int k; /* return value from "outcome_trimolecular()" */
int l = 0, jj, kk;
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
/* linked lists of the tile neighbors (first and second level) */
struct tile_neighbor *tile_nbr_head_f = NULL, *tile_nbr_head_s = NULL,
*curr_f, *curr_s;
int list_length_f, list_length_s; /* length of the linked lists above */
int max_size = 12 * 12 * MAX_MATCHING_RXNS; /* reasonable assumption */
/* array of reaction objects with neighbor molecules */
std::vector<struct rxn *> rxn_array(max_size);
/* local probability factors for the reactions */
double local_prob_factor_f, local_prob_factor_s;
std::vector<double> local_prob_factor(max_size);
std::vector<double> cf(max_size); /* Correction factors for area for those molecules */
/* points to the first partner in the trimol reaction */
std::vector<struct surface_molecule *> first_partner(max_size);
/* points to the second partner in the trimol reaction */
std::vector<struct surface_molecule *> second_partner(max_size);
for (kk = 0; kk < max_size; kk++) {
rxn_array[kk] = NULL;
first_partner[kk] = NULL;
second_partner[kk] = NULL;
cf[kk] = 0;
local_prob_factor[kk] = 0;
}
/* find first level neighbor molecules to react with */
find_neighbor_tiles(world, sm, sm->grid, sm->grid_index, 0, 1,
&tile_nbr_head_f, &list_length_f);
if (tile_nbr_head_f == NULL)
return sm;
/* Calculate local_prob_factor for the reaction probability.
Here we convert from 3 neighbor tiles (upper probability
limit) to the real number of neighbor tiles. */
local_prob_factor_f = 1.0 / list_length_f;
/* step through the neighbors */
for (curr_f = tile_nbr_head_f; curr_f != NULL; curr_f = curr_f->next) {
struct surface_molecule_list *sm_list = curr_f->grid->sm_list[curr_f->idx];
if (sm_list == NULL || sm_list->sm == NULL)
continue;
gm_f = sm_list->sm;
/* check whether the neighbor molecule is behind
the restrictive region boundary */
if ((sm->properties->flags & CAN_REGION_BORDER) ||
(gm_f->properties->flags & CAN_REGION_BORDER)) {
if (sm->grid->surface != gm_f->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, sm, gm_f->grid->surface, gm_f))
continue;
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, gm_f, gm_f->grid->surface, sm))
continue;
}
}
/* find nearest neighbor molecules to react with (2nd level) */
find_neighbor_tiles(world, gm_f, gm_f->grid, gm_f->grid_index, 0, 1,
&tile_nbr_head_s, &list_length_s);
if (tile_nbr_head_s == NULL)
continue;
local_prob_factor_s = 1.0 / (list_length_s - 1);
for (curr_s = tile_nbr_head_s; curr_s != NULL; curr_s = curr_s->next) {
sm_list = curr_s->grid->sm_list[curr_s->idx];
if (sm_list == NULL || sm_list->sm == NULL)
continue;
gm_s = curr_s->grid->sm_list[curr_s->idx]->sm;
if (gm_s == NULL)
continue;
if (gm_s == gm_f)
continue; /* no self reaction for trimolecular reaction */
if (gm_s == sm)
continue;
/* Check whether there are restrictive region boundaries between "sm" and
* "gm_s". By now we know that there are no restrictive region boundaries
* between "sm" and "gm_f". */
if ((sm->properties->flags & CAN_REGION_BORDER) ||
(gm_f->properties->flags & CAN_REGION_BORDER) ||
(gm_s->properties->flags & CAN_REGION_BORDER)) {
if (gm_f->grid->surface != gm_s->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, gm_f->grid->surface, gm_f, gm_s->grid->surface, gm_s))
continue;
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, gm_f->grid->surface, gm_s, gm_s->grid->surface, gm_f))
continue;
}
if (sm->grid->surface != gm_s->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, sm, gm_s->grid->surface, gm_s))
continue;
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, gm_s, gm_s->grid->surface, sm))
continue;
}
}
num_matching_rxns = trigger_trimolecular(
world->reaction_hash, world->rx_hashsize, sm->properties->hashval,
gm_f->properties->hashval, gm_s->properties->hashval, sm->properties,
gm_f->properties, gm_s->properties, sm->orient, gm_f->orient,
gm_s->orient, matching_rxns);
if (num_matching_rxns > 0) {
if ((final_summary == NOTIFY_FULL) &&
(molecule_collision_report == NOTIFY_FULL)) {
if (grid_grid_grid_reaction_flag)
surf_surf_surf_colls++;
}
for (jj = 0; jj < num_matching_rxns; jj++) {
if (matching_rxns[jj] != NULL) {
rxn_array[l] = matching_rxns[jj];
cf[l] = (t / (gm_f->grid->binding_factor)) *
(t / (gm_s->grid->binding_factor));
local_prob_factor[l] = local_prob_factor_f * local_prob_factor_s;
first_partner[l] = gm_f;
second_partner[l] = gm_s;
l++;
}
}
n += num_matching_rxns;
}
}
if (tile_nbr_head_s != NULL)
delete_tile_neighbor_list(tile_nbr_head_s);
}
if (tile_nbr_head_f != NULL)
delete_tile_neighbor_list(tile_nbr_head_f);
if (n > max_size)
mcell_internal_error("The size of the reactions array in the function "
"'react_2D_trimol_all_neighbors()' is not "
"sufficient.");
if (n == 0) {
return sm; /* Nobody to react with */
} else if (n == 1) {
/* XXX: Change required here to support macromol+trimol */
i = test_bimolecular(rxn_array[0], cf[0], local_prob_factor[0], NULL, NULL, world->rng);
j = 0;
} else {
/* XXX: Change required here to support macromol+trimol */
j = test_many_reactions_all_neighbors(&rxn_array[0], &cf[0], &local_prob_factor[0], n,
&(i), world->rng);
}
if ((j == RX_NO_RX) || (i < RX_LEAST_VALID_PATHWAY)) {
return sm; /* No reaction */
}
/* run the reaction */
k = outcome_trimolecular(
world, rxn_array[j], i, (struct abstract_molecule *)sm,
(struct abstract_molecule *)first_partner[j],
(struct abstract_molecule *)second_partner[j], sm->orient,
first_partner[j]->orient, second_partner[j]->orient, sm->t, NULL, NULL);
if (k == RX_DESTROY) {
mem_put(sm->birthplace, sm);
return NULL;
}
return sm;
}
| C |
3D | mcellteam/mcell | src/diffuse.c | .c | 186,214 | 5,322 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "diffuse.h"
#include "logging.h"
#include "mcell_structs.h"
#include "count_util.h"
#include "grid_util.h"
#include "vol_util.h"
#include "wall_util.h"
#include "react.h"
#include "react_nfsim.h"
#include "nfsim_func.h"
// for debug & mcell4 development
#include "debug_config.h"
#include "debug.h"
#include "dump_state.h"
#ifdef MCELL3_SORTED_WALLS_FOR_COLLISION
#include <vector>
#endif
#define FREE_COLLISION_LISTS() \
do { \
if (shead2 != NULL) \
mem_put_list(sv->local_storage->coll, shead2); \
if (shead != NULL) \
mem_put_list(sv->local_storage->coll, shead); \
} while (0)
static const int inert_to_mol = 1;
static const int inert_to_all = 2;
/* declaration of static functions */
int move_sm_on_same_triangle(
struct volume *state,
struct surface_molecule *sm,
struct vector2 *new_loc,
struct periodic_image *previous_box,
struct wall *new_wall,
struct hit_data *hd_info);
static void redo_collision_list(struct volume* world, struct collision** shead,
struct collision** stail, struct collision** shead_exp,
struct volume_molecule* m, struct vector3* displacement, struct subvolume* sv);
static int collide_and_react_with_vol_mol(
struct volume* world, struct collision* smash, struct volume_molecule* vm,
struct collision** tentative, struct vector3* displacement,
struct vector3* loc_certain, double t_steps, double r_rate_factor);
static int collide_and_react_with_surf_mol(
struct volume* world, struct collision* smash, struct volume_molecule* vm,
struct collision** tentative, struct vector3** loc_certain, double t_steps,
int mol_grid_flag, int mol_mol_grid_flag, double r_rate_factor);
static int collide_and_react_with_walls(
struct volume* world, struct collision* smash, struct volume_molecule* vm,
struct collision** tentative, struct vector3** loc_certain, double t_steps,
int inertness, double r_rate_factor);
static int reflect_or_periodic_bc(
struct volume* world, struct collision* smash, struct vector3* displacement,
struct volume_molecule** mol, struct wall** reflectee,
struct collision** tentative, double* t_steps);
static void reflect_absorb_inside_out(
struct volume *world, struct surface_molecule *sm, struct hit_data *hd_head,
struct rxn **rx, struct rxn *matching_rxns[], struct vector2 boundary_pos,
struct wall *this_wall, int index_edge_was_hit, int *reflect_now,
int *absorb_now, int *this_wall_edge_region_border);
int reflect_absorb_outside_in(
struct volume *world,
struct surface_molecule *sm,
struct hit_data **hd_head,
struct rxn **rx,
struct rxn *matching_rxns[],
struct vector2 boundary_pos,
struct wall *target_wall,
struct wall *this_wall,
int *reflect_now,
int *absorb_now,
int this_wall_edge_region_border);
void collide_and_react_with_subvol(
struct volume* world, struct collision *smash, struct vector3* displacement,
struct volume_molecule** mol, struct collision** tentative, double* t_steps);
void compute_displacement(
struct volume* world, struct collision* shead, struct volume_molecule* vm,
struct vector3* displacement, struct vector3* displacement2,
double* rate_factor, double* r_rate_factor, double* steps, double* t_steps,
double max_time);
void determine_mol_mol_reactions(
struct volume* world, struct volume_molecule* vm, struct collision** shead,
struct collision** stail, int interness);
void set_inertness_and_maxtime(
struct volume* world, struct volume_molecule* vm, double* maxtime,
int* inertness);
void register_hits(
struct volume* world, struct volume_molecule* m,
struct collision** tentative, struct wall** reflect_w, double* reflect_t,
struct vector3* displacement, struct collision* smash, double* t_steps);
void count_tentative_collisions(
struct volume *world, struct collision **tc, struct collision *smash, struct volume_molecule* m,
struct species *spec, double t_confident, int destroy_flag,
struct periodic_image *box, u_long id);
void change_boxes_2D(
bool periodic_traditional,
struct surface_molecule *sm,
struct geom_object *periodic_box_obj,
struct vector3 *hit_xyz,
struct vector3 *teleport_xyz);
/*************************************************************************
pick_2D_displacement:
In: v: vector2 to store the new displacement
scale: scale factor to apply to the displacement
rng:
Out: No return value. vector is set to a random orientation and a
distance chosen from the probability distribution of a diffusing
2D molecule, scaled by the scaling factor.
*************************************************************************/
void pick_2D_displacement(struct vector2 *v, double scale,
struct rng_state *rng) {
static const double one_over_2_to_16th = 1.52587890625e-5;
struct vector2 a;
/*
* NOTE: The below algorithm is the polar method due to Marsaglia
* combined with a rejection method for picking uniform random
* variates in C2.
* Both methods are nicely described in Chapters V.4.3 and V.4.4
* of "Non-Uniform Random Variate Generation" by Luc Devroye
* (http://luc.devroye.org/rnbookindex.html).
*/
double f;
do {
unsigned int n = rng_uint(rng);
a.u = 2.0 * one_over_2_to_16th * (n & 0xFFFF) - 1.0;
a.v = 2.0 * one_over_2_to_16th * (n >> 16) - 1.0;
f = a.u * a.u + a.v * a.v;
} while ((f < EPS_C) || (f > 1.0));
/*
* NOTE: The scaling factor to go from a uniform to
* a normal distribution is sqrt(-2log(f)/f).
* However, since we use two normally distributed
* variates to generate a normally distributed
* 2d vector (with variance 1) we have to normalize
* and divide by an additional factor of sqrt(2)
* resulting in normalFactor.
*/
double normalFactor = sqrt(-log(f) / f);
v->u = a.u * normalFactor * scale;
v->v = a.v * normalFactor * scale;
}
/*************************************************************************
pick_clamped_displacement:
In: v: vector3 to store the new displacement
vm: molecule that just came through the surface
rng:
radial_subdivisions:
Out: No return value. vector is set to a random orientation and a
distance chosen from the probability distribution of a diffusing
3D molecule that has come through a surface from a uniform
concentration on the other side.
Note: vm->previous_wall points to the wall we're coming from, and
vm->index is the orientation we came off with
*************************************************************************/
void pick_clamped_displacement(struct vector3 *v, struct volume_molecule *vm,
double *r_step_surface, struct rng_state *rng,
u_int radial_subdivisions) {
static const double one_over_2_to_20th = 9.5367431640625e-7;
struct wall *w = vm->previous_wall;
unsigned int n = rng_uint(rng);
/* Correct distribution along normal from surface (from lookup table) */
double r_n = r_step_surface[n & (radial_subdivisions - 1)];
double p = one_over_2_to_20th * ((n >> 12) + 0.5);
double t = r_n / erfcinv(p * erfc(r_n));
struct vector2 r_uv;
pick_2D_displacement(&r_uv, sqrt(t) * vm->get_space_step(vm), rng);
r_n *= vm->index * vm->get_space_step(vm);
v->x = r_n * w->normal.x + r_uv.u * w->unit_u.x + r_uv.v * w->unit_v.x;
v->y = r_n * w->normal.y + r_uv.u * w->unit_u.y + r_uv.v * w->unit_v.y;
v->z = r_n * w->normal.z + r_uv.u * w->unit_u.z + r_uv.v * w->unit_v.z;
}
/*************************************************************************
pick_release_displacement:
In: in_disk: vector3 to store the position on interaction disk to go to
away: vector3 along which to travel away from the disk
scale:
r_step_release:
d_step:
radial_subdivisions:
directions_mask:
num_directions:
rx_radius_3d:
rng:
Out: No return value. Vectors are set to random orientation with
distances chosen from the probability distribution matching
the binding of a 3D molecule (distance and direction to
interaction disk and distance along disk).
*************************************************************************/
void pick_release_displacement(struct vector3 *in_disk, struct vector3 *away,
double scale, double *r_step_release,
double *d_step, u_int radial_subdivisions,
int directions_mask, u_int num_directions,
double rx_radius_3d, struct rng_state *rng) {
static const double one_over_2_to_16th = 1.52587890625e-5;
struct vector2 disk;
struct vector3 orth, axo;
u_int bits = rng_uint(rng);
u_int x_bit = (bits & 0x80000000);
u_int y_bit = (bits & 0x40000000);
u_int z_bit = (bits & 0x20000000);
u_int thetaphi_bits = (bits & 0x1FFFF000) >> 12;
u_int r_bits = (bits & 0x00000FFF);
double r = scale * r_step_release[r_bits & (radial_subdivisions - 1)];
u_int idx = thetaphi_bits & directions_mask;
while (idx >= num_directions) {
idx = rng_uint(rng) & directions_mask;
}
if (x_bit)
away->x = d_step[idx];
else
away->x = -d_step[idx];
if (y_bit)
away->y = d_step[idx + 1];
else
away->y = -d_step[idx + 1];
if (z_bit)
away->z = d_step[idx + 2];
else
away->z = -d_step[idx + 2];
if (d_step[idx] < d_step[idx + 1]) {
if (d_step[idx] < d_step[idx + 2]) {
orth.x = 0;
orth.y = away->z;
orth.z = -away->y;
} else {
orth.x = away->y;
orth.y = -away->x;
orth.z = 0;
}
} else if (d_step[idx + 1] < d_step[idx + 2]) {
orth.x = away->z;
orth.y = 0;
orth.z = -away->x;
} else {
orth.x = away->y;
orth.y = -away->x;
orth.z = 0;
}
normalize(&orth);
cross_prod(away, &orth, &axo);
double f;
do {
bits = rng_uint(rng);
disk.u = 2.0 * one_over_2_to_16th * (bits & 0xFFFF) - 1.0;
disk.v = 2.0 * one_over_2_to_16th * (bits >> 16) - 1.0;
f = disk.u * disk.u + disk.v * disk.v;
} while (f < 0.01 || f > 1.0);
in_disk->x = (disk.u * orth.x + disk.v * axo.x) * rx_radius_3d;
in_disk->y = (disk.u * orth.y + disk.v * axo.y) * rx_radius_3d;
in_disk->z = (disk.u * orth.z + disk.v * axo.z) * rx_radius_3d;
away->x *= r;
away->y *= r;
away->z *= r;
}
/*************************************************************************
pick_displacement:
In: vector3 to store the new displacement
scale factor to apply to the displacement
Out: No return value. vector is set to a random orientation and a
distance chosen from the probability distribution of a diffusing
3D molecule, scaled by the scaling factor.
*************************************************************************/
void pick_displacement(struct vector3 *v, double scale, struct rng_state *rng) {
v->x = scale * rng_gauss(rng) * .70710678118654752440;
v->y = scale * rng_gauss(rng) * .70710678118654752440;
v->z = scale * rng_gauss(rng) * .70710678118654752440;
}
/*************************************************************************
reflect_periodic_2D:
In: state: simulation state
index_edge_was_hit: the index of the edge that we might have hit
origin_uv: uv coordinates of where the SM started
curr_wall: the wall that the SM is currently on
disp_uv: uv coordinates of the displacement
boundary_uv: uv coordinates of the edge boundary.
origin_xyz: uv coordinates of where the SM startedi
Note: for origin_xyz, we used to compute it in this function from origin_uv,
but it can be dangerous if we've just hit a PB, since the conversions
back and forth from uv to xyz led to precision errors.
Out: the following things are updated if we hit the periodic box:
disp_uv will be reversed if we hit. should do a proper reflection
return the XYZ loc if we hit the periodic box, NULL otherwise.
*************************************************************************/
struct vector3* reflect_periodic_2D(
struct volume *state,
int index_edge_was_hit,
struct vector2 *origin_uv,
struct wall *curr_wall,
struct vector2 *disp_uv,
struct vector2 *boundary_uv,
struct vector3 *origin_xyz) {
struct vector3 target_xyz;
struct vector2 target_uv = {
origin_uv->u + disp_uv->u,
origin_uv->v + disp_uv->v
};
// Still within current wall, but we might have hit the periodic box
// set the target_xyz
if (index_edge_was_hit == -1) {
uv2xyz(&target_uv, curr_wall, &target_xyz);
}
// Hit the edge of current wall, and we might have hit the periodic box
else if (index_edge_was_hit == 0 ||
index_edge_was_hit == 1 ||
index_edge_was_hit == 2) {
uv2xyz(boundary_uv, curr_wall, &target_xyz);
}
// It's unclear what we hit
else {
return NULL;
}
struct vector3 delta_xyz = {target_xyz.x - origin_xyz->x,
target_xyz.y - origin_xyz->y,
target_xyz.z - origin_xyz->z};
struct vector3 updated_xyz = *origin_xyz;
// Go through all the subvolumes between where we are to where we want to be
for (struct subvolume *sv = find_subvolume(state, origin_xyz, NULL);
sv != NULL; sv = next_subvol(
&updated_xyz, &delta_xyz, sv, state->x_fineparts, state->y_fineparts,
state->z_fineparts, state->ny_parts,
state->nz_parts)) {
// Check all the walls in this subvolume
for (struct wall_list *wl = sv->wall_head; wl != NULL; wl = wl->next) {
// Skip it if it's not part of the periodic box
if (wl->this_wall->parent_object != state->periodic_box_obj) {
continue;
}
struct vector3 *hit_xyz = (struct vector3 *)malloc(sizeof(*hit_xyz));
double t = 0.0;
int i = collide_wall(
&updated_xyz, &delta_xyz, wl->this_wall, &t, hit_xyz, 0, state->rng,
state->notify, &(state->ray_polygon_tests));
if (i != COLLIDE_MISS &&
(hit_xyz->x - target_xyz.x) * delta_xyz.x +
(hit_xyz->y - target_xyz.y) * delta_xyz.y +
(hit_xyz->z - target_xyz.z) * delta_xyz.z < 0) {
if (!state->periodic_traditional) {
struct vector2 hit_uv;
xyz2uv(hit_xyz, curr_wall, &hit_uv);
// Take the remaining displacement and reverse it. Raytrace backwards
// from the point we hit. Not a proper reflection but okay for now.
disp_uv->u = -(target_uv.u-hit_uv.u);
disp_uv->v = -(target_uv.v-hit_uv.v);
origin_uv->u = hit_uv.u;
origin_uv->v = hit_uv.v;
}
return hit_xyz;
}
free(hit_xyz);
}
}
return NULL;
}
/*************************************************************************
change_boxes_2D:
In: sm: the surface molecule
periodic_box_obj: the actual periodic box object (*not* periodic_image)
hit_xyz: where we hit on the periodic box
Out: If we are using traditional PBCs, then we set the teleport_xyz to the
opposite side of the box, which is where the molecule will move to.
Othwerise, the periodic box on the sm is updated (i.e. sm->periodic_box)
Todo: this function should probably be renamed, as it doesn't just change the
periodic box.
*************************************************************************/
void change_boxes_2D(
bool periodic_traditional,
struct surface_molecule *sm,
struct geom_object *periodic_box_obj,
struct vector3 *hit_xyz,
struct vector3 *teleport_xyz) {
assert(periodic_box_obj->object_type == BOX_OBJ);
struct polygon_object* p = (struct polygon_object*)(periodic_box_obj->contents);
struct subdivided_box* sb = p->sb;
// Lower left and upper right corners of the periodic box
double llx = sb->x[0];
double urx = sb->x[1];
double lly = sb->y[0];
double ury = sb->y[1];
double llz = sb->z[0];
double urz = sb->z[1];
int x_inc = (sm->periodic_box->x % 2 == 0) ? 1 : -1;
int y_inc = (sm->periodic_box->y % 2 == 0) ? 1 : -1;
int z_inc = (sm->periodic_box->z % 2 == 0) ? 1 : -1;
int box_inc_x = 0;
int box_inc_y = 0;
int box_inc_z = 0;
double x_pos = 0;
double y_pos = 0;
double z_pos = 0;
if (!distinguishable(hit_xyz->x, llx, EPS_C)) {
x_pos = urx - EPS_C;
box_inc_x = -x_inc;
} else if (!distinguishable(hit_xyz->x, urx, EPS_C)) {
x_pos = llx + EPS_C;
box_inc_x = x_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && x_pos) {
teleport_xyz->x = x_pos;
}
if (!distinguishable(hit_xyz->y, lly, EPS_C)) {
y_pos = ury - EPS_C;
box_inc_y = -y_inc;
} else if (!distinguishable(hit_xyz->y, ury, EPS_C)) {
y_pos = lly + EPS_C;
box_inc_y = y_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && y_pos) {
teleport_xyz->y = y_pos;
}
if (!distinguishable(hit_xyz->z, llz, EPS_C)) {
z_pos = urz - EPS_C;
box_inc_z = -z_inc;
} else if (!distinguishable(hit_xyz->z, urz, EPS_C)) {
z_pos = llz + EPS_C;
box_inc_z = z_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && z_pos) {
teleport_xyz->z = z_pos;
}
if (!(periodic_traditional) && (box_inc_x || box_inc_y || box_inc_z)) {
sm->periodic_box->x += box_inc_x;
sm->periodic_box->y += box_inc_y;
sm->periodic_box->z += box_inc_z;
}
}
/*************************************************************************
reflect_absorb_inside_out:
In: world: simulation state
sm: molecule that is moving
hd_head: region border hit data information
rx: the type of reaction if any - absorptive/reflective
matching_rxns: an array of possible reactions
boundary_pos: the uv coordinates where we hit
this_wall: the wall that we are on
index_edge_was_hit: the index of the edge we just hit (0,1,2)
reflect_now: should the sm reflect
absorb_now: should the sm be absorbed
this_wall_edge_region_border:
Out: 1 if we are about to reflect or absorb (reflect_now, absorb_now). 0
otherwise. hd_head and this_wall_edge_region_border are updated.
*************************************************************************/
void reflect_absorb_inside_out(
struct volume *world,
struct surface_molecule *sm,
struct hit_data *hd_head,
struct rxn **rx,
struct rxn *matching_rxns[],
struct vector2 boundary_pos,
struct wall *this_wall,
int index_edge_was_hit,
int *reflect_now,
int *absorb_now,
int *this_wall_edge_region_border) {
struct edge *this_edge = this_wall->edges[index_edge_was_hit];
if (is_wall_edge_region_border(this_wall, this_edge)) {
*this_wall_edge_region_border = 1;
}
/* find neighbor wall that shares this_edge and it's index in the coordinate
* system of neighbor wall */
struct wall *nbr_wall = NULL;
/* index of the shared edge with neighbor wall in the coordinate system of
* neighbor wall */
int nbr_edge_ind = -1;
find_neighbor_wall_and_edge(this_wall, index_edge_was_hit, &nbr_wall, &nbr_edge_ind);
int nbr_wall_edge_region_border = 0;
if (nbr_wall != NULL) {
if (is_wall_edge_region_border(nbr_wall, nbr_wall->edges[nbr_edge_ind])) {
nbr_wall_edge_region_border = 1;
}
}
if (is_wall_edge_restricted_region_border(world, this_wall, this_edge, sm)) {
int num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols,
sm->properties->hashval, (struct abstract_molecule *)sm, sm->orient,
this_wall, matching_rxns, 1, 1, 1);
/* check if this wall has any reflective or absorptive region borders for
* this molecule (aka special reactions) */
for (int i = 0; i < num_matching_rxns; i++) {
*rx = matching_rxns[i];
if ((*rx)->n_pathways == RX_REFLEC) {
/* check for REFLECTIVE border */
*reflect_now = 1;
break;
} else if ((*rx)->n_pathways == RX_ABSORB_REGION_BORDER) {
/* check for ABSORPTIVE border */
*absorb_now = 1;
break;
}
}
/* count hits if we absorb or reflect */
if (reflect_now || absorb_now) {
if (this_wall->flags & sm->properties->flags & COUNT_HITS) {
// XXX: treat hd_head like we do in reflect_absorb_outside_in?
update_hit_data(&hd_head, this_wall, this_wall, sm, boundary_pos, 1, 0);
}
if (nbr_wall != NULL && nbr_wall_edge_region_border) {
if (nbr_wall->flags & sm->properties->flags & COUNT_HITS) {
// XXX: treat hd_head like we do in reflect_absorb_outside_in?
update_hit_data(&hd_head, this_wall, nbr_wall, sm, boundary_pos, 0, 0);
}
}
}
}
}
/*************************************************************************
reflect_absorb_outside_in:
In: world: simulation state
sm: molecule that is moving
hd_head: region border hit data information
rx: the type of reaction if any - absorptive/reflective
matching_rxns: an array of possible reactions
boundary_pos: the uv coordinates where we hit
target_wall: the wall we hit
this_wall: the wall that we are on
reflect_now: should the sm reflect
absorb_now: should the sm be absorbed
this_wall_edge_region_border:
Out: 1 if we are about to reflect or absorb (reflect_now, absorb_now). 0
otherwise. hd_head is updated.
*************************************************************************/
int reflect_absorb_outside_in(
struct volume *world,
struct surface_molecule *sm,
struct hit_data **hd_head,
struct rxn **rx,
struct rxn *matching_rxns[],
struct vector2 boundary_pos,
struct wall *target_wall,
struct wall *this_wall,
int *reflect_now,
int *absorb_now,
int this_wall_edge_region_border) {
/* index of the shared edge in the coordinate system of target wall */
int target_edge_ind = find_shared_edge_index_of_neighbor_wall(this_wall, target_wall);
int target_wall_edge_region_border = 0;
if (is_wall_edge_region_border(target_wall, target_wall->edges[target_edge_ind])) {
target_wall_edge_region_border = 1;
}
if (is_wall_edge_restricted_region_border(world, target_wall, target_wall->edges[target_edge_ind], sm)) {
*reflect_now = 0;
*absorb_now = 0;
int num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols,
sm->properties->hashval, (struct abstract_molecule *)sm,
sm->orient, target_wall, matching_rxns, 1, 1, 1);
for (int i = 0; i < num_matching_rxns; i++) {
*rx = matching_rxns[i];
if ((*rx)->n_pathways == RX_REFLEC) {
/* check for REFLECTIVE border */
*reflect_now = 1;
break;
} else if ((*rx)->n_pathways == RX_ABSORB_REGION_BORDER) {
/* check for ABSORPTIVE border */
*absorb_now = 1;
break;
}
}
/* count hits if we reflect or absorb */
if (*reflect_now || *absorb_now) {
if (target_wall->flags & sm->properties->flags & COUNT_HITS) {
/* this is OUTSIDE IN hit */
update_hit_data(hd_head, this_wall, target_wall, sm, boundary_pos, 0, 0);
/* this is INSIDE OUT hit for the same region border */
update_hit_data(hd_head, this_wall, this_wall, sm, boundary_pos, 1, 0);
}
}
if (*reflect_now || *absorb_now) {
return 1;
}
}
if (this_wall_edge_region_border) {
/* if we get to this point in the code the molecule crossed
the region border inside out - update hits count */
if (this_wall->flags & sm->properties->flags & COUNT_HITS) {
update_hit_data(hd_head, this_wall, this_wall, sm, boundary_pos, 1, 1);
}
}
if (target_wall_edge_region_border) {
/* if we get to this point in the code the molecule crossed
the region border outside in - update hits count */
if (target_wall->flags & sm->properties->flags & COUNT_HITS) {
update_hit_data(hd_head, this_wall, target_wall, sm, boundary_pos, 0, 1);
}
}
return 0;
}
/*************************************************************************
ray_trace_2D:
In: world: simulation state
sm: molecule that is moving
disp: displacement vector from current to new location
pos: place to store new coordinate (in coord system of new wall)
kill_me: flag that tells that molecule hits ABSORPTIVE region border
(value = 1)
rxp: reaction object (valid only in case of hitting ABSORPTIVE region
border)
hit_data_info: region border hit data information
Out: Return wall at endpoint of movement vector. Otherwise NULL if we hit
ambiguous location or if SM was absorbed.
pos: location of that endpoint in the coordinate system of the new wall.
kill_me, rxp, and hit_data_info will all be updated if we hit absorptive
boundary.
*************************************************************************/
struct wall *ray_trace_2D(
struct volume *world,
struct surface_molecule *sm,
struct vector2 *disp,
struct vector2 *pos,
int *kill_me,
struct rxn **rxp,
struct hit_data **hit_data_info) {
struct hit_data *hit_data_head = NULL;
struct wall *this_wall = sm->grid->surface;
struct vector2 orig_pos = { sm->s_pos.u,
sm->s_pos.v
};
struct vector2 this_pos = { sm->s_pos.u,
sm->s_pos.v
};
struct vector2 this_disp = { disp->u,
disp->v
};
struct periodic_image orig_box = {sm->periodic_box->x,
sm->periodic_box->y,
sm->periodic_box->z
};
struct vector3 origin_xyz;
uv2xyz(&this_pos, this_wall, &origin_xyz);
struct rxn *rx = NULL;
/* Will break out with return or break when we're done traversing walls */
while (1) {
int this_wall_edge_region_border = 0;
int absorb_now = 0;
int reflect_now = 0;
/* Index of the wall edge that the SM hits */
struct vector2 boundary_pos;
int index_edge_was_hit =
find_edge_point(this_wall, &this_pos, &this_disp, &boundary_pos);
if (world->periodic_box_obj) {
struct vector3 *hit_xyz = reflect_periodic_2D(
world,
index_edge_was_hit,
&this_pos,
this_wall,
&this_disp,
&boundary_pos,
&origin_xyz);
// We hit the periodic box! Update PBC, "reflect", and keep moving.
if (hit_xyz) {
struct vector3 teleport_xyz = {hit_xyz->x,
hit_xyz->y,
hit_xyz->z
};
change_boxes_2D(
world->periodic_traditional, sm, world->periodic_box_obj, hit_xyz,
&teleport_xyz);
if (world->periodic_traditional) {
// Some of these uv coords might not be valid (i.e. they fall off
// edge of triangle), but (i think) that's okay. we're ultimately
// just trying to get remaining uv displacement.
struct vector2 target_uv = { this_pos.u + this_disp.u,
this_pos.v + this_disp.v
};
struct vector3 target_xyz;
uv2xyz(&target_uv, this_wall, &target_xyz);
struct vector3 remaining_disp_xyz = {target_xyz.x - hit_xyz->x,
target_xyz.y - hit_xyz->y,
target_xyz.z - hit_xyz->z
};
struct vector3 new_target_xyz = {teleport_xyz.x + remaining_disp_xyz.x,
teleport_xyz.y + remaining_disp_xyz.y,
teleport_xyz.z + remaining_disp_xyz.z,
};
int grid_index = 0;
int *grid_index_p = &grid_index;
struct wall *prev_wall = this_wall;
// this_pos is also being updated here.
this_wall = find_closest_wall(
world, &teleport_xyz, 0.0, &this_pos, grid_index_p, sm->properties, NULL, NULL, NULL);
// Try again if we can't find a place
if ((this_wall == NULL) ||
(this_wall->parent_object != prev_wall->parent_object) ) {
*hit_data_info = hit_data_head;
free(hit_xyz);
return NULL;
}
struct vector2 new_target_uv;
xyz2uv(&new_target_xyz, this_wall, &new_target_uv);
this_disp.u = new_target_uv.u - this_pos.u;
this_disp.v = new_target_uv.v - this_pos.v;
}
else {
origin_xyz.x = hit_xyz->x;
origin_xyz.y = hit_xyz->y;
origin_xyz.z = hit_xyz->z;
}
free(hit_xyz);
continue;
}
}
// Ambiguous edge collision. Give up and try again from diffuse_2D.
if (index_edge_was_hit == -2) {
sm->s_pos.u = orig_pos.u;
sm->s_pos.v = orig_pos.v;
sm->periodic_box->x = orig_box.x;
sm->periodic_box->y = orig_box.y;
sm->periodic_box->z = orig_box.z;
*hit_data_info = hit_data_head;
return NULL;
}
// We didn't hit the edge. Stay inside this wall. We're done!
else if (index_edge_was_hit == -1) {
pos->u = this_pos.u + this_disp.u;
pos->v = this_pos.v + this_disp.v;
sm->s_pos.u = orig_pos.u;
sm->s_pos.v = orig_pos.v;
*hit_data_info = hit_data_head;
return this_wall;
}
// Not ambiguous (-2) or inside wall (-1), must have hit edge (0, 1, 2)
struct vector2 old_pos = {this_pos.u,
this_pos.v
};
/* We hit the edge - check for the reflection/absorption from the
edges of the wall if they are region borders
Note - here we test for potential collisions with the region
border while moving INSIDE OUT */
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
if (sm->properties->flags & CAN_REGION_BORDER) {
reflect_absorb_inside_out(
world, sm, hit_data_head, &rx, matching_rxns, boundary_pos, this_wall,
index_edge_was_hit, &reflect_now, &absorb_now,
&this_wall_edge_region_border);
if (absorb_now) {
*kill_me = 1;
*rxp = rx;
*hit_data_info = hit_data_head;
return NULL;
}
}
/* no reflection - keep going */
struct vector2 new_disp;
if (!reflect_now) {
struct wall *target_wall =
traverse_surface(this_wall, &old_pos, index_edge_was_hit, &this_pos);
if (target_wall != NULL) {
if (sm->properties->flags & CAN_REGION_BORDER) {
/* We hit the edge - check for the reflection/absorption from the
edges of the wall if they are region borders
Note - here we test for potential collisions with the region
border while moving OUTSIDE IN */
if (reflect_absorb_outside_in(
world, sm, &hit_data_head, &rx, matching_rxns, boundary_pos,
target_wall, this_wall, &reflect_now, &absorb_now,
this_wall_edge_region_border)) {
if (absorb_now) {
*kill_me = 1;
*rxp = rx;
*hit_data_info = hit_data_head;
return NULL;
}
}
}
if (!reflect_now) {
this_disp.u = old_pos.u + this_disp.u;
this_disp.v = old_pos.v + this_disp.v;
traverse_surface(this_wall, &this_disp, index_edge_was_hit, &new_disp);
this_disp.u = new_disp.u - this_pos.u;
this_disp.v = new_disp.v - this_pos.v;
this_wall = target_wall;
continue;
}
}
}
if (!reflect_now) {
*hit_data_info = hit_data_head;
}
/* If we reach this point, assume we reflect off the edge since there is no
* neighboring wall
*
* NOTE: this_pos has been corrupted by traverse_surface; use old_pos to find
* out whether the present wall edge is a region border
*/
new_disp.u = this_disp.u - (boundary_pos.u - old_pos.u);
new_disp.v = this_disp.v - (boundary_pos.v - old_pos.v);
double f;
struct vector2 reflector;
switch (index_edge_was_hit) {
case 0:
new_disp.v *= -1.0;
break;
case 1:
reflector.u = -this_wall->uv_vert2.v;
reflector.v = this_wall->uv_vert2.u - this_wall->uv_vert1_u;
f = 1.0 / sqrt(reflector.u * reflector.u + reflector.v * reflector.v);
reflector.u *= f;
reflector.v *= f;
f = 2.0 * (new_disp.u * reflector.u + new_disp.v * reflector.v);
new_disp.u -= f * reflector.u;
new_disp.v -= f * reflector.v;
break;
case 2:
reflector.u = this_wall->uv_vert2.v;
reflector.v = -this_wall->uv_vert2.u;
f = 1.0 / sqrt(reflector.u * reflector.u + reflector.v * reflector.v);
reflector.u *= f;
reflector.v *= f;
f = 2.0 * (new_disp.u * reflector.u + new_disp.v * reflector.v);
new_disp.u -= f * reflector.u;
new_disp.v -= f * reflector.v;
break;
default:
UNHANDLED_CASE(index_edge_was_hit);
}
this_pos.u = boundary_pos.u;
this_pos.v = boundary_pos.v;
this_disp.u = new_disp.u;
this_disp.v = new_disp.v;
} /* end while(1) */
sm->s_pos.u = orig_pos.u;
sm->s_pos.v = orig_pos.v;
*hit_data_info = hit_data_head;
return NULL;
}
/*************************************************************************
ray_trace:
In: world: simulation state
init_pos: position of molecule that is moving
c: linked list of potential collisions with molecules (we could react)
sv: subvolume that we start in
v: displacement vector from current to new location
reflectee: wall we have reflected off of and should not hit again
Out: collision list of walls and molecules we intersected along our ray
(current subvolume only), plus the subvolume wall. Will always
return at least the subvolume wall--NULL indicates an out of
memory error.
*************************************************************************/
struct collision *ray_trace(struct volume *world, struct vector3 *init_pos,
struct collision *c, struct subvolume *sv,
struct vector3 *v, struct wall *reflectee) {
/* time, in units of of the molecule's time step, at which molecule
will cross the x,y,z partitions, respectively. */
double tx, ty, tz;
world->ray_voxel_tests++;
struct collision *shead = NULL;
struct collision *smash = (struct collision *)CHECKED_MEM_GET(
sv->local_storage->coll, "collision structure");
#ifdef MCELL3_SORTED_WALLS_FOR_COLLISION
// sort by side value, useful only for single objects
std::vector<wall_list*> sorted_walls;
for (struct wall_list *wlp = sv->wall_head; wlp != NULL; wlp = wlp->next) {
// same as original:
// sorted_walls.push_back(wlp);
// reversed order
sorted_walls.insert(sorted_walls.begin(), wlp);
}
#endif
struct wall_list fake_wlp;
fake_wlp.next = sv->wall_head;
// Check wall collisions
#ifdef MCELL3_SORTED_WALLS_FOR_COLLISION
for (unsigned wall_array_index = 0; wall_array_index < sorted_walls.size(); wall_array_index++) {
struct wall_list *wlp = sorted_walls[wall_array_index];
#else
for (struct wall_list *wlp = sv->wall_head; wlp != NULL; wlp = wlp->next) {
#endif
if (wlp->this_wall == reflectee)
continue;
#ifdef DEBUG_COLLISIONS_WALL_EXTRA
// just faking the name for the dump condition macro
DUMP_CONDITION3(
std::cout << "Checking wall:\n";
dump_wall(wlp->this_wall, "", true);
);
#endif
int i = collide_wall(init_pos, v, wlp->this_wall, &(smash->t), &(smash->loc),
1, world->rng, world->notify, &(world->ray_polygon_tests));
#ifdef DEBUG_COLLISIONS_WALL_EXTRA
// just faking the name for the dump condition macro
DUMP_CONDITION3(
if (i == COLLIDE_REDO || i == COLLIDE_FRONT || i == COLLIDE_BACK) {
std::cout << "Collide wall: vm pos: " << *init_pos << ", displacement: " << *v << "\n";
dump_wall(wlp->this_wall, "", true);
std::cout << "collision time: " << smash->t << ", collision pos: " << smash->loc << "\n";
}
);
#endif
if (i == COLLIDE_REDO) {
if (shead != NULL)
mem_put_list(sv->local_storage->coll, shead);
shead = NULL;
wlp = &fake_wlp;
#ifdef MCELL3_SORTED_WALLS_FOR_COLLISION
wall_array_index = 0;
#endif
continue;
} else if (i != COLLIDE_MISS) {
world->ray_polygon_colls++;
smash->what = COLLIDE_WALL + i;
smash->target = (void *)wlp->this_wall;
smash->next = shead;
shead = smash;
smash = (struct collision *)CHECKED_MEM_GET(sv->local_storage->coll,
"collision structure");
}
}
double dx, dy, dz;
dx = dy = dz = 0.0;
int i = -10;
if (v->x < 0.0) {
dx = world->x_fineparts[sv->llf.x] - init_pos->x;
i = 0;
} else if (v->x > 0.0) {
dx = world->x_fineparts[sv->urb.x] - init_pos->x;
i = 1;
}
int j = -10;
if (v->y < 0.0) {
dy = world->y_fineparts[sv->llf.y] - init_pos->y;
j = 0;
} else if (v->y > 0.0) {
dy = world->y_fineparts[sv->urb.y] - init_pos->y;
j = 1;
}
int k = -10;
if (v->z < 0.0) {
dz = world->z_fineparts[sv->llf.z] - init_pos->z;
k = 0;
} else if (v->z > 0.0) {
dz = world->z_fineparts[sv->urb.z] - init_pos->z;
k = 1;
}
if (i + j + k < 0) /* At least one vector is zero */
{
if (i + j + k < -15) /* Two or three vectors are zero */
{
if (i >= 0) /* X is the nonzero one */
{
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else if (j >= 0) /* Y is nonzero */
{
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else if (k >= 0) /* Z is nonzero */
{
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
} else {
smash->t = FOREVER;
smash->what =
COLLIDE_SUBVOL; /*Wrong, but we'll never hit it, so it's ok*/
}
} else /* One vector is zero; throw out other two */
{
if (i < 0) {
ty = fabs(dy * v->z);
tz = fabs(v->y * dz);
if (ty < tz) {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
} else if (j < 0) {
tx = fabs(dx * v->z);
tz = fabs(v->x * dz);
if (tx < tz) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else
{ smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k
; }
} else /* k<0 */
{
tx = fabs(dx * v->y);
ty = fabs(v->x * dy);
if (tx < ty) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
}
}
}
} else /* No vectors are zero--use alternate method */
{
tx = fabs(dx * v->y * v->z);
ty = fabs(v->x * dy * v->z);
tz = fabs(v->x * v->y * dz);
if (tx < ty) {
if (tx < tz) {
smash->t = dx / v->x;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NX + i;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
} else {
if (ty < tz) {
smash->t = dy / v->y;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NY + j;
} else {
smash->t = dz / v->z;
smash->what = COLLIDE_SUBVOL + COLLIDE_SV_NZ + k;
}
}
}
smash->loc.x = init_pos->x + smash->t * v->x;
smash->loc.y = init_pos->y + smash->t * v->y;
smash->loc.z = init_pos->z + smash->t * v->z;
smash->target = sv;
smash->next = shead;
shead = smash;
// Check molecule collisions
for (; c != NULL; c = c->next) {
struct abstract_molecule *a = (struct abstract_molecule *)c->target;
if (a->properties == NULL)
continue;
i = collide_mol(init_pos, v, a, &(c->t), &(c->loc), world->rx_radius_3d);
if (i != COLLIDE_MISS) {
smash = (struct collision *)CHECKED_MEM_GET(sv->local_storage->coll,
"collision structure");
memcpy(smash, c, sizeof(struct collision));
smash->what = COLLIDE_VOL + i;
smash->next = shead;
shead = smash;
}
}
return shead;
}
/******************************/
/** exact_disk stuff follows **/
/******************************/
/* This is the same as the normal vector3, but the coordinates have different
* names */
struct exd_vector3 {
double m, u, v;
};
/****************************************************************
exd_zetize:
In: y coordinate (as in atan2)
x coordinate (as in atan2)
Out: Zeta value corresponding to (y,x), in the range 0 to 4.
Zeta is a substitute for the angle theta, and this function
is a substitute for atan2(y,x) which returns theta. Like
theta, zeta increases throughout the unit circle, but it
only has 8-fold symmetry instead of perfect symmetry. Zeta
values 0-1 are the first quadrant, 1-2 the second, and so
on. Zeta is a monotonically increasing function of theta,
but requires ~9x less computation time--valuable for when
you need to sort by angle but don't need the angle itself.
Note: This is a utility function in 'exact_disk()'.
****************************************************************/
/* Speed: 9ns (compare with 84ns for atan2) */
/* Added extra computations--speed not retested yet */
static double exd_zetize(double y, double x) {
if (y >= 0.0) {
if (x >= 0) {
if (x < y)
return 1.0 - 0.5 * x / y;
else
return 0.5 * y / x;
} else {
if (-x < y)
return 1.0 - 0.5 * x / y;
else
return 2.0 + 0.5 * y / x;
}
} else {
if (x <= 0) {
if (y < x)
return 3.0 - 0.5 * x / y;
else
return 2.0 + 0.5 * y / x;
} else {
if (x < -y)
return 3.0 - 0.5 * x / y;
else
return 4.0 + 0.5 * y / x;
}
}
}
/*********************************************************************
exd_coordize:
In: movement vector
place to store unit movement vector (first basis vector)
place to store second basis vector
place to store third basis vector
Out: No return value. Unit vectors m,u,v are set such that vector m
is in the direction of vector mv, and vectors u and v are
orthogonal to m. The vectors m,u,v, form a right-handed
coordinate system.
Note: This is a utility function for 'exact_disk()'.
*********************************************************************/
/* Speed: 86ns on azzuri (as marked + 6ns function call overhead) */
static void exd_coordize(struct vector3 *mv, struct vector3 *m,
struct vector3 *u, struct vector3 *v) {
double a;
/* Normalize input vector -- 27ns */
a = 1.0 / sqrt(mv->x * mv->x + mv->y * mv->y + mv->z * mv->z);
m->x = a * mv->x;
m->y = a * mv->y;
m->z = a * mv->z;
/* Find orthogonal vectors -- 21ns */
if (m->x * m->x > m->y * m->y) {
if (m->x * m->x > m->z * m->z) {
if (m->y * m->y > m->z * m->z) {
u->x = m->y;
u->y = -m->x;
u->z = 0.0;
a = 1.0 - m->z * m->z;
v->x = m->z * m->x;
v->y = m->z * m->y;
v->z = -a;
} else {
u->x = m->z;
u->y = 0.0;
u->z = -m->x;
a = 1.0 - m->y * m->y;
v->x = -m->y * m->x;
v->y = a;
v->z = -m->y * m->z;
}
} else {
u->x = -m->z;
u->y = 0.0;
u->z = m->x;
a = 1.0 - m->y * m->y;
v->x = m->y * m->x;
v->y = -a;
v->z = m->y * m->z;
}
} else {
if (m->y * m->y > m->z * m->z) {
if (m->x * m->x > m->z * m->z) {
u->x = -m->y;
u->y = m->x;
u->z = 0.0;
a = 1.0 - m->z * m->z;
v->x = -m->z * m->x;
v->y = -m->z * m->y;
v->z = a;
} else {
u->x = 0.0;
u->y = m->z;
u->z = -m->y;
a = 1.0 - m->x * m->x;
v->x = -a;
v->y = m->x * m->y;
v->z = m->x * m->z;
}
} else {
u->x = 0.0;
u->y = -m->z;
u->z = m->y;
a = 1.0 - m->x * m->x;
v->x = a;
v->y = -m->x * m->y;
v->z = -m->x * m->z;
}
}
/* Normalize orthogonal vectors -- 32ns */
a = 1 / sqrt(a);
u->x *= a;
u->y *= a;
u->z *= a;
v->x *= a;
v->y *= a;
v->z *= a;
}
/* Exact Disk Flags */
/* Flags for the exact disk computation */
enum {
EXD_HEAD,
EXD_TAIL,
EXD_CROSS,
EXD_SPAN,
EXD_OTHER
};
/* Negative numbers used as flags for reaction disks */
/* Note: TARGET_OCCLUDED is assumed for any negative number not defined here */
#define TARGET_OCCLUDED -1
/*************************************************************************
exact_disk:
In: world: simulation state
loc: location of moving molecule at time of collision
mv: movement vector for moving molecule
R: interaction radius
sv: subvolume the moving molecule is in
moving: the moving molecule
target: the target molecule at time of collision
use_expanded_list:
x_fineparts:
y_fineparts:
z_fineparts:
Out: The fraction of a full interaction disk that is actually
accessible to the moving molecule, computed exactly from the
geometry, or TARGET_OCCLUDED if the path to the target molecule is
blocked.
*************************************************************************/
double exact_disk(struct volume *world, struct vector3 *loc, struct vector3 *mv,
double R, struct subvolume *sv,
struct volume_molecule *moving,
struct volume_molecule *target, int use_expanded_list,
double *x_fineparts, double *y_fineparts,
double *z_fineparts) {
#define EXD_SPAN_CALC(v1, v2, p) \
((v1)->u - (p)->u) * ((v2)->v - (p)->v) - \
((v2)->u - (p)->u) * ((v1)->v - (p)->v)
#define EXD_TIME_CALC(v1, v2, p) \
((p)->u *(v1)->v - (p)->v *(v1)->u) / \
((p)->v *((v2)->u - (v1)->u) - (p)->u *((v2)->v - (v1)->v))
struct wall_list *wl;
struct wall *w;
struct vector3 llf, urb;
struct exd_vector3 v0muv, v1muv, v2muv;
struct exd_vertex pa, pb;
struct exd_vertex *ppa, *ppb, *pqa, *pqb, *vertex_head, *vp, *vq, *vr, *vs;
double pa_pb;
int n_verts, n_edges;
int p_flags;
double R2;
struct vector3 m, u, v;
struct exd_vector3 Lmuv;
struct exd_vertex sm;
double m2_i;
double l_n, m_n;
double a, b, c, d, r, s, t, A, zeta, last_zeta;
int i;
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
/* Initialize */
vertex_head = NULL;
n_verts = 0;
n_edges = 0;
/* Partially set up coordinate systems for first pass */
R2 = R * R;
m2_i = 1.0 / (mv->x * mv->x + mv->y * mv->y + mv->z * mv->z);
Lmuv.m = Lmuv.u = Lmuv.v = 0.0; /* Keep compiler happy */
sm.u = sm.v = sm.r2 = sm.zeta = 0.0; /* More compiler happiness */
/* Set up coordinate system and convert vertices */
exd_coordize(mv, &m, &u, &v);
Lmuv.m = loc->x * m.x + loc->y * m.y + loc->z * m.z;
Lmuv.u = loc->x * u.x + loc->y * u.y + loc->z * u.z;
Lmuv.v = loc->x * v.x + loc->y * v.y + loc->z * v.z;
if (!distinguishable_vec3(loc, &(target->pos), EPS_C)) { /* Hit target exactly! */
sm.u = sm.v = sm.r2 = sm.zeta = 0.0;
} else { /* Find location of target in moving-molecule-centric coords */
sm.u = (target->pos.x - loc->x) * u.x + (target->pos.y - loc->y) * u.y +
(target->pos.z - loc->z) * u.z;
sm.v = (target->pos.x - loc->x) * v.x + (target->pos.y - loc->y) * v.y +
(target->pos.z - loc->z) * v.z;
sm.r2 = sm.u * sm.u + sm.v * sm.v;
sm.zeta = exd_zetize(sm.v, sm.u);
}
/* Find walls that occlude the interaction disk (or block the reaction) */
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
w = wl->this_wall;
/* Ignore this wall if it is too far away! */
/* Find distance from plane of wall to molecule */
l_n = loc->x * w->normal.x + loc->y * w->normal.y + loc->z * w->normal.z;
d = w->d - l_n;
/* See if we're within interaction distance of wall */
m_n = mv->x * w->normal.x + mv->y * w->normal.y + mv->z * w->normal.z;
if (d * d >= R2 * (1 - m2_i * m_n * m_n))
continue;
/* Ignore this wall if no overlap between wall & disk bounding boxes */
/* Find wall bounding box */
urb.x = llf.x = w->vert[0]->x;
if (w->vert[1]->x < llf.x)
llf.x = w->vert[1]->x;
else
urb.x = w->vert[1]->x;
if (w->vert[2]->x < llf.x)
llf.x = w->vert[2]->x;
else if (w->vert[2]->x > urb.x)
urb.x = w->vert[2]->x;
urb.y = llf.y = w->vert[0]->y;
if (w->vert[1]->y < llf.y)
llf.y = w->vert[1]->y;
else
urb.y = w->vert[1]->y;
if (w->vert[2]->y < llf.y)
llf.y = w->vert[2]->y;
else if (w->vert[2]->y > urb.y)
urb.y = w->vert[2]->y;
urb.z = llf.z = w->vert[0]->z;
if (w->vert[1]->z < llf.z)
llf.z = w->vert[1]->z;
else
urb.z = w->vert[1]->z;
if (w->vert[2]->z < llf.z)
llf.z = w->vert[2]->z;
else if (w->vert[2]->z > urb.z)
urb.z = w->vert[2]->z;
/* Reject those without overlapping bounding boxes */
b = R2 * (1.0 - mv->x * mv->x * m2_i);
a = llf.x - loc->x;
if (a > 0 && a * a >= b)
continue;
a = loc->x - urb.x;
if (a > 0 && a * a >= b)
continue;
b = R2 * (1.0 - mv->y * mv->y * m2_i);
a = llf.y - loc->y;
if (a > 0 && a * a >= b)
continue;
a = loc->y - urb.y;
if (a > 0 && a * a >= b)
continue;
b = R2 * (1.0 - mv->z * mv->z * m2_i);
a = llf.z - loc->z;
if (a > 0 && a * a >= b)
continue;
a = loc->z - urb.z;
if (a > 0 && a * a >= b)
continue;
/* Ignore this wall if moving molecule can travel through it */
/* Reject those that the moving particle can travel through */
if ((moving->properties->flags & CAN_VOLWALL) != 0) {
num_matching_rxns = trigger_intersect(
world->reaction_hash, world->rx_hashsize, world->all_mols,
world->all_volume_mols, world->all_surface_mols,
moving->properties->hashval, (struct abstract_molecule *)moving, 0, w,
matching_rxns, 1, 1, 0);
if (num_matching_rxns != 0) {
// all reactions with the wall must be "transparent" for this wall to be ignored
bool all_transparent = true;
for (i = 0; i < num_matching_rxns; i++) {
if (matching_rxns[i]->n_pathways != RX_TRANSP) {
all_transparent = false;
break;
}
}
if (all_transparent) {
// ignore this wall
continue;
}
}
}
/* Find line of intersection between wall and disk */
#if 0
/* Set up coordinate system and convert vertices */
if (uncoordinated) {
exd_coordize(mv, &m, &u, &v);
Lmuv.m = loc->x * m.x + loc->y * m.y + loc->z * m.z;
Lmuv.u = loc->x * u.x + loc->y * u.y + loc->z * u.z;
Lmuv.v = loc->x * v.x + loc->y * v.y + loc->z * v.z;
if (!distinguishable_vec3(loc, &(target->pos),
EPS_C)) /* Hit target exactly! */
{
sm.u = sm.v = sm.r2 = sm.zeta = 0.0;
} else /* Find location of target in moving-molecule-centric coords */
{
sm.u = (target->pos.x - loc->x) * u.x + (target->pos.y - loc->y) * u.y +
(target->pos.z - loc->z) * u.z;
sm.v = (target->pos.x - loc->x) * v.x + (target->pos.y - loc->y) * v.y +
(target->pos.z - loc->z) * v.z;
sm.r2 = sm.u * sm.u + sm.v * sm.v;
sm.zeta = exd_zetize(sm.v, sm.u);
}
uncoordinated = 0;
}
#endif
v0muv.m = w->vert[0]->x * m.x + w->vert[0]->y * m.y + w->vert[0]->z * m.z -
Lmuv.m;
v0muv.u = w->vert[0]->x * u.x + w->vert[0]->y * u.y + w->vert[0]->z * u.z -
Lmuv.u;
v0muv.v = w->vert[0]->x * v.x + w->vert[0]->y * v.y + w->vert[0]->z * v.z -
Lmuv.v;
v1muv.m = w->vert[1]->x * m.x + w->vert[1]->y * m.y + w->vert[1]->z * m.z -
Lmuv.m;
v1muv.u = w->vert[1]->x * u.x + w->vert[1]->y * u.y + w->vert[1]->z * u.z -
Lmuv.u;
v1muv.v = w->vert[1]->x * v.x + w->vert[1]->y * v.y + w->vert[1]->z * v.z -
Lmuv.v;
v2muv.m = w->vert[2]->x * m.x + w->vert[2]->y * m.y + w->vert[2]->z * m.z -
Lmuv.m;
v2muv.u = w->vert[2]->x * u.x + w->vert[2]->y * u.y + w->vert[2]->z * u.z -
Lmuv.u;
v2muv.v = w->vert[2]->x * v.x + w->vert[2]->y * v.y + w->vert[2]->z * v.z -
Lmuv.v;
/* Draw lines between points and pick intersections with plane of m=0 */
if ((v0muv.m < 0) == (v1muv.m < 0)) /* v0,v1 on same side */
{
if ((v2muv.m < 0) == (v1muv.m < 0))
continue;
t = v0muv.m / (v0muv.m - v2muv.m);
pa.u = v0muv.u + (v2muv.u - v0muv.u) * t;
pa.v = v0muv.v + (v2muv.v - v0muv.v) * t;
t = v1muv.m / (v1muv.m - v2muv.m);
pb.u = v1muv.u + (v2muv.u - v1muv.u) * t;
pb.v = v1muv.v + (v2muv.v - v1muv.v) * t;
} else if ((v0muv.m < 0) == (v2muv.m < 0)) /* v0,v2 on same side */
{
t = v0muv.m / (v0muv.m - v1muv.m);
pa.u = v0muv.u + (v1muv.u - v0muv.u) * t;
pa.v = v0muv.v + (v1muv.v - v0muv.v) * t;
t = v2muv.m / (v2muv.m - v1muv.m);
pb.u = v2muv.u + (v1muv.u - v2muv.u) * t;
pb.v = v2muv.v + (v1muv.v - v2muv.v) * t;
} else /* v1, v2 on same side */
{
t = v1muv.m / (v1muv.m - v0muv.m);
pa.u = v1muv.u + (v0muv.u - v1muv.u) * t;
pa.v = v1muv.v + (v0muv.v - v1muv.v) * t;
t = v2muv.m / (v2muv.m - v0muv.m);
pb.u = v2muv.u + (v0muv.u - v2muv.u) * t;
pb.v = v2muv.v + (v0muv.v - v2muv.v) * t;
}
/* Check to make sure endpoints are sensible */
pa.r2 = pa.u * pa.u + pa.v * pa.v;
pb.r2 = pb.u * pb.u + pb.v * pb.v;
if (pa.r2 < EPS_C * R2 ||
pb.r2 < EPS_C * R2) /* Can't tell where origin is relative to wall
endpoints */
{
if (vertex_head != NULL)
mem_put_list(sv->local_storage->exdv, vertex_head);
return TARGET_OCCLUDED;
}
if (!distinguishable(pa.u * pb.v, pb.u * pa.v, EPS_C) &&
pa.u * pb.u + pa.v * pb.v <
0) /* Antiparallel, can't tell which side of wall origin is on */
{
if (vertex_head != NULL)
mem_put_list(sv->local_storage->exdv, vertex_head);
return TARGET_OCCLUDED;
}
/* Intersect line with circle; skip this wall if no intersection */
t = 0;
s = 1;
if (pa.r2 > R2 || pb.r2 > R2) {
pa_pb = pa.u * pb.u + pa.v * pb.v;
if (!distinguishable(pa.r2 + pb.r2, 2 * pa_pb,
EPS_C)) /* Wall endpoints are basically on top of
each other */
{
/* Might this tiny bit of wall block the target? If not, continue,
* otherwise return TARGET_OCCLUDED */
/* Safe if we're clearly closer; in danger if we're even remotely
* parallel, otherwise surely safe */
/* Note: use SQRT_EPS_C for cross products since previous test vs. EPS_C
* was on squared values (linear difference term cancels) */
if (sm.r2 < pa.r2 && sm.r2 < pb.r2 &&
distinguishable(sm.r2, pa.r2, EPS_C) &&
distinguishable(sm.r2, pa.r2, EPS_C))
continue;
if (!distinguishable(sm.u * pa.v, sm.v * pa.u, SQRT_EPS_C) ||
!distinguishable(sm.u * pb.v, sm.v * pb.u, SQRT_EPS_C)) {
if (vertex_head != NULL)
mem_put_list(sv->local_storage->exdv, vertex_head);
return TARGET_OCCLUDED;
}
continue;
}
a = 1.0 / (pa.r2 + pb.r2 - 2 * pa_pb);
b = (pa_pb - pa.r2) * a;
c = (R2 - pa.r2) * a;
d = b * b + c;
if (d <= 0)
continue;
d = sqrt(d);
t = -b - d;
if (t >= 1)
continue;
if (t < 0)
t = 0;
s = -b + d;
if (s <= 0)
continue;
if (s > 1)
s = 1;
}
/* Add this edge to the growing list, or return -1 if edge blocks target */
/* Construct final endpoints and prepare to store them */
ppa = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
ppb = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
if (t > 0) {
ppa->u = pa.u + t * (pb.u - pa.u);
ppa->v = pa.v + t * (pb.v - pa.v);
ppa->r2 = ppa->u * ppa->u + ppa->v * ppa->v;
ppa->zeta = exd_zetize(ppa->v, ppa->u);
} else {
ppa->u = pa.u;
ppa->v = pa.v;
ppa->r2 = pa.r2;
ppa->zeta = exd_zetize(pa.v, pa.u);
}
if (s < 1) {
ppb->u = pa.u + s * (pb.u - pa.u);
ppb->v = pa.v + s * (pb.v - pa.v);
ppb->r2 = ppb->u * ppb->u + ppb->v * ppb->v;
ppb->zeta = exd_zetize(ppb->v, ppb->u);
} else {
ppb->u = pb.u;
ppb->v = pb.v;
ppb->r2 = pb.r2;
ppb->zeta = exd_zetize(pb.v, pb.u);
}
/* It's convenient if ppa is earlier, ccw, than ppb */
a = (ppb->zeta - ppa->zeta);
if (a < 0)
a += 4.0;
if (a >= 2.0) {
vp = ppb;
ppb = ppa;
ppa = vp;
a = 4.0 - a;
}
/* Detect a blocked reaction: line is between origin and target */
b = (sm.zeta - ppa->zeta);
if (b < 0)
b += 4.0;
if (b < a) {
c = (ppa->u - sm.u) * (ppb->v - sm.v) - (ppa->v - sm.v) * (ppb->u - sm.u);
if (c < 0 || !distinguishable((ppa->u - sm.u) * (ppb->v - sm.v),
(ppa->v - sm.v) * (ppb->u - sm.u),
EPS_C)) /* Blocked! */
{
ppa->next = ppb;
ppb->next = vertex_head;
mem_put_list(sv->local_storage->exdv, ppa);
return TARGET_OCCLUDED;
}
}
ppa->role = EXD_HEAD;
ppb->role = EXD_TAIL;
ppa->e = ppb;
ppb->e = NULL;
ppb->next = vertex_head;
ppa->next = ppb;
vertex_head = ppa;
n_verts += 2;
n_edges++;
}
/* Find partition boundaries that occlude the interaction disk */
if (!use_expanded_list) /* We'll hit partitions */
{
/* First see if any overlap */
p_flags = 0;
d = loc->x - x_fineparts[sv->llf.x];
if (d < R) {
c = R2 * (mv->y * mv->y + mv->z * mv->z) * m2_i;
if (d * d < c)
p_flags |= X_NEG_BIT;
d = x_fineparts[sv->urb.x] - loc->x;
if (d * d < c)
p_flags |= X_POS_BIT;
} else {
d = x_fineparts[sv->urb.x] - loc->x;
if (d < R && d * d < R2 * (mv->y * mv->y + mv->z * mv->z) * m2_i)
p_flags |= X_POS_BIT;
}
d = loc->y - y_fineparts[sv->llf.y];
if (d < R) {
c = R2 * (mv->x * mv->x + mv->z * mv->z) * m2_i;
if (d * d < c)
p_flags |= Y_NEG_BIT;
d = y_fineparts[sv->urb.y] - loc->y;
if (d * d < c)
p_flags |= Y_POS_BIT;
} else {
d = y_fineparts[sv->urb.y] - loc->y;
if (d < R && d * d < R2 * (mv->x * mv->x + mv->z * mv->z) * m2_i)
p_flags |= Y_POS_BIT;
}
d = loc->z - z_fineparts[sv->llf.z];
if (d < R) {
c = R2 * (mv->y * mv->y + mv->x * mv->x) * m2_i;
if (d * d < c)
p_flags |= Z_NEG_BIT;
d = z_fineparts[sv->urb.z] - loc->z;
if (d * d < c)
p_flags |= Z_POS_BIT;
} else {
d = z_fineparts[sv->urb.z] - loc->z;
if (d < R && d * d < R2 * (mv->y * mv->y + mv->x * mv->x) * m2_i)
p_flags |= Z_POS_BIT;
}
/* Now find the lines created by any that do overlap */
if (p_flags) {
for (i = 1; i <= p_flags; i *= 2) {
if ((i & p_flags) != 0) {
/* Load up the relevant variables */
switch (i) {
case X_NEG_BIT:
d = x_fineparts[sv->llf.x] - loc->x;
a = u.x;
b = v.x;
break;
case X_POS_BIT:
d = x_fineparts[sv->urb.x] - loc->x;
a = u.x;
b = v.x;
break;
case Y_NEG_BIT:
d = y_fineparts[sv->llf.y] - loc->y;
a = u.y;
b = v.y;
break;
case Y_POS_BIT:
d = y_fineparts[sv->urb.y] - loc->y;
a = u.y;
b = v.y;
break;
case Z_NEG_BIT:
d = z_fineparts[sv->llf.z] - loc->z;
a = u.z;
b = v.z;
break;
case Z_POS_BIT:
d = z_fineparts[sv->urb.z] - loc->z;
a = u.z;
b = v.z;
break;
default:
continue;
}
if (!distinguishable(a, 0, EPS_C)) {
s = d / b;
if (s * s > R2) {
mcell_internal_error(
"Unexpected results in exact disk: s=%.2f s^2=%.2f R2=%.2f\n",
s, s * s, R2);
/*continue;*/
}
t = sqrt(R2 - s * s);
pa.u = t;
pa.v = s;
pb.u = -t;
pb.v = s;
} else if (!distinguishable(b, 0, EPS_C)) {
t = d / a;
if (t * t > R2) {
mcell_internal_error(
"Unexpected results in exact disk: t=%.2f t^2=%.2f R2=%.2f\n",
t, t * t, R2);
/*continue;*/
}
s = sqrt(R2 - t * t);
pa.u = t;
pa.v = s;
pb.u = t;
pb.v = -s;
} else {
c = a * a + b * b;
s = d * b;
if (d * d > R2 * c) {
mcell_internal_error("Unexpected results in exact disk: d=%.2f "
"d^2=%.2f R2=%.2f c=%.2f R2*c=%.2f\n",
d, d * d, R2, c, R2 * c);
/*continue;*/
}
t = sqrt(R2 * c - d * d);
c = 1.0 / c;
r = 1.0 / a;
pa.v = c * (s + t * a);
pa.u = (d - b * pa.v) * r;
pb.v = c * (s - t * a);
pb.u = (d - b * pb.v) * r;
}
/* Create memory for the pair of vertices */
ppa = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
ppb = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
a = exd_zetize(pa.v, pa.u);
b = exd_zetize(pb.v, pb.u);
c = b - a;
if (c < 0)
c += 4;
if (c < 2) {
ppa->u = pa.u;
ppa->v = pa.v;
ppa->r2 = pa.u * pa.u + pa.v * pa.v;
ppa->zeta = a;
ppb->u = pb.u;
ppb->v = pb.v;
ppb->r2 = pb.u * pb.u + pb.v * pb.v;
ppb->zeta = b;
} else {
ppb->u = pa.u;
ppb->v = pa.v;
ppb->r2 = pa.u * pa.u + pa.v * pa.v;
ppb->zeta = a;
ppa->u = pb.u;
ppa->v = pb.v;
ppa->r2 = pb.u * pb.u + pb.v * pb.v;
ppa->zeta = b;
}
ppa->role = EXD_HEAD;
ppb->role = EXD_TAIL;
ppa->e = ppb;
ppb->e = NULL;
ppb->next = vertex_head;
ppa->next = ppb;
vertex_head = ppa;
n_verts += 2;
n_edges++;
}
}
}
}
/* Now that we have everything, see if we can perform simple calculations */
/* Did we even find anything? If not, return full area */
if (n_edges == 0) {
return 1.0;
}
/* If there is only one edge, just calculate it */
else if (n_edges == 1) {
ppa = vertex_head;
ppb = ppa->e;
a = ppa->u * ppb->u + ppa->v * ppb->v;
b = ppa->u * ppb->v - ppa->v * ppb->u;
if (a <= 0) /* Angle > pi/2 */
{
s = atan(-a / b) + 0.5 * MY_PI;
} else {
s = atan(b / a);
}
A = (0.5 * b + R2 * (MY_PI - 0.5 * s)) / (MY_PI * R2);
mem_put_list(sv->local_storage->exdv, vertex_head);
return A;
}
/* If there are multiple edges, calculating area is more complex. */
/* Insertion sort the multiple edges */
vp = vertex_head->next;
ppa = ppb = vertex_head;
ppa->next = NULL;
ppa->span = NULL;
while (vp != NULL) {
/* Snip off one item from old list to add */
vp->span = NULL;
vq = vp->next;
/* Add it to list with ppa as head and ppb as tail */
if (vp->zeta < ppa->zeta) {
vp->next = ppa;
ppa = vp;
} else {
for (pqa = ppa; pqa->next != NULL; pqa = pqa->next) {
if (vp->zeta < pqa->next->zeta)
break;
}
vp->next = pqa->next;
pqa->next = vp;
if (vp->next == NULL)
ppb = vp;
}
/* Repeat for remainder of old list */
vp = vq;
}
/* Close circular list */
vertex_head = ppa;
ppb->next = ppa;
/* Walk around the circle, inserting points where lines cross */
ppb = NULL;
for (ppa = vertex_head; ppa != vertex_head || ppb == NULL; ppa = ppa->next) {
if (ppa->role != EXD_HEAD)
continue;
ppb = ppa->e;
for (pqa = ppa->next; pqa != ppb; pqa = pqa->next) {
if (pqa->role != EXD_HEAD)
continue;
pqb = pqa->e;
/* Create displacement vectors */
pa.u = ppb->u - ppa->u;
pa.v = ppb->v - ppa->v;
pb.u = pqb->u - pqa->u;
pb.v = pqb->v - pqa->v;
r = pb.u * pa.v - pa.u * pb.v;
/* Check if lines are parallel--combine if so */
if (r * r <
EPS_C * (pa.u * pa.u + pa.v * pa.v) * (pb.u * pb.u + pb.v * pb.v)) {
pqa->e = NULL;
pqa->role = EXD_OTHER;
a = pqb->zeta - ppb->zeta;
if (a < 0)
a += 4.0;
if (a > 2) /* Other line is completely contained inside us */
{
pqb->role = EXD_OTHER;
} else /* We have a new endpoint, so we need to check crosses again */
{
ppa->e = pqb;
ppb->role = EXD_OTHER;
ppb = pqb;
pqa = ppa;
}
continue;
}
/* Check if these lines cross and find times at which they do */
s = (ppa->u - pqa->u) * pa.v - (ppa->v - pqa->v) * pa.u;
if (s * r <= EPS_C * R2 * R2)
continue;
t = s / r;
if (t >= 1 - EPS_C)
continue;
if (pa.u * pa.u > pa.v * pa.v) {
s = (pqa->u - ppa->u + t * pb.u) * pa.u;
if (s <= EPS_C * R2 || s >= pa.u * pa.u * (1.0 - EPS_C))
continue;
} else {
s = (pqa->v - ppa->v + t * pb.v) * pa.v;
if (s <= EPS_C * R2 || s >= pa.v * pa.v * (1.0 - EPS_C))
continue;
}
/* Create intersection point */
vq = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
vq->u = pqa->u + t * pb.u;
vq->v = pqa->v + t * pb.v;
vq->r2 = vq->u * vq->u + vq->v * vq->v;
vq->zeta = exd_zetize(vq->v, vq->u);
vq->e = ppb;
vq->span = NULL;
vq->role = EXD_CROSS;
/* Insert new point into the list */
for (vp = ppa; vp != ppb; vp = vp->next) {
a = vq->zeta - vp->next->zeta;
if (a > 2.0)
a -= 4.0;
else if (a < -2.0)
a += 4.0;
if (a < 0)
break;
}
vq->next = vp->next;
vp->next = vq;
if (vq->zeta < vertex_head->zeta)
vertex_head = vq;
}
}
/* Collapse nearby points in zeta and R */
for (vp = vertex_head, vq = NULL; vq != vertex_head; vp = vq) {
for (vq = vp->next; vq != vertex_head; vq = vq->next) {
if (vq->zeta - vp->zeta < EPS_C) {
vq->zeta = vp->zeta;
if (-EPS_C < vq->r2 - vp->r2 && EPS_C > vq->r2 - vp->r2) {
vq->r2 = vp->r2;
/* Mark crosses that occur multiple times--only need one */
// if (vq->role==EXD_CROSS && vp->role != EXD_OTHER) vq->role
// = EXD_OTHER;
// else if (vp->role==EXD_CROSS && vq->role != EXD_OTHER)
// vp->role = EXD_OTHER;
}
} else
break;
}
}
/* Register all spanning line segments */
vq = NULL;
for (vp = vertex_head; vp != vertex_head || vq == NULL; vp = vp->next) {
if (vp->role != EXD_HEAD)
continue;
for (vq = vp->next; vq != vp->e; vq = vq->next) {
if (!distinguishable(vq->zeta, vp->zeta, EPS_C))
continue;
if (!distinguishable(vq->zeta, vp->e->zeta, EPS_C))
break;
if (vq->role == EXD_OTHER)
continue;
vr = (struct exd_vertex *)CHECKED_MEM_GET(sv->local_storage->exdv,
"exact disk vertex");
vr->next = vq->span;
vq->span = vr;
vr->e = vp;
vr->zeta = vq->zeta;
vr->role = EXD_SPAN;
}
}
/* Now we finally walk through and calculate the area */
A = 0.0;
zeta = 0.0;
last_zeta = -1;
vs = NULL;
for (vp = vertex_head; zeta < 4.0 - EPS_C; vp = vp->next) {
if (vp->role == EXD_OTHER)
continue;
if (!distinguishable(vp->zeta, last_zeta, EPS_C))
continue;
last_zeta = vp->zeta;
/* Store data for the next tentatively approved point */
if (vs == &pa)
vr = &pb;
else
vr = &pa;
vr->u = vp->u;
vr->v = vp->v;
vr->zeta = vp->zeta;
if (vp->role == EXD_TAIL) {
vr->r2 = R2 * (1.0 + EPS_C);
vr->e = NULL;
} else {
vr->r2 = vp->r2;
vr->e = vp->e;
}
/* Check head points at same place to see if they're closer */
for (vq = vp->next; (!distinguishable(vq->zeta, last_zeta, EPS_C));
vq = vq->next) {
if (vq->role == EXD_HEAD) {
if (vq->r2 < vp->r2 || vr->e == NULL) {
vr->u = vq->u;
vr->v = vq->v;
vr->r2 = vq->r2;
vr->e = vq->e;
} else if (!distinguishable(vq->r2, vr->r2, EPS_C)) {
b = EXD_SPAN_CALC(vr, vr->e, vq->e);
if (b > 0)
vr->e = vq->e;
}
}
}
/* Check each span to see if anything is closer than our approval point */
for (vq = vp->span; vq != NULL; vq = vq->next) {
ppa = vq->e;
ppb = ppa->e;
b = EXD_SPAN_CALC(ppa, ppb, vr);
c = b * b;
if (c < R2 * R2 * EPS_C) /* Span crosses the point */
{
if (vr->e == NULL) {
vr->r2 = vr->u * vr->u + vr->v * vr->v;
vr->e = ppb;
} else {
b = EXD_SPAN_CALC(vr, vr->e, ppb);
if (b > 0)
vr->e = ppb;
}
} else if (b < 0 ||
vr->e == NULL) /* Span is inside the point or spans tail */
{
t = EXD_TIME_CALC(ppa, ppb, vp);
vr->u = ppa->u + t * (ppb->u - ppa->u);
vr->v = ppa->v + t * (ppb->v - ppa->v);
vr->r2 = vr->u * vr->u + vr->v * vr->v;
vr->e = ppb;
}
}
/* Should have an approved point in vr */
if (vs == NULL) /* No angle traversed yet */
{
vs = vr;
} else {
c = vr->zeta - vs->zeta;
if (c < 0)
c += 4.0;
if (/*vr->e != vs->e || c+zeta >= 4.0-EPS_C*/ c > EPS_C) {
zeta += c;
if (vs->e == NULL ||
(vs->e->zeta - vs->zeta) * (vs->e->zeta - vs->zeta) <
EPS_C * EPS_C) {
if (c >= 2.0) /* More than pi */
{
vs->u = -vs->u;
vs->v = -vs->v;
A += 0.5 * MY_PI * R2;
}
a = vs->u * vr->u + vs->v * vr->v;
b = vs->u * vr->v - vs->v * vr->u;
if (a <= 0) /* More than pi/2 */
{
s = atan(-a / b) + 0.5 * MY_PI;
} else {
s = atan(b / a);
}
A += 0.5 * s * R2;
} else {
if (!distinguishable(vs->e->zeta, vr->zeta, EPS_C)) {
A += 0.5 * (vs->u * vs->e->v - vs->v * vs->e->u);
} else {
t = EXD_TIME_CALC(vs, vs->e, vr);
b = vs->u + (vs->e->u - vs->u) * t;
c = vs->v + (vs->e->v - vs->v) * t;
A += 0.5 * (vs->u * c - vs->v * b);
}
}
vs = vr;
} else {
if (vr->e != NULL)
vs = vr;
}
}
}
/* Finally, let's clean up the mess we made! */
/* Deallocate lists */
/* Note: vertex_head points to a circular list at this point. */
/* We delete starting with vertex_head->next, and nil */
/* that pointer to break the cycle in the list. */
ppa = vertex_head->next;
vertex_head->next = NULL;
/* Flatten out lists so that "span" elements are included... */
for (ppb = ppa; ppb != NULL; ppb = ppb->next) {
if (ppb->span != NULL) {
struct exd_vertex *next = ppb->next;
ppb->next = ppb->span;
ppb->span = NULL;
while (ppb->next != NULL)
ppb = ppb->next;
ppb->next = next;
}
}
mem_put_list(sv->local_storage->exdv, ppa);
/* Return fractional area */
return A / (MY_PI * R2);
#undef EXD_TIME_CALC
#undef EXD_SPAN_CALC
}
/**************************/
/** done with exact_disk **/
/**************************/
/****************************************************************************
safe_diffusion_step:
In: vm: molecule that is moving
shead: linked list of potential collisions with molecules from the
radial_subdivisions:
r_step:
x_fineparts:
y_fineparts:
z_fineparts:
Out: The estimated number of diffusion steps this molecule can take before
something interesting might happen to it, or 1.0 if something might
happen within one timestep.
Note: Each molecule uses its own timestep. Only molecules that the moving
molecule can react with directly are counted (secondary reaction
products are ignored, so might be skipped). "Might happen" is to
the 99% confidence level (i.e. the distance you'd have to go before
1% of the molecules will have gotten far enough to have a chance of
reacting, although those 1% will probably not go in the right
direction). This doesn't take into account the diffusion of other
target molecules, so it may introduce errors for clouds of molecules
diffusing into each other from a distance.
*FIXME*: Add a flag to make this be very conservative or to turn
this off entirely, aside from the TIME_STEP_MAX= directive.
****************************************************************************/
double safe_diffusion_step(struct volume_molecule *vm, struct collision *shead,
u_int radial_subdivisions, double *r_step,
double *x_fineparts, double *y_fineparts,
double *z_fineparts) {
double d2;
double d2_nearmax;
double d2min = GIGANTIC;
struct subvolume *sv = vm->subvol;
struct wall *w;
struct wall_list *wl;
struct collision *smash;
double steps;
struct volume_molecule *mp;
d2_nearmax = vm->get_space_step(vm) *
r_step[(int)(radial_subdivisions * MULTISTEP_PERCENTILE)];
d2_nearmax *= d2_nearmax;
if ((vm->properties->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL) {
for (smash = shead; smash != NULL; smash = smash->next) {
mp = (struct volume_molecule *)smash->target;
d2 = (vm->pos.x - mp->pos.x) * (vm->pos.x - mp->pos.x) +
(vm->pos.y - mp->pos.y) * (vm->pos.y - mp->pos.y) +
(vm->pos.z - mp->pos.z) * (vm->pos.z - mp->pos.z);
if (d2 < d2min)
d2min = d2;
}
}
for (wl = sv->wall_head; wl != NULL; wl = wl->next) {
w = wl->this_wall;
d2 = (w->normal.x * vm->pos.x + w->normal.y * vm->pos.y +
w->normal.z * vm->pos.z) -
w->d;
d2 *= d2;
if (d2 < d2min)
d2min = d2;
}
d2 = (vm->pos.x - x_fineparts[sv->llf.x]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
d2 = (vm->pos.x - x_fineparts[sv->urb.x]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
d2 = (vm->pos.y - y_fineparts[sv->llf.y]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
d2 = (vm->pos.y - y_fineparts[sv->urb.y]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
d2 = (vm->pos.z - z_fineparts[sv->llf.z]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
d2 = (vm->pos.z - z_fineparts[sv->urb.z]);
d2 *= d2;
if (d2 < d2min)
d2min = d2;
#ifdef MCELL3_4_SAFE_DIFF_STEP_RETURNS_CONSTANT
return 1;
#else
if (d2min < d2_nearmax)
steps = 1.0;
else {
double steps_sq = d2min / d2_nearmax;
if (steps_sq < MULTISTEP_WORTHWHILE * MULTISTEP_WORTHWHILE)
steps = 1.0;
else
steps = sqrt(steps_sq);
}
return steps;
#endif
}
/****************************************************************************
expand_collision_list_for_neighbor:
This is a helper function to reduce duplicated code in expand_collision_list.
This code will be called once for each adjacent subvolume. The clipping
indicators below (trim_[xyz]) are interpreted as follows:
trim < 0: We went in the negative direction for this axis. Search within
-trim of the maximal partition boundary in the adjacent subvol
trim > 0: We went in the positive direction for this axis. Search within
trim of the minimal partition boundary in the adjacent subvol
trim = 0: The subvolume is adjacent along this axis. Search the entire
width of this axis of the subvolume.
In: sv: the "current" subvolume
vm: the current molecule
new_sv: adjacent subvolume to search
path_llf: path bounding box lower left front
path_urb: path bounding box upper right back
shead1: current list head
trim_x: X clipping indicator
trim_y: Y clipping indicator
trim_z: Z clipping indicator
x_fineparts:
y_fineparts:
z_fineparts:
rx_hashsize:
reaction_hash:
Out: Returns linked list of molecules from neighbor subvolumes
that are located within "interaction_radius" from the the subvolume
border.
The molecules are added only when the molecule displacement
bounding box intersects with the subvolume bounding box.
****************************************************************************/
static struct collision *expand_collision_list_for_neighbor(struct volume *world,
struct subvolume *sv, struct volume_molecule *vm, struct subvolume *new_sv,
struct vector3 *path_llf, struct vector3 *path_urb,
struct collision *shead1, double trim_x, double trim_y, double trim_z,
double *x_fineparts, double *y_fineparts, double *z_fineparts,
int rx_hashsize, struct rxn **reaction_hash) {
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
/* Grab the subvolume boundaries */
struct vector3 new_sv_llf, new_sv_urb;
new_sv_llf.x = x_fineparts[new_sv->llf.x];
new_sv_llf.y = y_fineparts[new_sv->llf.y];
new_sv_llf.z = z_fineparts[new_sv->llf.z];
new_sv_urb.x = x_fineparts[new_sv->urb.x];
new_sv_urb.y = y_fineparts[new_sv->urb.y];
new_sv_urb.z = z_fineparts[new_sv->urb.z];
/* Quickly check if the subvolume bounds and the path bounds intersect */
if (!test_bounding_boxes(path_llf, path_urb, &new_sv_llf, &new_sv_urb))
return shead1;
/* Find the bounds for molecules to check */
double x_min, x_max;
double y_min, y_max;
double z_min, z_max;
if (trim_x < 0.0) {
x_min = new_sv_urb.x + trim_x;
x_max = new_sv_urb.x + EPS_C;
} else if (trim_x > 0.0) {
x_min = new_sv_llf.x - EPS_C;
x_max = new_sv_llf.x + trim_x;
} else {
x_min = new_sv_llf.x - EPS_C;
x_max = new_sv_urb.x + EPS_C;
}
if (trim_y < 0.0) {
y_min = new_sv_urb.y + trim_y;
y_max = new_sv_urb.y + EPS_C;
} else if (trim_y > 0.0) {
y_min = new_sv_llf.y - EPS_C;
y_max = new_sv_llf.y + trim_y;
} else {
y_min = new_sv_llf.y - EPS_C;
y_max = new_sv_urb.y + EPS_C;
}
if (trim_z < 0.0) {
z_min = new_sv_urb.z + trim_z;
z_max = new_sv_urb.z + EPS_C;
} else if (trim_z > 0.0) {
z_min = new_sv_llf.z - EPS_C;
z_max = new_sv_llf.z + trim_z;
} else {
z_min = new_sv_llf.z - EPS_C;
z_max = new_sv_urb.z + EPS_C;
}
/* scan molecules from this SV */
struct per_species_list *psl_next, *psl, **psl_head = &new_sv->species_head;
for (psl = new_sv->species_head; psl != NULL; psl = psl_next) {
psl_next = psl->next;
if (psl->properties == NULL) {
psl_head = &psl->next;
continue;
}
/* Garbage collection of empty per-species lists */
if (psl->head == NULL) {
*psl_head = psl->next;
ht_remove(&new_sv->mol_by_species, psl);
mem_put(new_sv->local_storage->pslv, psl);
continue;
} else
psl_head = &psl->next;
/* no possible reactions. skip it. */
if(vm->properties->flags & EXTERNAL_SPECIES){
if(!trigger_bimolecular_preliminary_nfsim((struct abstract_molecule *)vm, (struct abstract_molecule *)psl->head))
continue;
}
else{
if (!trigger_bimolecular_preliminary(
reaction_hash, rx_hashsize, vm->properties->hashval,
psl->properties->hashval, vm->properties, psl->properties))
continue;
}
for (struct volume_molecule *mp = psl->head; mp != NULL; mp = mp->next_v) {
/* Skip defunct molecules */
if (mp->properties == NULL)
continue;
/* skip molecules outside the region of interest */
if (mp->pos.x < x_min || mp->pos.x > x_max)
continue;
if (mp->pos.y < y_min || mp->pos.y > y_max)
continue;
if (mp->pos.z < z_min || mp->pos.z > z_max)
continue;
// count only in the relevant periodic box
if (!periodic_boxes_are_identical(vm->periodic_box, mp->periodic_box)) {
continue;
}
/* check for possible reactions */
/*num_matching_rxns = trigger_bimolecular(
reaction_hash, rx_hashsize, vm->properties->hashval,
mp->properties->hashval, (struct abstract_molecule *)vm,
(struct abstract_molecule *)mp, 0, 0, matching_rxns);*/
if(vm->properties->flags & EXTERNAL_SPECIES){
num_matching_rxns = trigger_bimolecular_nfsim(world, (struct abstract_molecule *)vm,
(struct abstract_molecule *)mp, 0, 0, matching_rxns);
}
else{
num_matching_rxns = trigger_bimolecular(
reaction_hash, rx_hashsize, vm->properties->hashval,
mp->properties->hashval, (struct abstract_molecule *)vm,
(struct abstract_molecule *)mp, 0, 0, matching_rxns);
}
if (num_matching_rxns <= 0)
continue;
/* Add a collision for each matching reaction */
for (int i = 0; i < num_matching_rxns; i++) {
struct collision *smash = (struct collision *)CHECKED_MEM_GET(
sv->local_storage->coll, "collision data");
smash->target = (void *)mp;
smash->intermediate = matching_rxns[i];
smash->next = shead1;
smash->what = 0;
smash->what |= COLLIDE_VOL;
shead1 = smash;
}
}
}
return shead1;
}
/****************************************************************************
expand_collision_list:
In: vm: molecule that is moving
mv: displacement to the new location
sv: subvolume that we start in
rx_radius_3d:
ny_parts:
nz_parts:
x_fineparts:
y_fineparts:
z_fineparts:
Out: Returns list of collisions with molecules from neighbor subvolumes
that are located within "interaction_radius" from the the subvolume
border. The molecules are added only when the molecule displacement
bounding box intersects with the subvolume bounding box.
****************************************************************************/
static struct collision *
expand_collision_list(struct volume *world, struct volume_molecule *vm, struct vector3 *mv,
struct subvolume *sv, double rx_radius_3d,
int ny_parts, int nz_parts, double *x_fineparts,
double *y_fineparts, double *z_fineparts, int rx_hashsize,
struct rxn **reaction_hash) {
struct collision *shead1 = NULL;
/* neighbors of the current subvolume */
struct vector3 path_llf, path_urb;
double R = (rx_radius_3d);
/* find the molecule path bounding box. */
path_bounding_box(&vm->pos, mv, &path_llf, &path_urb, rx_radius_3d);
/* Decide which directions we need to go */
int x_neg = 0, x_pos = 0, y_neg = 0, y_pos = 0, z_neg = 0, z_pos = 0;
if (!(sv->world_edge & X_POS_BIT) && path_urb.x + R > x_fineparts[sv->urb.x])
x_pos = 1;
if (!(sv->world_edge & X_NEG_BIT) && path_llf.x - R < x_fineparts[sv->llf.x])
x_neg = 1;
if (!(sv->world_edge & Y_POS_BIT) && path_urb.y + R > y_fineparts[sv->urb.y])
y_pos = 1;
if (!(sv->world_edge & Y_NEG_BIT) && path_llf.y - R < y_fineparts[sv->llf.y])
y_neg = 1;
if (!(sv->world_edge & Z_POS_BIT) && path_urb.z + R > z_fineparts[sv->urb.z])
z_pos = 1;
if (!(sv->world_edge & Z_NEG_BIT) && path_llf.z - R < z_fineparts[sv->llf.z])
z_neg = 1;
/* go in the direction X_POS */
if (x_pos) {
struct subvolume *new_sv = sv + (nz_parts - 1) * (ny_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv, &path_llf, &path_urb, shead1, R, 0.0, 0.0, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y) */
if (y_pos) {
struct subvolume *new_sv_y = new_sv + (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y, &path_llf, &path_urb, shead1, R, R, 0.0, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y + 1, &path_llf, &path_urb, shead1, R, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, +Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y - 1, &path_llf, &path_urb, shead1, R, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +X, -Y) */
if (y_neg) {
struct subvolume *new_sv_y = new_sv - (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y, &path_llf, &path_urb, shead1, R, -R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y + 1, &path_llf, &path_urb, shead1, R, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y - 1, &path_llf, &path_urb, shead1, R, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go +X, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv + 1, &path_llf, &path_urb, shead1, R, 0.0, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +X, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv - 1, &path_llf, &path_urb, shead1, R, 0.0, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go in the direction X_NEG */
if (x_neg) {
struct subvolume *new_sv = sv - (nz_parts - 1) * (ny_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv, &path_llf, &path_urb, shead1, -R, 0.0, 0.0, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y) */
if (y_pos) {
struct subvolume *new_sv_y = new_sv + (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y, &path_llf, &path_urb, shead1, -R, R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y + 1, &path_llf, &path_urb, shead1, -R, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, +Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y - 1, &path_llf, &path_urb, shead1, -R, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -X, -Y) */
if (y_neg) {
struct subvolume *new_sv_y = new_sv - (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y, &path_llf, &path_urb, shead1, -R, -R, 0.0,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y + 1, &path_llf, &path_urb, shead1, -R, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv_y - 1, &path_llf, &path_urb, shead1, -R, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go -X, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv + 1, &path_llf, &path_urb, shead1, -R, 0.0, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -X, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv - 1, &path_llf, &path_urb, shead1, -R, 0.0, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go in the direction Y_POS */
if (y_pos) {
struct subvolume *new_sv = sv + (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv, &path_llf, &path_urb, shead1, 0.0, R, 0.0, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv + 1, &path_llf, &path_urb, shead1, 0.0, R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go +Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv - 1, &path_llf, &path_urb, shead1, 0.0, R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go in the direction Y_NEG */
if (y_neg) {
struct subvolume *new_sv = sv - (nz_parts - 1);
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv, &path_llf, &path_urb, shead1, 0.0, -R, 0.0, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -Y, +Z) */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv + 1, &path_llf, &path_urb, shead1, 0.0, -R, R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go -Y, -Z */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, new_sv - 1, &path_llf, &path_urb, shead1, 0.0, -R, -R,
x_fineparts, y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
}
/* go in the direction Z_POS */
if (z_pos)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, sv + 1, &path_llf, &path_urb, shead1, 0.0, 0.0, R, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
/* go in the direction Z_NEG */
if (z_neg)
shead1 = expand_collision_list_for_neighbor(world,
sv, vm, sv - 1, &path_llf, &path_urb, shead1, 0.0, 0.0, -R, x_fineparts,
y_fineparts, z_fineparts, rx_hashsize, reaction_hash);
return shead1;
}
/****************************************************************************
expand_collision_partner_list_for_neighbor:
This is a helper function to reduce duplicated code in
expand_collision_partner_list. This code will be called once for each
adjacent subvolume. The clipping indicators below (trim_[xyz]) are
interpreted as follows:
trim < 0: We went in the negative direction for this axis. Search within
-trim of the maximal partition boundary in the adjacent subvol
trim > 0: We went in the positive direction for this axis. Search within
trim of the minimal partition boundary in the adjacent subvol
trim = 0: The subvolume is adjacent along this axis. Search the entire
width of this axis of the subvolume.
In: struct subvolume *sv - the "current" subvolume
struct volume_molecule *vm - the current molecule
struct vector3 *mv - displacement to the new location
struct subvolume *new_sv - adjacent subvolume to search
struct vector3 *path_llf - path bounding box lower left front
struct vector3 *path_urb - path bounding box upper right back
struct sp_collision *shead1 - current list head
double trim_x - X clipping indicator
double trim_y - Y clipping indicator
double trim_z - Z clipping indicator
Out: Returns linked list of molecules from neighbor subvolumes
that are located within "interaction_radius" from the the subvolume
border.
The molecules are added only when the molecule displacement
bounding box intersects with the subvolume bounding box.
****************************************************************************/
struct sp_collision *expand_collision_partner_list_for_neighbor(
struct subvolume *sv, struct volume_molecule *vm, struct vector3 *mv,
struct subvolume *new_sv, struct vector3 *path_llf,
struct vector3 *path_urb, struct sp_collision *shead1, double trim_x,
double trim_y, double trim_z, double *x_fineparts, double *y_fineparts,
double *z_fineparts, int rx_hashsize, struct rxn **reaction_hash) {
struct species *spec = vm->properties;
struct sp_collision *smash;
/* Grab the subvolume boundaries */
struct vector3 new_sv_llf, new_sv_urb;
new_sv_llf.x = x_fineparts[new_sv->llf.x];
new_sv_llf.y = y_fineparts[new_sv->llf.y];
new_sv_llf.z = z_fineparts[new_sv->llf.z];
new_sv_urb.x = x_fineparts[new_sv->urb.x];
new_sv_urb.y = y_fineparts[new_sv->urb.y];
new_sv_urb.z = z_fineparts[new_sv->urb.z];
/* Quickly check if the subvolume bounds and the path bounds intersect */
if (!test_bounding_boxes(path_llf, path_urb, &new_sv_llf, &new_sv_urb))
return shead1;
int moving_tri_molecular_flag = 0, moving_bi_molecular_flag = 0,
moving_mol_mol_grid_flag = 0;
/* collision flags */
int col_tri_molecular_flag = 0, col_bi_molecular_flag = 0,
col_mol_mol_grid_flag = 0;
moving_tri_molecular_flag =
((spec->flags & (CAN_VOLVOLVOL | CANT_INITIATE)) == CAN_VOLVOLVOL);
moving_bi_molecular_flag =
((spec->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL);
moving_mol_mol_grid_flag =
((spec->flags & (CAN_VOLVOLSURF | CANT_INITIATE)) == CAN_VOLVOLSURF);
/* Find the bounds for molecules to check */
double x_min, x_max;
double y_min, y_max;
double z_min, z_max;
if (trim_x < 0.0) {
x_min = new_sv_urb.x + trim_x;
x_max = new_sv_urb.x + EPS_C;
} else if (trim_x > 0.0) {
x_min = new_sv_llf.x - EPS_C;
x_max = new_sv_llf.x + trim_x;
} else {
x_min = new_sv_llf.x - EPS_C;
x_max = new_sv_urb.x + EPS_C;
}
if (trim_y < 0.0) {
y_min = new_sv_urb.y + trim_y;
y_max = new_sv_urb.y + EPS_C;
} else if (trim_y > 0.0) {
y_min = new_sv_llf.y - EPS_C;
y_max = new_sv_llf.y + trim_y;
} else {
y_min = new_sv_llf.y - EPS_C;
y_max = new_sv_urb.y + EPS_C;
}
if (trim_z < 0.0) {
z_min = new_sv_urb.z + trim_z;
z_max = new_sv_urb.z + EPS_C;
} else if (trim_z > 0.0) {
z_min = new_sv_llf.z - EPS_C;
z_max = new_sv_llf.z + trim_z;
} else {
z_min = new_sv_llf.z - EPS_C;
z_max = new_sv_urb.z + EPS_C;
}
/* scan molecules from this SV */
struct per_species_list *psl_next, *psl, **psl_head = &new_sv->species_head;
for (psl = new_sv->species_head; psl != NULL; psl = psl_next) {
psl_next = psl->next;
if (psl->properties == NULL) {
psl_head = &psl->next;
continue;
}
/* Garbage collection of empty per-species lists */
if (psl->head == NULL) {
*psl_head = psl->next;
ht_remove(&new_sv->mol_by_species, psl);
mem_put(new_sv->local_storage->pslv, psl);
continue;
} else
psl_head = &psl->next;
int preliminary_check = 0;
if(spec->flags & EXTERNAL_SPECIES){
preliminary_check =trigger_bimolecular_preliminary_nfsim((struct abstract_molecule *)vm,
(struct abstract_molecule *)psl->head);
}
else{
preliminary_check = trigger_bimolecular_preliminary(reaction_hash, rx_hashsize,
spec->hashval, psl->properties->hashval,
spec, psl->properties);
}
col_tri_molecular_flag =
moving_tri_molecular_flag &&
((psl->properties->flags & CAN_VOLVOLVOL) == CAN_VOLVOLVOL);
col_bi_molecular_flag =
moving_bi_molecular_flag &&
((psl->properties->flags & CAN_VOLVOL) == CAN_VOLVOL) && preliminary_check;
col_mol_mol_grid_flag =
moving_mol_mol_grid_flag &&
((psl->properties->flags & CAN_VOLVOLSURF) == CAN_VOLVOLSURF);
if (col_bi_molecular_flag || col_tri_molecular_flag ||
col_mol_mol_grid_flag) {
struct volume_molecule *mp;
for (mp = psl->head; mp != NULL; mp = mp->next_v) {
/* Skip defunct molecules */
if (mp->properties == NULL)
continue;
/* skip molecules outside the region of interest */
if (mp->pos.x < x_min || mp->pos.x > x_max)
continue;
if (mp->pos.y < y_min || mp->pos.y > y_max)
continue;
if (mp->pos.z < z_min || mp->pos.z > z_max)
continue;
smash = (struct sp_collision *)CHECKED_MEM_GET(
sv->local_storage->sp_coll, "collision data");
smash->t = 0.0;
smash->t_start = 0.0;
smash->pos_start.x = vm->pos.x;
smash->pos_start.y = vm->pos.y;
smash->pos_start.z = vm->pos.z;
smash->sv_start = sv;
smash->disp.x = mv->x;
smash->disp.y = mv->y;
smash->disp.z = mv->z;
smash->loc.x = 0.0;
smash->loc.y = 0.0;
smash->loc.z = 0.0;
smash->moving = spec;
smash->target = (void *)mp;
smash->what = 0;
if (col_bi_molecular_flag) {
smash->what |= COLLIDE_VOL;
}
if (col_tri_molecular_flag) {
smash->what |= COLLIDE_VOL_VOL;
}
if (col_mol_mol_grid_flag) {
smash->what |= COLLIDE_VOL_SURF;
}
smash->next = shead1;
shead1 = smash;
}
}
}
return shead1;
}
/*************************************************************************
diffuse_3D:
In: world: simulation state
vm: molecule that is moving
max_time: maximum time we can spend diffusing
Out: Pointer to the molecule if it still exists (may have been
reallocated), NULL otherwise.
Position and time are updated, but molecule is not rescheduled.
Note: This version takes into account only 2-way reactions and 3-way
reactions of type MOL_GRID_GRID
*************************************************************************/
struct volume_molecule *diffuse_3D(
struct volume *world,
struct volume_molecule *vm,
double max_time) {
world->diffuse_3d_calls++;
struct species* spec = vm->properties;
if (spec == NULL) {
mcell_internal_error(
"Attempted to take a diffusion step for a defunct molecule.");
}
/* flags related to the possible reaction between volume molecule
and one or two surface molecules */
int mol_grid_flag = ((spec->flags & CAN_VOLSURF) == CAN_VOLSURF);
int mol_grid_grid_flag = ((spec->flags & CAN_VOLSURFSURF) == CAN_VOLSURFSURF);
if (vm->get_space_step(vm) <= 0.0) {
vm->t += max_time;
return vm;
}
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION3(
dump_volume_molecule(vm, "", true, "Diffusing vm:", world->current_iterations, vm->t, true);
);
#endif
int inertness = 0;
set_inertness_and_maxtime(world, vm, &max_time, &inertness);
ASSERT_FOR_MCELL4(inertness == 0);
/* Done housekeeping, now let's do something fun! */
int calculate_displacement = 1;
/* this flag is set to 1 only after reflection from a wall and only with
* expanded lists. */
int redo_expand_collision_list_flag = 0;
/* initialize before fake recursion */
double steps = 1.0;
double t_steps = 1.0;
double rate_factor = 1.0;
double r_rate_factor = 1.0;
struct vector3 displacement; /* Molecule moves along this vector */
struct vector3 displacement2; /* Used for 3D mol-mol unbinding */
bool displacement_printed = false; // mcell4
bool timing_printed = false; // mcell4
pretend_to_call_diffuse_3D: ; /* Label to allow fake recursion */
struct subvolume *sv = vm->subvol;
struct collision *shead = NULL; /* Things we might hit (can interact with) */
struct collision *stail = NULL; /* Things we might hit (can interact with -
tail of the collision linked list) */
struct collision *shead_exp = NULL; /* Things we might hit (can interact with)
from neighbor subvolumes */
/* scan subvolume for possible mol-mol reactions with vm */
if ((spec->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL &&
inertness < inert_to_all) {
determine_mol_mol_reactions(world, vm, &shead, &stail, inertness);
}
if (calculate_displacement) {
compute_displacement(world, shead, vm, &displacement, &displacement2,
&rate_factor, &r_rate_factor, &steps, &t_steps, max_time);
}
#ifdef DEBUG_TIMING
DUMP_CONDITION3(
if (!timing_printed) {
MCell::dump_vol_mol_timing(
"- Timing vm", world->current_iterations, vm->id,
vm->t, max_time, vm->t + vm->t2,
rate_factor, r_rate_factor, steps, t_steps
);
timing_printed = true;
}
);
#endif
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION3(
if (!displacement_printed) {
dump_vector3(displacement, " displacement:");
std::cout << "t_steps: " << t_steps << "\n";
displacement_printed = true;
}
);
#endif
if (world->use_expanded_list &&
((vm->properties->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL) &&
!inertness) {
shead_exp = expand_collision_list(world,
vm, &displacement, sv, world->rx_radius_3d, world->ny_parts,
world->nz_parts, world->x_fineparts, world->y_fineparts,
world->z_fineparts, world->rx_hashsize, world->reaction_hash);
if (stail != NULL)
stail->next = shead_exp;
else {
if (shead != NULL)
mcell_internal_error("Collision lists corrupted. While expanding the "
"collision lists, expected shead to be NULL, but "
"it wasn't.");
shead = shead_exp;
}
}
struct wall* reflectee = NULL;
struct collision *smash; /* Thing we've hit that's under consideration */
do {
/* due to redo_expand_collision_list_flag this only happens after reflection */
if (world->use_expanded_list && redo_expand_collision_list_flag) {
redo_collision_list(world, &shead, &stail, &shead_exp, vm, &displacement, sv);
}
struct collision* shead2 = ray_trace(world, &(vm->pos), shead, sv, &displacement, reflectee);
if (shead2 == NULL) {
mcell_internal_error("ray_trace returned NULL.");
}
if (shead2->next != NULL) {
shead2 =
(struct collision *)ae_list_sort((struct abstract_element *)shead2);
}
#ifdef DEBUG_COLLISIONS
DUMP_CONDITION3(
dump_collisions(shead2);
);
#endif
struct vector3* loc_certain = NULL;
struct collision *tentative = shead2;
for (smash = shead2; smash != NULL; smash = smash->next) {
if (world->notify->molecule_collision_report == NOTIFY_FULL) {
if (((smash->what & COLLIDE_VOL) != 0) &&
(world->rxn_flags.vol_vol_reaction_flag)) {
world->vol_vol_colls++;
}
}
if (smash->t >= 1.0 || smash->t < 0.0) {
if ((smash->what & COLLIDE_VOL) != 0) {
mcell_internal_error(
"Detected a mol-mol collision outside of the 0.0...1.0 time "
"window. Iteration %lld, time of collision %.8e, mol1=%s, "
"mol2=%s",
world->current_iterations, smash->t, vm->properties->sym->name,
((struct volume_molecule *)smash->target)->properties->sym->name);
}
smash = NULL;
break;
}
if ((smash->what & COLLIDE_VOL) != 0) {
if (smash->t < EPS_C) {
continue;
}
if (collide_and_react_with_vol_mol(world, smash, vm, &tentative,
&displacement, loc_certain, t_steps, r_rate_factor) == 1) {
FREE_COLLISION_LISTS();
return NULL;
} else {
continue;
}
} else if ((smash->what & COLLIDE_WALL) != 0) {
struct wall* w = (struct wall *)smash->target;
if (w->grid != NULL && (mol_grid_flag || mol_grid_grid_flag) &&
inertness < inert_to_all) {
int destroyed = collide_and_react_with_surf_mol(world, smash, vm,
&tentative, &loc_certain, t_steps, mol_grid_flag, mol_grid_grid_flag,
r_rate_factor);
// if destroyed = -1 we didn't react with any molecules and keep going
// to check for wall collisions
if (destroyed == 1) {
FREE_COLLISION_LISTS();
return NULL;
} else if (destroyed == 0) {
continue;
}
}
if ((spec->flags & CAN_VOLWALL) != 0) {
int destroyed = collide_and_react_with_walls(world, smash, vm,
&tentative, &loc_certain, t_steps, inertness, r_rate_factor);
// if destroyed = -1 we didn't react with any walls and keep going to
// either reflect or encounter periodic bc
if (destroyed == 1) {
FREE_COLLISION_LISTS();
return NULL;
} else if (destroyed == 0) {
continue;
}
}
if (reflect_or_periodic_bc(world, smash, &displacement, &vm, &reflectee,
&tentative, &t_steps) == 1) {
FREE_COLLISION_LISTS();
calculate_displacement = 0;
if (vm->properties == NULL) {
mcell_internal_error("A defunct molecule is diffusing.");
}
// molecule was reflected into periodic box. Need to start over
// figuring out targets based on the current displacement
goto pretend_to_call_diffuse_3D;
}
// Only useful if using expanded lists, but easier to always set it
redo_expand_collision_list_flag = 1;
break;
} else if ((smash->what & COLLIDE_SUBVOL) != 0) {
collide_and_react_with_subvol(
world, smash, &displacement, &vm, &tentative, &t_steps);
FREE_COLLISION_LISTS();
calculate_displacement = 0;
if (vm->properties == NULL) {
mcell_internal_error("A defunct molecule is diffusing.");
}
// molecule entered a new subvolume. Continue motion from the beginning.
goto pretend_to_call_diffuse_3D;
}
}
if (shead2 != NULL) {
mem_put_list(sv->local_storage->coll, shead2);
}
} while (smash != NULL);
vm->pos.x += displacement.x;
vm->pos.y += displacement.y;
vm->pos.z += displacement.z;
vm->t += t_steps;
/* Done with traversing disk, now do real motion */
if (inertness == inert_to_all)
{
inertness = inert_to_mol;
t_steps = vm->get_time_step(vm);
displacement = displacement2;
calculate_displacement = 0;
goto pretend_to_call_diffuse_3D;
}
vm->index = -1;
vm->previous_wall = NULL;
if (shead != NULL)
mem_put_list(sv->local_storage->coll, shead);
#ifdef DEBUG_DIFFUSION
if (vm->properties != NULL) {
DUMP_CONDITION3(
dump_volume_molecule(vm, "", true, "- Final vm position:", world->current_iterations, /*vm->t*/0, true);
);
}
#endif
return vm;
}
/*************************************************************************
move_sm_on_same_triangle:
This is a helper function for diffuse_2D.
In: world: simulation state
sm: molecule that is moving
new_loc: this is the location we are moving to.
previous_box: this is the periodic box we were in previously.
new_wall: this is the new wall we ended up on
hd_info:
Out: The grid is created on a new triangle and we place the molecule if
possible. Counts are updated.
*************************************************************************/
int move_sm_on_same_triangle(
struct volume *state,
struct surface_molecule *sm,
struct vector2 *new_loc,
struct periodic_image *previous_box,
struct wall *new_wall,
struct hit_data *hd_info) {
unsigned int new_idx = uv2grid(new_loc, new_wall->grid);
if (new_idx >= sm->grid->n_tiles) {
mcell_internal_error("After ray_trace_2D, selected u, v coordinates "
"map to an out-of-bounds grid cell. uv=(%.2f, "
"%.2f) sm=%d/%d",
new_loc->u, new_loc->v, new_idx, sm->grid->n_tiles);
}
// We're on a new part of the grid
struct surface_molecule_list *sm_list = sm->grid->sm_list[new_idx];
if (new_idx != sm->grid_index) {
if ((state->periodic_box_obj && periodicbox_in_surfmol_list(sm->periodic_box, sm_list)) ||
(!state->periodic_box_obj && sm_list && sm_list->sm)) {
if (hd_info != NULL) {
delete_void_list((struct void_list *)hd_info);
hd_info = NULL;
}
return 1; /* Pick again--full here */
}
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid_index = new_idx;
sm->grid->sm_list[new_idx] = add_surfmol_with_unique_pb_to_list(
sm->grid->sm_list[new_idx], sm);
assert(sm->grid->sm_list[new_idx] != NULL);
count_moved_surface_mol(
state, sm, sm->grid, new_loc, state->count_hashmask,
state->count_hash, &state->ray_polygon_colls, previous_box);
// We ended up on the same exact grid element!
// XXX: do we even need to update counts??
} else {
count_moved_surface_mol(
state, sm, sm->grid, new_loc, state->count_hashmask,
state->count_hash, &state->ray_polygon_colls, previous_box);
}
sm->s_pos.u = new_loc->u;
sm->s_pos.v = new_loc->v;
return 0;
}
/*************************************************************************
move_sm_to_new_triangle:
This is a helper function for diffuse_2D.
In: world: simulation state
sm: molecule that is moving
new_loc: this is the location we are moving to.
previous_box: this is the periodic box we were in previously.
new_wall: this is the new wall we ended up on
hd_info:
Out: The grid is created on a new triangle and we place the molecule if
possible. Counts are updated.
*************************************************************************/
int move_sm_to_new_triangle(
struct volume *state,
struct surface_molecule *sm,
struct vector2 *new_loc,
struct periodic_image *previous_box,
struct wall *new_wall,
struct hit_data *hd_info) {
// No SM has been here before, so we need to make a grid on this wall.
if (new_wall->grid == NULL) {
if (create_grid(state, new_wall, NULL))
mcell_allocfailed("Failed to create a grid for a wall.");
}
/* Move to new tile */
unsigned int new_idx = uv2grid(new_loc, new_wall->grid);
if (new_idx >= new_wall->grid->n_tiles) {
mcell_internal_error(
"After ray_trace_2D to a new wall, selected u, v coordinates map "
"to an out-of-bounds grid cell. uv=(%.2f, %.2f) sm=%d/%d",
new_loc->u, new_loc->v, new_idx, new_wall->grid->n_tiles);
}
struct surface_molecule_list *sm_list = new_wall->grid->sm_list[new_idx];
if ((state->periodic_box_obj && periodicbox_in_surfmol_list(sm->periodic_box, sm_list)) ||
(!state->periodic_box_obj && sm_list && sm_list->sm)) {
if (hd_info != NULL) {
delete_void_list((struct void_list *)hd_info);
hd_info = NULL;
}
return 1; /* Pick again--full here */
}
count_moved_surface_mol(
state, sm, new_wall->grid, new_loc, state->count_hashmask,
state->count_hash, &state->ray_polygon_colls, previous_box);
remove_surfmol_from_list(&sm->grid->sm_list[sm->grid_index], sm);
sm->grid->n_occupied--;
sm->grid = new_wall->grid;
sm->grid_index = new_idx;
sm_list = add_surfmol_with_unique_pb_to_list(sm->grid->sm_list[new_idx], sm);
assert(sm_list != NULL);
sm->grid->sm_list[sm->grid_index] = sm_list;
sm->grid->n_occupied++;
sm->s_pos.u = new_loc->u;
sm->s_pos.v = new_loc->v;
return 0;
}
/*************************************************************************
diffuse_2D:
In: world: simulation state
sm: molecule that is moving
max_time: maximum time we can spend diffusing
advance_time: how much to advance molecule internal time (return value)
Out: Pointer to the molecule, or NULL if there was an error (right now
there is no reallocation)
Position and time are updated, but molecule is not rescheduled,
nor does it react
To-do: This doesn't work with triggers. Change style of counting code
so that it can update as we go, like with 3D diffusion.
*************************************************************************/
struct surface_molecule *diffuse_2D(
struct volume *world,
struct surface_molecule *sm,
double max_time,
double *advance_time) {
struct species *spec = sm->properties;
if (spec == NULL) {
mcell_internal_error(
"Attempted to take a 2-D diffusion step for a defunct molecule.");
}
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION3(
dump_surface_molecule(sm, "", true, "Diffusing sm:", world->current_iterations, sm->t, true);
);
#endif
// XXX: When would this ever happen, and shouldn't it just be an error?
if (sm->get_space_step(sm) <= 0.0) {
sm->t += max_time;
return sm;
}
// Using global SPACE_STEP or per species CUSTOM_SPACE_STEP/CUSTOM_TIME_STEP
if (sm->get_time_step(sm) > 1.0) {
double sched_time = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, sm->t);
/* Newly created particles with long custom time steps gradually increase
* their timestep to the full value... Why??? */
double f = 1 + 0.2 * ((sched_time - sm->birthday)/world->time_unit);
if (f < 1)
mcell_internal_error("A %s molecule is scheduled to move before it was "
"born [birthday=%.15g, t=%.15g]",
spec->sym->name, sm->birthday, sched_time);
if (max_time > f)
max_time = f;
}
double steps = 0.0;
double t_steps = 0.0;
double space_factor = 0.0;
/* Where are we going? */
if (sm->get_time_step(sm) > max_time) {
t_steps = max_time;
steps = max_time / sm->get_time_step(sm);
} else {
t_steps = sm->get_time_step(sm);
steps = 1.0;
}
if (steps < EPS_C) {
steps = EPS_C;
t_steps = EPS_C * sm->get_time_step(sm);
}
if (steps == 1.0)
space_factor = sm->get_space_step(sm);
else
space_factor = sm->get_space_step(sm) * sqrt(steps);
#ifdef DEBUG_TIMING
DUMP_CONDITION3(
MCell::dump_surf_mol_timing(
"- Timing sm", world->current_iterations, sm->id,
sm->t, max_time, sm->t + sm->t2,
space_factor, steps, t_steps
); // advance_time?
);
#endif
world->diffusion_number++;
world->diffusion_cumtime += steps;
struct periodic_image previous_box = {sm->periodic_box->x,
sm->periodic_box->y,
sm->periodic_box->z
};
struct hit_data *hd_info = NULL;
for (int find_new_position = (SURFACE_DIFFUSION_RETRIES + 1);
find_new_position > 0; find_new_position--) {
hd_info = NULL;
struct vector2 displacement;
pick_2D_displacement(&displacement, space_factor, world->rng);
#ifdef DEBUG_DIFFUSION
DUMP_CONDITION3(
dump_vector2(displacement, " displacement:")
);
#endif
if (sm->properties->flags & SET_MAX_STEP_LENGTH) {
double disp_length = sqrt(displacement.u * displacement.u +
displacement.v * displacement.v);
if (disp_length > sm->properties->max_step_length) {
/* rescale displacement to the level of MAXIMUM_STEP_LENGTH */
displacement.u *= (sm->properties->max_step_length / disp_length);
displacement.v *= (sm->properties->max_step_length / disp_length);
}
}
struct vector2 new_loc;
struct rxn *rxp = NULL;
int kill_me = 0;
struct wall *new_wall = ray_trace_2D(world, sm, &displacement, &new_loc,
&kill_me, &rxp, &hd_info);
// Either something ambiguous happened or we hit absorptive border
if (new_wall == NULL) {
if (kill_me == 1) {
/* molecule hit ABSORPTIVE region border */
if (rxp == NULL) {
mcell_internal_error("Error in 'ray_trace_2D()' after hitting "
"ABSORPTIVE region border.");
}
if (hd_info != NULL) {
count_region_border_update(world, sm->properties, hd_info, sm->id);
}
int result = outcome_unimolecular(world, rxp, 0,
(struct abstract_molecule *)sm, sm->t);
if (result != RX_DESTROY) {
mcell_internal_error("Molecule should disappear after hitting "
"ABSORPTIVE region border.");
}
delete_void_list((struct void_list *)hd_info);
hd_info = NULL;
return NULL;
}
if (hd_info != NULL) {
delete_void_list((struct void_list *)hd_info);
hd_info = NULL;
}
continue; /* Something went wrong--try again */
}
// After diffusing, we are still on the SAME triangle.
if (new_wall == sm->grid->surface) {
if (move_sm_on_same_triangle(world, sm, &new_loc, &previous_box, new_wall, hd_info)) {
continue;
}
}
// After diffusing, we ended up on a NEW triangle.
else {
if (move_sm_to_new_triangle(world, sm, &new_loc, &previous_box, new_wall, hd_info)) {
continue;
}
}
find_new_position = 0;
}
if (hd_info != NULL) {
count_region_border_update(world, sm->properties, hd_info, sm->id);
delete_void_list((struct void_list *)hd_info);
hd_info = NULL;
}
*advance_time = t_steps;
return sm;
}
/***************************************************************************
react_2D_all_neighbors:
In: world: simulation state
sm: molecule that may react
t: maximum duration we have to react
molecule_collision_report:
grid_grid_reaction_flag:
surf_surf_colls:
Out: Pointer to the molecule if it still exists (may have been
destroyed), NULL otherwise.
Note: Time is not updated--assume that's already taken care of
elsewhere.
This function takes into account variable number of neighbors.
Note: If surface molecule (reaction initiator) or potential reaction
partner are located on the different regions and any of them is
behind the restrictive region boundary - we do not even
test for reaction.
****************************************************************************/
struct surface_molecule *
react_2D_all_neighbors(struct volume *world, struct surface_molecule *sm,
double t, enum notify_level_t molecule_collision_report,
int grid_grid_reaction_flag,
long long *surf_surf_colls) {
#ifdef DEBUG_TIMING
DUMP_CONDITION3(
MCell::dump_react_2D_all_neighbors_timing(t, sm->t);
);
#endif
int i; /* points to the pathway of the reaction */
int j; /* points to the the reaction */
int n = 0; /* total number of possible reactions for a given molecules
with all its neighbors */
int l = 0;
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
/* linked list of the tile neighbors */
struct tile_neighbor *tile_nbr_head = NULL, *curr;
int list_length = 0; /* length of the linked lists above */
if ((u_int)sm->grid_index >= sm->grid->n_tiles) {
mcell_internal_error("tile index %u is greater or equal number_of_tiles %u",
(u_int)sm->grid_index, sm->grid->n_tiles);
}
find_neighbor_tiles(world, sm, sm->grid, sm->grid_index, 0, 1, &tile_nbr_head,
&list_length);
if (tile_nbr_head == NULL)
return sm; /* no reaction may happen */
const int num_nbrs = list_length;
int max_size = num_nbrs * MAX_MATCHING_RXNS;
/* array of reaction objects with neighbor molecules */
std::vector<struct rxn *> rxn_array(max_size);
double local_prob_factor; /* local probability factor for the
reactions */
std::vector<double> cf(max_size); /* Correction factors for area for those molecules */
std::vector<struct surface_molecule *> smol(max_size); /* points to neighbor molecules */
/* Calculate local_prob_factor for the reaction probability.
Here we convert from 3 neighbor tiles (upper probability
limit) to the real "num_nbrs" neighbor tiles. */
local_prob_factor = 3.0 / num_nbrs;
for (int kk = 0; kk < max_size; kk++) { // NOTE: this is done every call..
rxn_array[kk] = NULL;
smol[kk] = NULL;
cf[kk] = 0;
}
/* step through the neighbors */
for (curr = tile_nbr_head; curr != NULL; curr = curr->next) {
/* Neighboring molecule */
struct surface_molecule_list *sm_list = curr->grid->sm_list[curr->idx];
if (sm_list == NULL || sm_list->sm == NULL)
continue;
struct surface_molecule *smp = curr->grid->sm_list[curr->idx]->sm;
#ifdef DEBUG_RXNS
DUMP_CONDITION3(
dump_surface_molecule(smp, "", true, " checking in react_2D_all_neighbors: ", world->current_iterations, 0.0, true);
);
#endif
/* check whether the neighbor molecule is behind
the restrictive region boundary */
if ((sm->properties->flags & CAN_REGION_BORDER) ||
(smp->properties->flags & CAN_REGION_BORDER)) {
if (sm->grid->surface != smp->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, sm, smp->grid->surface, smp))
continue;
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, smp, smp->grid->surface, sm))
continue;
}
}
if(sm->properties->flags & EXTERNAL_SPECIES){
num_matching_rxns = trigger_bimolecular_nfsim(world, (struct abstract_molecule *)sm,
(struct abstract_molecule *)smp, sm->orient, smp->orient, matching_rxns);
}
else{
num_matching_rxns = trigger_bimolecular(
world->reaction_hash, world->rx_hashsize, sm->properties->hashval,
smp->properties->hashval, (struct abstract_molecule *)sm,
(struct abstract_molecule *)smp, sm->orient, smp->orient,
matching_rxns);
}
if (num_matching_rxns > 0) {
if (molecule_collision_report == NOTIFY_FULL) {
if (grid_grid_reaction_flag)
surf_surf_colls++;
}
for (int jj = 0; jj < num_matching_rxns; jj++) {
if (matching_rxns[jj] != NULL) {
if (matching_rxns[jj]->prob_t != NULL)
update_probs(world, matching_rxns[jj], sm->t);
rxn_array[l] = matching_rxns[jj];
cf[l] = t / (curr->grid->binding_factor);
smol[l] = smp;
l++;
}
}
n += num_matching_rxns;
}
}
delete_tile_neighbor_list(tile_nbr_head);
if (n == 0) {
return sm; /* Nobody to react with */
} else if (n == 1) {
i = test_bimolecular(rxn_array[0], cf[0], local_prob_factor, NULL, NULL,
world->rng);
j = 0;
} else {
// previously "test_many_bimolecular_all_neighbors"
int all_neighbors_flag = 1;
j = test_many_bimolecular(&rxn_array[0], &cf[0], local_prob_factor, n, &(i),
world->rng, all_neighbors_flag);
}
if ((j == RX_NO_RX) || (i < RX_LEAST_VALID_PATHWAY)) {
return sm; /* No reaction */
}
/* run the reaction */
int outcome_bimol_result = outcome_bimolecular(
world, rxn_array[j], i, (struct abstract_molecule *)sm,
(struct abstract_molecule *)smol[j], sm->orient, smol[j]->orient, sm->t,
NULL, NULL);
if (outcome_bimol_result == RX_DESTROY) {
mem_put(sm->birthplace, sm);
return NULL;
}
return sm;
}
/*************************************************************************
clean_up_old_molecules:
This function just removes defunct molecules from the scheduler.
*************************************************************************/
void clean_up_old_molecules(struct storage *local) {
if (local->timer->defunct_count > MIN_DEFUNCT_FOR_GC &&
MAX_DEFUNCT_FRAC * (local->timer->count) < local->timer->defunct_count) {
struct abstract_molecule *am;
am = (struct abstract_molecule *)schedule_cleanup(local->timer,
*is_defunct_molecule);
while (am != NULL) {
struct abstract_molecule *temp = am;
am = am->next;
if ((temp->flags & IN_MASK) == IN_SCHEDULE) {
temp->next = NULL;
mem_put(temp->birthplace, temp);
} else {
temp->flags &= ~IN_SCHEDULE;
}
}
}
}
/*************************************************************************
reschedule_surface_molecules:
If a surface molecules moves across a memory subdivision boundary, it might
need to be reallocated and moved to a new scheduler.
*************************************************************************/
void reschedule_surface_molecules(
struct volume *state, struct storage *local,
struct abstract_molecule *am) {
struct vector3 pos3d;
struct surface_molecule *sm = (struct surface_molecule *)(void *)am;
uv2xyz(&sm->s_pos, sm->grid->surface, &pos3d);
struct subvolume *sv = find_subvolume(state, &pos3d, sm->grid->subvol);
if (sv->local_storage != local) {
struct surface_molecule *sm_new =
(struct surface_molecule *)CHECKED_MEM_GET(sv->local_storage->smol,
"surface molecule");
memcpy(sm_new, sm, sizeof(struct surface_molecule));
sm_new->next = NULL;
sm_new->birthplace = sv->local_storage->smol;
if (sm->grid->sm_list[sm->grid_index] &&
(sm->grid->sm_list[sm->grid_index]->sm == sm)) {
sm->grid->sm_list[sm->grid_index]->sm = sm_new;
sm->grid = NULL;
sm->grid_index = 0;
}
mem_put(sm->birthplace, sm);
if (schedule_add_mol(sv->local_storage->timer, sm_new))
mcell_allocfailed("Failed to add a '%s' surface molecule to scheduler "
"after migrating to a new memory store.",
am->properties->sym->name);
} else {
if (schedule_add_mol(local->timer, am))
mcell_allocfailed("Failed to add a '%s' surface molecule to scheduler "
"after taking a diffusion step.",
am->properties->sym->name);
}
}
/*************************************************************************
run_timestep:
In: state: simulation state
local: local storage area to use
release_time: time of the next release event
checkpt_time: time of the next checkpoint
Out: No return value. Every molecule in the subvolume is updated in
position and rescheduled at least one timestep ahead.
Note: This also occasionally does garbage collection on the scheduling
queue.
*************************************************************************/
void run_timestep(struct volume *state, struct storage *local,
double release_time, double checkpt_time) {
struct abstract_molecule *am;
// Check for garbage collection first
clean_up_old_molecules(local);
// Now run the timestep
#ifdef MCELL3_SORTED_MOLS_ON_RUN_TIMESTEP
#ifdef DUMP_LOCAL_SCHEDULE_HELPER
dump_schedule_helper(local->timer, "Before sorting", "", "", true);
#endif
// sort by time and id so that we get the same ordering as in mcell4
sort_schedule_by_time_and_id(local->timer);
#ifdef DUMP_LOCAL_SCHEDULE_HELPER
dump_schedule_helper(local->timer, "After sorting", "", "", true);
#endif
#endif
/* Do not trigger the scheduler to advance! This will be done
* by the main loop. */
while (local->timer->current != NULL) {
#ifdef DUMP_LOCAL_SCHEDULE_HELPER
dump_schedule_helper(local->timer, "local", "", "", true);
#endif
#ifdef MCELL3_4_ALWAYS_SORT_MOLS_BY_TIME_AND_ID
#ifdef DUMP_LOCAL_SCHEDULE_HELPER
dump_schedule_helper(local->timer, "Before sorting", "", "", true);
#endif
sort_schedule_by_time_and_id(local->timer);
#ifdef DUMP_LOCAL_SCHEDULE_HELPER
dump_schedule_helper(local->timer, "After sorting", "", "", true);
#endif
#endif
am = (struct abstract_molecule *)schedule_next(local->timer);
if (am->properties == NULL) /* Defunct! Remove molecule. */
{
if ((am->flags & IN_MASK) == IN_SCHEDULE) {
am->next = NULL;
mem_put(am->birthplace, am);
} else
am->flags &= ~IN_SCHEDULE;
if (local->timer->defunct_count > 0)
local->timer->defunct_count--;
continue;
}
#ifdef DEBUG_SCHEDULER
{
struct volume *world = state;
DUMP_CONDITION3(
struct volume_molecule* vm = (struct volume_molecule*)am;
dump_volume_molecule(vm, "", true, "\n* Running scheduled action: ", world->current_iterations, vm->t, true);
);
}
#endif
am->flags &= ~IN_SCHEDULE;
// Check for unimolecular reactions
// If molec is new or need rescheduled, this just computes a new lifetime
if (am->t2 < EPS_C || am->t2 < EPS_C * am->t) {
if (!check_for_unimolecular_reaction(state, am)) {
continue;
}
}
// How to advance surface molecule scheduling time
double surface_mol_advance_time = 0;
struct wall *current_wall = NULL;
// The maximum time we can spend diffusing or looking for reactions
double max_time;
#ifdef MCELL_ALWAYS_DIFFUSE
int can_diffuse = 1;
#else
int can_diffuse = ((am->flags & ACT_DIFFUSE) != 0);
#endif
if (can_diffuse) {
max_time = checkpt_time - am->t;
if (local->max_timestep < max_time)
max_time = local->max_timestep;
if ((am->flags & (ACT_REACT)) != 0 && am->t2 < max_time)
max_time = am->t2;
if ((am->flags & TYPE_VOL) != 0) {
double save_sched_time = am->t;
if (max_time > release_time - am->t)
max_time = release_time - am->t;
if (am->properties->flags & (CAN_VOLVOLVOL | CAN_VOLVOLSURF))
am = (struct abstract_molecule *)diffuse_3D_big_list(
state, (struct volume_molecule *)am, max_time);
else
am = (struct abstract_molecule *)diffuse_3D(
state, (struct volume_molecule *)am, max_time);
if (am != NULL) /* We still exist */
{
// Perform only for unimolecular reactions
if ((am->flags & ACT_REACT) != 0) {
am->t2 -= am->t - save_sched_time;
if (am->t2 < 0)
am->t2 = 0;
}
} else
continue;
} else {
if (max_time > release_time - am->t) {
max_time = release_time - am->t;
}
// Remember current wall
current_wall = ((struct surface_molecule *)am)->grid->surface;
am = (struct abstract_molecule *)diffuse_2D(
state, (struct surface_molecule *)am, max_time,
&surface_mol_advance_time);
if (am == NULL) {
continue;
}
}
}
else {
// DUMP
#ifdef DEBUG_DIFFUSION
struct volume *world = state;
if ((am->flags & TYPE_VOL) != 0) {
DUMP_CONDITION3(
dump_volume_molecule((struct volume_molecule *)am, "", true, "Not diffusing vm:", world->current_iterations, am->t, true);
);
}
else {
DUMP_CONDITION3(
dump_surface_molecule((struct surface_molecule *)am, "", true, "Not diffusing sm:", world->current_iterations, am->t, true);
);
}
#endif
}
//int can_surface_mol_react =
// (am->properties->flags & (CAN_SURFSURFSURF | CAN_SURFSURF));
int can_surface_mol_react = (am->get_flags(am) & (CAN_SURFSURFSURF | CAN_SURFSURF));
if (((am->flags & TYPE_SURF) != 0) && can_surface_mol_react) {
// Didn't move, so we need to figure out how long to react for
if (!can_diffuse)
{
max_time = checkpt_time - am->t;
if (am->t2 < max_time && (am->flags & (ACT_REACT)) != 0)
max_time = am->t2;
if (max_time > release_time - am->t)
max_time = release_time - am->t;
if (am->get_time_step(am) < max_time)
max_time = am->get_time_step(am);
surface_mol_advance_time = max_time;
} else
max_time = surface_mol_advance_time;
if (can_surface_mol_react) {
if ((am->properties->flags & (CANT_INITIATE | CAN_SURFSURF)) ==
CAN_SURFSURF) {
am = (struct abstract_molecule *)react_2D_all_neighbors(
state, (struct surface_molecule *)am, max_time,
state->notify->molecule_collision_report,
state->rxn_flags.surf_surf_reaction_flag,
&(state->surf_surf_colls));
if (am == NULL)
continue;
}
if ((am->properties->flags & (CANT_INITIATE | CAN_SURFSURFSURF)) ==
CAN_SURFSURFSURF) {
am = (struct abstract_molecule *)react_2D_trimol_all_neighbors(
state, (struct surface_molecule *)am, max_time,
state->notify->molecule_collision_report,
state->notify->final_summary,
state->rxn_flags.surf_surf_surf_reaction_flag,
&(state->surf_surf_surf_colls));
if (am == NULL)
continue;
}
}
}
// Advance surface molecule scheduling time
if ((am->flags & TYPE_SURF) != 0 && (can_diffuse || can_surface_mol_react)) {
am->t += surface_mol_advance_time;
// Perform only for unimolecular reactions
if ((am->flags & ACT_REACT) != 0) {
/* This case takes care of newly created surface products A which
* only have a unimolecular surface reaction defined (A @surf) and
* are thus scheduled am->t2 = FOREVER */
int can_surf_react = ((am->properties->flags & CAN_SURFWALL) != 0);
if (can_surf_react && !distinguishable(am->t2, (double)FOREVER, EPS_C)) {
am->t2 = 0;
am->flags |= ACT_CHANGE; /* Reschedule reaction time */
}
else {
am->t2 -= surface_mol_advance_time;
if (am->t2 < 0) {
am->t2 = 0;
}
/* If the molecule didn't leave its wall AND its lifetime hasn't run
* out, then we don't need to reschedule.
* NOTE: We really only have to make sure that the new wall has the
* same collection of surface classes. Doing so could be
* significantly more efficient. */
if ((current_wall !=
((struct surface_molecule *)am)->grid->surface) &&
(am->t2 > EPS_C || am->t2 > EPS_C * am->t)) {
am->t2 = 0;
am->flags |= ACT_CHANGE; /* Reschedule reaction time */
}
}
}
} else if (!can_diffuse) {
// NOTE: t2 should only be 0 at this point if "am" is inert. This is
// basically just a clunky way to ignore it, although it's not clear why
// we can't just set t to the total number of iterations.
if (am->t2 == 0)
am->t += MAX_UNI_TIMESKIP;
else {
am->t += am->t2;
am->t2 = 0;
}
}
am->flags |= IN_SCHEDULE;
/* If we're near an integer boundary, advance to the next integer */
double t = ceil(am->t) * (1.0 + 0.1 * EPS_C);
if (!distinguishable(t, am->t, EPS_C))
am->t = t;
if (am->flags & TYPE_SURF) {
reschedule_surface_molecules(state, local, am);
} else {
if (schedule_add(
((struct volume_molecule *)am)->subvol->local_storage->timer, am))
mcell_allocfailed("Failed to add a '%s' volume molecule to scheduler "
"after taking a diffusion step.",
am->properties->sym->name);
}
}
if (local->timer->error)
mcell_internal_error("Scheduler reported an out-of-memory error while "
"retrieving molecules, but this should never happen.");
}
/*************************************************************************
run_clamp:
In: world: simulation state
t_now: the current time.
Out: No return value. Molecules are released at clamped
surfaces to maintain the desired concentation or flux.
*************************************************************************/
void run_clamp(struct volume *world, double t_now) {
int this_count = 0;
static int total_count = 0;
for (struct clamp_data *cdp = world->clamp_list; cdp != NULL; cdp = cdp->next) {
if (cdp->objp == NULL) {
continue;
}
for (struct clamp_data *cdpo = cdp; cdpo != NULL; cdpo = cdpo->next_obj) {
for (struct clamp_data *cdpm = cdpo; cdpm != NULL; cdpm = cdpm->next_mol) {
double n_collisions = cdpo->scaling_factor * cdpm->mol->space_step *
cdpm->clamp_value / cdpm->mol->time_step;
if (cdpm->orient != 0) {
n_collisions *= 0.5;
}
int n_emitted = poisson_dist(n_collisions, rng_dbl(world->rng));
if (n_emitted == 0)
continue;
struct volume_molecule vm;
vm.t = t_now + 0.5;
vm.t2 = 0;
vm.flags = IN_SCHEDULE | ACT_NEWBIE | TYPE_VOL | IN_VOLUME |
ACT_CLAMPED | ACT_DIFFUSE;
vm.properties = cdpm->mol;
initialize_diffusion_function((struct abstract_molecule*)&vm);
vm.mesh_name = NULL;
vm.birthplace = NULL;
vm.birthday = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, t_now);
vm.subvol = NULL;
vm.previous_wall = NULL;
vm.index = 0;
struct volume_molecule *vmp = NULL;
this_count += n_emitted;
while (n_emitted > 0) {
int idx = bisect_high(cdpo->cum_area, cdpo->n_sides,
rng_dbl(world->rng) *
cdpo->cum_area[cdp->n_sides - 1]);
struct wall *w = cdpo->objp->wall_p[cdpo->side_idx[idx]];
double s1 = sqrt(rng_dbl(world->rng));
double s2 = rng_dbl(world->rng) * s1;
struct vector3 v;
v.x = w->vert[0]->x + s1 * (w->vert[1]->x - w->vert[0]->x) +
s2 * (w->vert[2]->x - w->vert[1]->x);
v.y = w->vert[0]->y + s1 * (w->vert[1]->y - w->vert[0]->y) +
s2 * (w->vert[2]->y - w->vert[1]->y);
v.z = w->vert[0]->z + s1 * (w->vert[1]->z - w->vert[0]->z) +
s2 * (w->vert[2]->z - w->vert[1]->z);
if (cdpm->orient == 1) {
vm.index = 1;
}
else if (cdpm->orient == -1) {
vm.index = -1;
}
else {
vm.index = (rng_uint(world->rng) & 2) - 1;
}
double eps = EPS_C * vm.index;
s1 = fabs(v.x);
s2 = fabs(v.y);
if (s1 < s2) {
s1 = s2;
}
s2 = fabs(v.z);
if (s1 < s2) {
s1 = s2;
}
if (s1 > 1.0){
eps *= s1;
}
vm.pos.x = v.x + w->normal.x * eps;
vm.pos.y = v.y + w->normal.y * eps;
vm.pos.z = v.z + w->normal.z * eps;
vm.previous_wall = w;
// TODO: This isn't right. We need to figure out what PB these should
// really be created in.
struct periodic_image periodic_box = {0, 0, 0};
vm.periodic_box = &periodic_box;
if (vmp == NULL) {
vmp = insert_volume_molecule(world, &vm, vmp);
if (vmp == NULL)
mcell_allocfailed("Failed to insert a '%s' volume molecule while "
"concentration/flux clamping.",
vm.properties->sym->name);
if (trigger_unimolecular(world->reaction_hash, world->rx_hashsize,
cdpm->mol->hashval,
(struct abstract_molecule *)vmp) != NULL) {
vm.flags |= ACT_REACT;
vmp->flags |= ACT_REACT;
}
} else {
vmp = insert_volume_molecule(world, &vm, vmp);
if (vmp == NULL)
mcell_allocfailed("Failed to insert a '%s' volume molecule while "
"concentration/flux clamping.",
vm.properties->sym->name);
}
n_emitted--;
}
}
}
}
total_count += this_count;
}
/******************************************************************************
*
* redo_collision list is a helper function used in diffuse_3D to compute the
* list of possible collisions in neighboring subvolumes.
*
******************************************************************************/
void redo_collision_list(struct volume* world, struct collision** shead,
struct collision** stail, struct collision** shead_exp, struct volume_molecule* m,
struct vector3* displacement, struct subvolume* sv) {
struct collision* st = *stail;
struct collision* sh = *shead_exp;
if (st != NULL) {
st->next = NULL;
if (sh != NULL) {
mem_put_list(sv->local_storage->coll, sh);
sh = NULL;
}
} else if (sh != NULL) {
mem_put_list(sv->local_storage->coll, sh);
sh = NULL;
*shead = NULL;
}
if ((m->properties->flags & (CAN_VOLVOL | CANT_INITIATE)) == CAN_VOLVOL) {
sh = expand_collision_list(world, m, displacement, sv, world->rx_radius_3d,
world->ny_parts, world->nz_parts, world->x_fineparts,
world->y_fineparts, world->z_fineparts, world->rx_hashsize,
world->reaction_hash);
if (st != NULL)
st->next = sh;
else {
if (*shead != NULL)
mcell_internal_error("Collision lists corrupted. While expanding "
"the collision lists, expected shead to be "
"NULL, but it wasn't.");
*shead = sh;
}
}
*stail = st;
*shead_exp = sh;
}
/******************************************************************************
*
* collide_and_react_with_vol_mol is a helper function used in diffuse_3D to
* handle collision of a diffusing molecule with a molecular target.
*
* Returns 1 if reaction does happen and 0 otherwise.
*
******************************************************************************/
static int collide_and_react_with_vol_mol(struct volume* world,
struct collision* smash, struct volume_molecule* m, struct collision**
tentative, struct vector3* displacement, struct vector3* loc_certain, double
t_steps, double r_rate_factor) {
struct abstract_molecule* am = (struct abstract_molecule *)smash->target;
double factor = exact_disk(
world, &(smash->loc), displacement, world->rx_radius_3d, m->subvol,
m, (struct volume_molecule *)am, world->use_expanded_list,
world->x_fineparts, world->y_fineparts, world->z_fineparts);
if (factor < 0) { /* Probably hit a wall, might have run out of memory */
return 0; /* Reaction blocked by a wall */
}
double scaling = factor * r_rate_factor;
struct rxn* rx = smash->intermediate;
if ((rx != NULL) && (rx->prob_t != NULL)) {
update_probs(world, rx, m->t);
}
struct species *spec = m->properties;
struct periodic_image *periodic_box = m->periodic_box;
int i = test_bimolecular(
rx, scaling, 0, am, (struct abstract_molecule *)m, world->rng);
if (i < RX_LEAST_VALID_PATHWAY) {
return 0;
}
if (loc_certain != NULL) {
// only for counting - handled correctly
// ASSERT_FOR_MCELL4(loc_certain->x == 0 && loc_certain->y == 0 && loc_certain->z == 0);
}
int j = outcome_bimolecular(world, rx, i, (struct abstract_molecule *)m, am,
0, 0, m->t + t_steps * smash->t, &(smash->loc), loc_certain);
if (j != RX_DESTROY) {
return 0;
} else {
/* Count the hits up until we were destroyed */
struct collision* ttv = *tentative;
for (; ttv != NULL && ttv->t <= smash->t; ttv = ttv->next) {
if (!(ttv->what & COLLIDE_WALL)) {
continue;
}
if (m->properties == NULL) {
continue;
}
if (!(m->properties->flags & ((struct wall *)ttv->target)->flags &
COUNT_SOME_MASK)) {
continue;
}
count_region_update(world, m, spec, m->id, periodic_box,
((struct wall *)ttv->target)->counting_regions,
((ttv->what & COLLIDE_MASK) == COLLIDE_FRONT) ? 1 : -1, 0, &(ttv->loc), ttv->t);
if (ttv == smash) {
break;
}
}
*tentative = ttv;
}
return 1;
}
/******************************************************************************
*
* collide_and_react_with_surf_mol is a helper function used in diffuse_3D to
* handle collision of a diffusing 3D molecule with a surface molecule
*
* Return values:
*
* -1 : nothing happened - continue on with next smash targets
* 0 : reaction happened and we still exist but are done with the current smash
* 1 : reaction happened and we are destroyed
* target
*
******************************************************************************/
int collide_and_react_with_surf_mol(struct volume* world, struct collision* smash,
struct volume_molecule* m, struct collision** tentative,
struct vector3** loc_certain, double t_steps, int mol_grid_flag,
int mol_grid_grid_flag, double r_rate_factor) {
ASSERT_FOR_MCELL4(mol_grid_flag == 1);
struct collision* ttv = *tentative;
struct vector3* loc = *loc_certain;
struct wall* w = (struct wall *)smash->target;
double t_confident = 0.0;
if (smash->next == NULL) {
t_confident = smash->t;
} else if (smash->next->t * (1.0 - EPS_C) > smash->t) {
t_confident = smash->t;
} else {
ASSERT_FOR_MCELL4(false);
t_confident = smash->t * (1.0 - EPS_C);
}
int k = -1;
if ((smash->what & COLLIDE_MASK) == COLLIDE_FRONT) {
k = 1;
}
int j = xyz2grid(&(smash->loc), w->grid);
struct surface_molecule_list *sm_list = w->grid->sm_list[j];
if (sm_list == NULL || sm_list->sm == NULL) {
return -1;
}
struct surface_molecule* sm = w->grid->sm_list[j]->sm;
if (m->index == j && m->previous_wall == w) {
m->index = -1; // Avoided rebinding, but next time it's OK
return -1;
}
int num_matching_rxns = 0;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
double scaling_coef[MAX_MATCHING_RXNS];
struct species* spec = m->properties;
struct periodic_image *periodic_box = m->periodic_box;
int ii = 0, jj = 0;
if (mol_grid_flag) {
if(sm->properties->flags & EXTERNAL_SPECIES){
num_matching_rxns = trigger_bimolecular_nfsim(world, (struct abstract_molecule *)m,
(struct abstract_molecule *)sm, k, sm->orient, matching_rxns);
}
else{
num_matching_rxns = trigger_bimolecular(
world->reaction_hash, world->rx_hashsize, spec->hashval,
sm->properties->hashval, (struct abstract_molecule *)m,
(struct abstract_molecule *)sm, k, sm->orient, matching_rxns);
}
if (num_matching_rxns > 0) {
if (world->notify->molecule_collision_report == NOTIFY_FULL) {
if (world->rxn_flags.vol_surf_reaction_flag)
world->vol_surf_colls++;
}
for (int l = 0; l < num_matching_rxns; l++) {
if (matching_rxns[l]->prob_t != NULL) {
ASSERT_FOR_MCELL4(false);
update_probs(world, matching_rxns[l], m->t);
}
scaling_coef[l] = r_rate_factor / w->grid->binding_factor;
}
if (num_matching_rxns == 1) {
ii = test_bimolecular(matching_rxns[0], scaling_coef[0], 0,
(struct abstract_molecule *)m, (struct abstract_molecule *)sm,
world->rng);
jj = 0;
} else {
ASSERT_FOR_MCELL4(false);
jj = test_many_bimolecular(matching_rxns, scaling_coef, 0,
num_matching_rxns, &(ii), world->rng, 0);
}
if ((jj > RX_NO_RX) && (ii >= RX_LEAST_VALID_PATHWAY)) {
/* Save m flags in case m gets collected in outcome_bimolecular */
short mflags = m->flags;
int l = outcome_bimolecular(world, matching_rxns[jj], ii,
(struct abstract_molecule *)m, (struct abstract_molecule *)sm,
k, sm->orient, m->t + t_steps * smash->t, &(smash->loc), loc);
if (l == RX_FLIP) {
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
int destroy_flag = 0;
count_tentative_collisions(
world, &ttv, smash, m, spec, t_confident, destroy_flag,
periodic_box, m->id);
}
*tentative = ttv;
*loc_certain = &(ttv->loc);
return 0; /* pass through */
} else if (l == RX_DESTROY) {
if ((mflags & COUNT_ME) != 0 && (spec->flags & COUNT_HITS) != 0) {
/* Count the hits up until we were destroyed */
int destroy_flag = 0;
count_tentative_collisions(
world, &ttv, smash, m, spec, t_confident, destroy_flag,
periodic_box, m->id);
}
*tentative = ttv;
return 1;
}
}
}
}
/* test for the trimolecular reactions of the type MOL_GRID_GRID */
if (mol_grid_grid_flag) {
struct surface_molecule *smp; /* Neighboring molecules */
struct tile_neighbor *tile_nbr_head = NULL, *curr;
int list_length = 0;
int n = 0; /* total number of possible reactions for a given
molecule with all its neighbors */
/* find neighbor molecules to react with */
find_neighbor_tiles(world, sm, sm->grid, sm->grid_index, 0, 1,
&tile_nbr_head, &list_length);
if (tile_nbr_head != NULL) {
const int num_nbrs = (int)list_length;
double local_prob_factor; /*local probability factor for the
reaction */
int max_size = num_nbrs * MAX_MATCHING_RXNS;
/* array of reaction objects with neighbor mols */
std::vector<struct rxn *> rxn_array(max_size);
std::vector<double> cf(max_size); /* Correction factors for area for those molecules */
std::vector<struct surface_molecule *> smol(max_size); /* points to neighbor molecules */
local_prob_factor = 3.0 / num_nbrs;
jj = RX_NO_RX;
ii = RX_LEAST_VALID_PATHWAY - 1;
for (int kk = 0; kk < max_size; kk++) {
smol[kk] = NULL;
rxn_array[kk] = NULL;
cf[kk] = 0;
}
/* step through the neighbors */
int ll = 0;
for (curr = tile_nbr_head; curr != NULL; curr = curr->next) {
sm_list = curr->grid->sm_list[curr->idx];
if (sm_list == NULL || sm_list->sm == NULL)
continue;
smp = curr->grid->sm_list[curr->idx]->sm;
/* check whether any of potential partners
are behind restrictive (REFLECTIVE/ABSORPTIVE) boundary */
if ((sm->properties->flags & CAN_REGION_BORDER) ||
(smp->properties->flags & CAN_REGION_BORDER)) {
if (sm->grid->surface != smp->grid->surface) {
/* INSIDE-OUT check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, sm, smp->grid->surface, smp)) {
continue;
}
/* OUTSIDE-IN check */
if (walls_belong_to_at_least_one_different_restricted_region(
world, sm->grid->surface, smp, smp->grid->surface, sm)) {
continue;
}
}
}
num_matching_rxns = trigger_trimolecular(world->reaction_hash,
world->rx_hashsize, spec->hashval, sm->properties->hashval,
smp->properties->hashval, spec, sm->properties, smp->properties,
k, sm->orient, smp->orient, matching_rxns);
if (num_matching_rxns > 0) {
if (world->notify->molecule_collision_report == NOTIFY_FULL &&
world->rxn_flags.vol_surf_surf_reaction_flag) {
world->vol_surf_surf_colls++;
}
for (j = 0; j < num_matching_rxns; j++) {
if (matching_rxns[j]->prob_t != NULL) {
update_probs(world, matching_rxns[j], m->t);
}
rxn_array[ll] = matching_rxns[j];
cf[ll] = r_rate_factor / (w->grid->binding_factor *
curr->grid->binding_factor);
smol[ll] = smp;
ll++;
}
n += num_matching_rxns;
}
}
delete_tile_neighbor_list(tile_nbr_head);
if (n == 1) {
ii = test_bimolecular(rxn_array[0], cf[0], local_prob_factor,
NULL, NULL, world->rng);
jj = 0;
} else if (n > 1) {
// previously "test_many_bimolecular_all_neighbors"
int all_neighbors_flag = 1;
jj = test_many_bimolecular(&rxn_array[0], &cf[0], local_prob_factor,
n, &(ii), world->rng, all_neighbors_flag);
}
if (n > max_size)
mcell_internal_error(
"The size of the reactions array is not sufficient.");
if ((n > 0) && (ii >= RX_LEAST_VALID_PATHWAY) && (jj > RX_NO_RX)) {
/* Save m flags in case it gets collected in outcome_trimolecular */
int mflags = m->flags;
int l = outcome_trimolecular(world, rxn_array[jj], ii,
(struct abstract_molecule *)m, (struct abstract_molecule *)sm,
(struct abstract_molecule *)smol[jj], k, sm->orient,
smol[jj]->orient, m->t + t_steps * smash->t, &smash->loc, &m->pos);
if (l == RX_FLIP) {
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
int destroy_flag = 0;
count_tentative_collisions(
world, &ttv, smash, m, spec, t_confident, destroy_flag,
periodic_box, m->id);
}
*loc_certain = &(ttv->loc);
*tentative = ttv;
return 0; /* pass through */
} else if (l == RX_DESTROY) {
if ((mflags & COUNT_ME) != 0 && (spec->flags & COUNT_HITS) != 0) {
/* Count the hits up until we were destroyed */
int destroy_flag = 0;
count_tentative_collisions(
world, &ttv, smash, m, spec, t_confident, destroy_flag,
periodic_box, m->id);
}
*tentative = ttv;
return 1;
}
}
}
}
return -1;
}
/******************************************************************************
*
* check_collisions_with_walls is a helper function used in diffuse_3D to handle
* collision of a diffusing molecule with a wall
*
* Return values:
*
* -1 : nothing happened - continue on with next smash targets
* 0 : reaction happened and we still exist but are done with the current smash
* target
* 1 : reaction happened and we are destroyed
*
******************************************************************************/
int collide_and_react_with_walls(struct volume* world, struct collision* smash,
struct volume_molecule* m, struct collision** tentative,
struct vector3** loc_certain, double t_steps, int inertness,
double r_rate_factor) {
struct collision *ttv = *tentative;
struct vector3 *loc = *loc_certain;
double t_confident = 0.0;
if (smash->next == NULL) {
t_confident = smash->t;
} else if (smash->next->t * (1.0 - EPS_C) > smash->t) {
t_confident = smash->t;
} else {
t_confident = smash->t * (1.0 - EPS_C);
}
int k = -1;
if ((smash->what & COLLIDE_MASK) == COLLIDE_FRONT) {
k = 1;
}
// check for reactions with walls
m->index = -1;
int num_matching_rxns = 0;
struct rxn* rx = NULL;
struct species* spec = m->properties;
struct wall* w = (struct wall *)smash->target;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
num_matching_rxns = trigger_intersect(world->reaction_hash,
world->rx_hashsize, world->all_mols, world->all_volume_mols,
world->all_surface_mols, spec->hashval, (struct abstract_molecule *)m, k, w,
matching_rxns, 1, 0, 0);
if (num_matching_rxns == 0) {
return -1;
}
int is_transp_flag = 0;
struct rxn *transp_rx = NULL;
for (int ii = 0; ii < num_matching_rxns; ii++) {
rx = matching_rxns[ii];
if (rx->n_pathways == RX_TRANSP) {
is_transp_flag = 1;
transp_rx = matching_rxns[ii];
break;
}
}
if ((!is_transp_flag) && (world->notify->molecule_collision_report == NOTIFY_FULL) &&
world->rxn_flags.vol_wall_reaction_flag) {
world->vol_wall_colls++;
}
struct periodic_image *periodic_box = m->periodic_box;
if (is_transp_flag) {
transp_rx->n_occurred++;
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
int destroy_flag = 0;
count_tentative_collisions(
world, tentative, smash, m, spec, smash->t, destroy_flag, periodic_box,
m->id);
// XXX: RX_FLIP case below should probably be handled this way too.
for (; ttv != NULL && ttv->t <= t_confident; ttv = ttv->next) {
*loc_certain = &(ttv->loc);
}
}
#ifdef DEBUG_TRANSPARENT_SURFACES
std::cout << "Crossed a transparent wall, side: " << ((wall*)smash->target)->side << "\n";
#endif
return 0; /* Ignore this wall and keep going */
} else if (inertness < inert_to_all) {
/* Collisions with the surfaces declared REFLECTIVE are treated similar to
* the default surfaces after this loop. */
for (int l = 0; l < num_matching_rxns; l++) {
if (matching_rxns[l]->prob_t != NULL) {
update_probs(world, matching_rxns[l], m->t);
}
}
int jj = 0;
int i = 0;
if (num_matching_rxns == 1) {
i = test_intersect(matching_rxns[0], r_rate_factor, world->rng);
jj = 0;
} else {
jj = test_many_intersect(matching_rxns, r_rate_factor,
num_matching_rxns, &(i), world->rng);
}
if ((i >= RX_LEAST_VALID_PATHWAY) && (jj > RX_NO_RX)) {
/* Save m flags in case it gets collected in outcome_intersect */
rx = matching_rxns[jj];
int mflags = m->flags;
int j = outcome_intersect(world, rx, i, w, (struct abstract_molecule *)m, k,
m->t + t_steps * smash->t, &(smash->loc), loc);
if (j == RX_FLIP) {
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* Count as far up as we can unambiguously */
int destroy_flag = 0;
count_tentative_collisions(
world, &ttv, smash, m, spec, t_confident, destroy_flag,
periodic_box, m->id);
}
*loc_certain = &(ttv->loc);
*tentative = ttv;
return 0; /* pass through */
} else if (j == RX_DESTROY) {
if ((mflags & COUNT_ME) != 0 && (spec->flags & COUNT_HITS) != 0) {
/* Count the hits up until we were destroyed */
int destroy_flag = 1;
count_tentative_collisions(
world, tentative, smash, m, spec, smash->t, destroy_flag,
periodic_box, m->id);
}
return 1;
}
}
}
return -1;
}
/******************************************************************************
*
* the reflect_or_periodic_bc helper function is used in diffuse_3D to handle
* either reflections or periodic boundary conditions for a diffusing molecule
* encountering a wall
*
* Return values:
*
* 0 : indicates that the molecule reflected off a wall
* 1 : indicates that the molecule hit a periodic box and was moved to a
* position in the neighboring image
*
******************************************************************************/
int reflect_or_periodic_bc(
struct volume* world, struct collision* smash,
struct vector3* displacement, struct volume_molecule** mol,
struct wall** reflectee, struct collision** tentative, double* t_steps) {
struct wall* w = (struct wall*)smash->target;
struct wall *reflect_w = w;
double reflect_t = smash->t;
struct volume_molecule* vm = *mol;
bool periodic_traditional = world->periodic_traditional;
ASSERT_FOR_MCELL4(!periodic_traditional);
register_hits(world, vm, tentative, &reflect_w, &reflect_t, displacement,
smash, t_steps);
struct vector3 orig_pos = {vm->pos.x, vm->pos.y, vm->pos.z};
(*reflectee) = reflect_w;
int k = -1;
if ((smash->what & COLLIDE_MASK) == COLLIDE_FRONT) {
k = 1;
}
bool periodic_x = w->parent_object->periodic_x && (k == -1);
bool periodic_y = w->parent_object->periodic_y && (k == -1);
bool periodic_z = w->parent_object->periodic_z && (k == -1);
// Lower left and upper right corners of the periodic box
double llx = 0.0;
double urx = 0.0;
double lly = 0.0;
double ury = 0.0;
double llz = 0.0;
double urz = 0.0;
// in the presence of periodic boundary conditions we retrieve the box size
if (periodic_x || periodic_y || periodic_z) {
struct geom_object* o = w->parent_object;
assert(o->object_type == BOX_OBJ);
struct polygon_object* p = (struct polygon_object*)(o->contents);
struct subdivided_box* sb = p->sb;
llx = sb->x[0];
urx = sb->x[1];
lly = sb->y[0];
ury = sb->y[1];
llz = sb->z[0];
urz = sb->z[1];
}
double reflectFactor = -2.0 * (displacement->x * reflect_w->normal.x +
displacement->y * reflect_w->normal.y + displacement->z *
reflect_w->normal.z);
int box_inc_x = 0;
int box_inc_y = 0;
int box_inc_z = 0;
double x_pos = 0;
double y_pos = 0;
double z_pos = 0;
// X direction: reflect or periodic BC
if (periodic_x) {
int x_inc = (vm->periodic_box->x % 2 == 0) ? 1 : -1;
if (!distinguishable(vm->pos.x, llx, EPS_C)) {
x_pos = urx - EPS_C;
box_inc_x = -x_inc;
} else if (!distinguishable(vm->pos.x, urx, EPS_C)) {
x_pos = llx + EPS_C;
box_inc_x = x_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && x_pos) {
vm->pos.x = x_pos;
}
}
// Set displacement for remainder of step length
//
// No PBCs or non-traditional PBCs
if ((!periodic_x) || (periodic_x && !periodic_traditional)) {
displacement->x = (displacement->x + reflectFactor * reflect_w->normal.x) *
(1.0 - reflect_t);
}
// Traditional PBCs
else {
displacement->x *= (1.0 - reflect_t);
}
// Y direction: reflect or periodic BC
if (periodic_y) {
int y_inc = (vm->periodic_box->y % 2 == 0) ? 1 : -1;
if (!distinguishable(vm->pos.y, lly, EPS_C)) {
y_pos = ury - EPS_C;
box_inc_y = -y_inc;
} else if (!distinguishable(vm->pos.y, ury, EPS_C)) {
y_pos = lly + EPS_C;
box_inc_y = y_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && y_pos) {
vm->pos.y = y_pos;
}
}
// Set displacement for remainder of step length
//
// No PBCs or non-traditional PBCs
if ((!periodic_y) || (periodic_y && !periodic_traditional)) {
displacement->y = (displacement->y + reflectFactor * reflect_w->normal.y) *
(1.0 - reflect_t);
}
// Traditional PBCs
else {
displacement->y *= (1.0 - reflect_t);
}
// Z direction: reflect or periodic BC
if (periodic_z) {
int z_inc = (vm->periodic_box->z % 2 == 0) ? 1 : -1;
if (!distinguishable(vm->pos.z, llz, EPS_C)) {
z_pos = urz - EPS_C;
box_inc_z = -z_inc;
} else if (!distinguishable(vm->pos.z, urz, EPS_C)) {
z_pos = llz + EPS_C;
box_inc_z = z_inc;
}
// Wrap molecule around to other side of box
if (periodic_traditional && z_pos) {
vm->pos.z = z_pos;
}
}
// Set displacement for remainder of step length
//
// No PBCs or non-traditional PBCs
if ((!periodic_z) || (periodic_z && !periodic_traditional)) {
displacement->z = (displacement->z + reflectFactor * reflect_w->normal.z) *
(1.0 - reflect_t);
}
// Traditional PBCs
else {
displacement->z *= (1.0 - reflect_t);
}
// if we changed our position by periodic BC in either x, y or z we need
// to check for migration to the proper subvolume.
if ((periodic_traditional) && (periodic_x || periodic_y || periodic_z)) {
(*reflectee) = NULL;
struct subvolume *nsv = find_subvolume(world, &vm->pos, NULL);
if (nsv == NULL) {
struct species* spec = vm->properties;
mcell_internal_error(
"A %s molecule escaped the periodic box at [%.2f, %.2f, %.2f]",
spec->sym->name, vm->pos.x * world->length_unit,
vm->pos.y * world->length_unit, vm->pos.z * world->length_unit);
} else {
// decrement counts of regions we are leaving
if (vm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(world, (struct abstract_molecule *)vm, NULL,
-1, &(orig_pos), NULL, reflect_t, NULL);
}
struct volume_molecule *new_m = migrate_volume_molecule(vm, nsv);
// increment counts of regions we are entering
if (new_m->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(world, (struct abstract_molecule *)new_m, NULL, 1,
&(new_m->pos), NULL, reflect_t, NULL);
}
*mol = new_m;
}
return 1;
}
if (!(periodic_traditional) && (box_inc_x || box_inc_y || box_inc_z)) {
(*reflectee) = NULL;
struct subvolume *nsv = find_subvolume(world, &vm->pos, NULL);
if (nsv == NULL) {
struct species* spec = vm->properties;
mcell_internal_error(
"A %s molecule escaped the periodic box at [%.2f, %.2f, %.2f]",
spec->sym->name, vm->pos.x * world->length_unit,
vm->pos.y * world->length_unit, vm->pos.z * world->length_unit);
} else {
// decrement counts of regions we are leaving
if (vm->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(world, (struct abstract_molecule *)vm, NULL,
-1, &(orig_pos), NULL, reflect_t,
vm->periodic_box);
}
struct volume_molecule *new_m = migrate_volume_molecule(vm, nsv);
vm->periodic_box->x += box_inc_x;
vm->periodic_box->y += box_inc_y;
vm->periodic_box->z += box_inc_z;
// increment counts of regions we are entering
if (new_m->properties->flags & (COUNT_CONTENTS | COUNT_ENCLOSED)) {
count_region_from_scratch(world, (struct abstract_molecule *)new_m,
NULL, 1, &(new_m->pos), NULL, reflect_t,
new_m->periodic_box);
}
*mol = new_m;
}
return 1;
}
*mol = vm;
return 0;
}
/******************************************************************************
*
* register_hits during 3D diffusion when colliding with a wall before
* reflecting or encountering periodic boundary conditions.
*
* Return values:
*
* No return value.
*
* By default, we will reflect from the point of collision on the last
* wall we hit; however, if there were one or more transparent walls we
* hit at the same time or slightly before, we did not count them as
* crossings, so we'd better be sure we don't cross them now. Due to
* round-off error, if we are counting, we need to make sure we don't
* go back through these "tentative" surfaces again. This involves
* finding the first "tentative" surface, and traveling back a tiny
* bit from that.
* If we're doing counting, register hits for all "tentative" surfaces,
* and update the point of reflection as explained above.
*
******************************************************************************/
void register_hits(struct volume* world, struct volume_molecule* m,
struct collision** tentative, struct wall** reflect_w, double* reflect_t,
struct vector3* displacement, struct collision* smash, double* t_steps) {
struct collision* ttv = *tentative;
struct species* spec = m->properties;
struct vector3 reflect_pt = smash->loc;
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* Find the first wall among the tentative collisions. */
while (ttv != NULL && ttv->t <= smash->t &&
!(ttv->what & COLLIDE_WALL)) {
ttv = ttv->next;
}
assert(ttv != NULL);
/* Grab out the relevant details. */
(*reflect_w) = ((struct wall *)ttv->target);
reflect_pt = ttv->loc;
(*reflect_t) = ttv->t * (1 - EPS_C);
/* Now, since we're reflecting before passing through these surfaces,
* register them as hits, but not as crossings. */
for (; ttv != NULL && ttv->t <= smash->t; ttv = ttv->next) {
if (!(ttv->what & COLLIDE_WALL)) {
continue;
}
if (!(spec->flags & ((struct wall *)ttv->target)->flags &
COUNT_SOME_MASK)) {
continue;
}
count_region_update(world, m, m->properties, m->id, m->periodic_box,
((struct wall *)ttv->target)->counting_regions,
((ttv->what & COLLIDE_MASK) == COLLIDE_FRONT) ? 1 : -1, 0, &(ttv->loc), ttv->t);
if (ttv == smash)
break;
}
}
*tentative = ttv;
/* Update molecule location to the point of reflection */
m->pos = reflect_pt;
m->t += *t_steps * (*reflect_t);
/* Reduce our remaining available time. */
*t_steps *= (1.0 - (*reflect_t));
}
/******************************************************************************
*
* the collide_and_react_with_subvol helper function is used in diffuse_3D to
* collisions of diffusing molecule with a subvolume
*
* Return values:
*
* No return value. We just have to ensure that we update the counts properly
* and then migrate the molecule to the proper subvolume.
*
******************************************************************************/
void collide_and_react_with_subvol(struct volume* world, struct collision *smash,
struct vector3* displacement, struct volume_molecule** mol,
struct collision** tentative, double* t_steps) {
struct collision* ttv = *tentative;
struct volume_molecule* m = *mol;
struct species* spec = m->properties;
if ((m->flags & COUNT_ME) != 0 && (spec->flags & COUNT_SOME_MASK) != 0) {
/* We're leaving the SV so we actually crossed everything we thought
* we might have crossed */
for (; ttv != NULL && ttv != smash; ttv = ttv->next) {
if (!(ttv->what & COLLIDE_WALL)) {
continue;
}
if (!(spec->flags & ((struct wall *)ttv->target)->flags & COUNT_SOME_MASK)) {
continue;
}
count_region_update(world, m, spec, m->id, m->periodic_box,
((struct wall *)ttv->target)->counting_regions,
((ttv->what & COLLIDE_MASK) == COLLIDE_FRONT) ? 1 : -1, 1, &(ttv->loc), ttv->t);
}
}
m->pos.x = smash->loc.x;
m->pos.y = smash->loc.y;
m->pos.z = smash->loc.z;
displacement->x *= (1.0 - smash->t);
displacement->y *= (1.0 - smash->t);
displacement->z *= (1.0 - smash->t);
m->t += (*t_steps) * smash->t;
(*t_steps) *= (1.0 - smash->t);
if (*t_steps < EPS_C) {
*t_steps = EPS_C;
}
struct subvolume *nsv = traverse_subvol(
m->subvol, smash->what - COLLIDE_SV_NX - COLLIDE_SUBVOL, world->ny_parts,
world->nz_parts);
if (nsv == NULL) {
mcell_internal_error(
"A %s molecule escaped the world at [%.2f, %.2f, %.2f]",
spec->sym->name, m->pos.x * world->length_unit,
m->pos.y * world->length_unit, m->pos.z * world->length_unit);
} else {
m = migrate_volume_molecule(m, nsv);
}
*mol = m;
*tentative = ttv;
}
/******************************************************************************
*
* the compute_displacement helper function is used in diffuse_3D to compute the
* displacement for the currently diffusing volume molecule
*
* Return values:
*
* this function does not return anything
*
******************************************************************************/
void compute_displacement(struct volume* world, struct collision* shead,
struct volume_molecule* m, struct vector3* displacement,
struct vector3* displacement2, double* rate_factor, double* r_rate_factor,
double* steps, double* t_steps, double max_time) {
struct species* spec = m->properties;
if (m->flags & ACT_CLAMPED) { /* Surface clamping and microscopic reversibility */
if (m->index <= DISSOCIATION_MAX) { /* Volume microscopic reversibility */
pick_release_displacement(displacement, displacement2, m->get_space_step(m),
world->r_step_release, world->d_step, world->radial_subdivisions,
world->directions_mask, world->num_directions, world->rx_radius_3d,
world->rng);
*t_steps = 0;
} else { /* Clamping or surface microscopic reversibility */
pick_clamped_displacement(displacement, m, world->r_step_surface,
world->rng, world->radial_subdivisions);
*t_steps = m->get_time_step(m);
m->previous_wall = NULL;
m->index = -1;
}
m->flags -= ACT_CLAMPED;
*r_rate_factor = *rate_factor = 1.0;
*steps = 1.0;
} else {
if (max_time > MULTISTEP_WORTHWHILE) {
*steps = safe_diffusion_step(m, shead, world->radial_subdivisions,
world->r_step, world->x_fineparts, world->y_fineparts, world->z_fineparts);
} else {
*steps = 1.0;
}
*t_steps = *steps * m->get_time_step(m);
if (*t_steps > max_time) {
*t_steps = max_time;
*steps = max_time / m->get_time_step(m);
#ifdef MCELL3_ROUND_TSTEPS
// makes the floating point difference between mcell3 and 4 little smaller,
// but not completely
if (*t_steps > 1.0 - EPS_C && *t_steps < 1.0 + EPS_C) {
*t_steps = 1.0;
}
if (*steps > 1.0 - EPS_C && *steps < 1.0 + EPS_C) {
*steps = 1.0;
}
#endif
}
if (*steps < EPS_C) {
*steps = EPS_C;
*t_steps = EPS_C * m->get_time_step(m);
}
if (*steps == 1.0) {
pick_displacement(displacement, m->get_space_step(m), world->rng);
*r_rate_factor = *rate_factor = 1.0;
} else {
*rate_factor = sqrt(*steps);
*r_rate_factor = 1.0 / *rate_factor;
pick_displacement(displacement, *rate_factor * m->get_space_step(m), world->rng);
}
}
if (spec->flags & SET_MAX_STEP_LENGTH) {
double disp_length = vect_length(displacement);
if (disp_length > spec->max_step_length) {
/* rescale displacement to the level of MAXIMUM_STEP_LENGTH */
displacement->x *= (spec->max_step_length / disp_length);
displacement->y *= (spec->max_step_length / disp_length);
displacement->z *= (spec->max_step_length / disp_length);
}
}
world->diffusion_number++;
world->diffusion_cumtime += *steps;
}
/******************************************************************************
*
* the determine_mol_mol_reactions helper function is used in diffuse_3D to
* compute all possible molecule molecule reactions between the diffusing
* molecule m and all other volume molecules in the subvolume.
*
* Return values:
*
* this function does not return anything
*
******************************************************************************/
void determine_mol_mol_reactions(struct volume* world, struct volume_molecule* m,
struct collision** shead, struct collision** stail, int inertness) {
struct subvolume* sv = m->subvol;
struct rxn *matching_rxns[MAX_MATCHING_RXNS];
int num_matching_rxns = 0;
struct species* spec = m->properties;
struct per_species_list *psl_next, *psl, **psl_head = &sv->species_head;
for (psl = sv->species_head; psl != NULL; psl = psl_next) {
psl_next = psl->next;
if (psl->properties == NULL) {
psl_head = &psl->next;
continue;
}
/* Garbage collection of empty per-species lists */
if (psl->head == NULL) {
*psl_head = psl->next;
ht_remove(&sv->mol_by_species, psl);
mem_put(sv->local_storage->pslv, psl);
continue;
} else
psl_head = &psl->next;
//is this an nfsim external species. if so query whether the 2 reactants can react together
if(m->properties->flags & EXTERNAL_SPECIES){
if(!trigger_bimolecular_preliminary_nfsim((struct abstract_molecule *)m,
(struct abstract_molecule *)psl->head)){
continue;
}
}
else{
/* no possible reactions. skip it. */
if (!trigger_bimolecular_preliminary(world->reaction_hash, world->rx_hashsize,
m->properties->hashval, psl->properties->hashval, m->properties, psl->properties)) {
continue;
}
}
for (struct volume_molecule* mp = psl->head; mp != NULL; mp = mp->next_v) {
if (mp == m) {
continue;
}
if (inertness == inert_to_mol && m->index == mp->index) {
continue;
}
// count only in the relevant periodic box
if (!periodic_boxes_are_identical(m->periodic_box, mp->periodic_box)) {
continue;
}
if(m->properties->flags & EXTERNAL_SPECIES){
num_matching_rxns = trigger_bimolecular_nfsim(world, (struct abstract_molecule *)m,
(struct abstract_molecule *)mp,0, 0, matching_rxns);
}
else{
num_matching_rxns = trigger_bimolecular(world->reaction_hash,
world->rx_hashsize, spec->hashval, psl->properties->hashval,
(struct abstract_molecule *)m, (struct abstract_molecule *)mp, 0, 0,
matching_rxns);
}
if (num_matching_rxns > 0) {
for (int i = 0; i < num_matching_rxns; i++) {
struct collision* smash =
(struct collision *)CHECKED_MEM_GET(sv->local_storage->coll,
"collision data");
smash->target = (void *)mp;
smash->what = COLLIDE_VOL;
smash->intermediate = matching_rxns[i];
smash->next = *shead;
*shead = smash;
if (*stail == NULL)
*stail = *shead;
}
}
}
}
}
/******************************************************************************
*
* the set_inertness_and_maxtime helper function is used in diffuse_3D to
* set the maxtime used for diffusion as well as the inertness for clamped
* molecules.
*
* Return values:
*
* this function does not return anything
*
******************************************************************************/
void set_inertness_and_maxtime(
struct volume* world, struct volume_molecule* m, double* max_time,
int* inertness) {
struct species* spec = m->properties;
if (world->volume_reversibility || world->surface_reversibility) {
if (world->volume_reversibility &&
m->index <= DISSOCIATION_MAX) { /* Only set if volume_reversibility is */
if ((m->flags & ACT_CLAMPED) != 0) {
*inertness = inert_to_all;
} else {
m->index = -1;
}
} else if (!world->surface_reversibility) {
if (m->flags & ACT_CLAMPED) { /* Pretend we were already moving */
m->birthday -= 5 * m->get_time_step(m); /* Pretend to be old */
}
}
} else {
if (m->flags & ACT_CLAMPED) { /* Pretend we were already moving */
m->birthday -= 5 * m->get_time_step(m); /* Pretend to be old */
} else if ((m->flags & MATURE_MOLECULE) == 0) {
#ifndef MCELL3_MOLECULE_MOVES_WITH_MAXIMUM_TIMESTEP
/* Newly created particles that have long time steps gradually increase */
/* their timestep to the full value */
if (m->get_time_step(m) > 1.0) {
/* Birthday is in seconds */
double f = 1.0 + 0.2 * (m->t - m->birthday / world->time_unit);
if (f < 1 - EPS_C)
mcell_internal_error("A %s molecule is scheduled to move before it "
"was born [birthday=%.15g, t=%.15g]",
spec->sym->name, m->birthday,
m->t * world->time_unit);
if (*max_time > f) {
*max_time = f;
}
if (f > m->subvol->local_storage->max_timestep) {
m->flags |= MATURE_MOLECULE;
}
}
#else
m->flags |= MATURE_MOLECULE;
#endif // MCELL3_MOLECULE_MOVES_WITH_MAXIMUM_TIMESTEP
}
}
}
/*******************************************************************************
*
* count_tentative_collisions is a helper function counting hits of a diffusing
* volume molecules with time-ordered collision targets along a ray up to time
* t_confident.
*
******************************************************************************/
void count_tentative_collisions(
struct volume *world, struct collision **tc, struct collision *smash, struct volume_molecule* m,
struct species *spec, double t_confident, int destroy_flag,
struct periodic_image *box, u_long id) {
int crossed_flag = 1;
if (destroy_flag == 1) {
// If we are destroyed, then we haven't crossed.
crossed_flag = 0;
}
struct collision *ttv = *tc;
for (; ttv != NULL && ttv->t <= t_confident; ttv = ttv->next) {
if (!(ttv->what & COLLIDE_WALL)) {
continue;
}
if (!(spec->flags & ((struct wall *)ttv->target)->flags & COUNT_SOME_MASK)) {
continue;
}
count_region_update(
world, m, spec, id, box, ((struct wall *)ttv->target)->counting_regions,
((ttv->what & COLLIDE_MASK) == COLLIDE_FRONT) ? 1 : -1, crossed_flag,
&(ttv->loc), ttv->t);
if ((destroy_flag) && (ttv == smash)) {
break;
}
}
*tc = ttv;
}
/*************************************************************************
periodicbox_in_surfmol_list:
Is the periodic box of one surface molecule (e.g. [0,0,0]) the same as any of
the periodic boxes in a surface molecule list?
In: periodic_box: the periodic box of a surface molecule
sml: a list of surface molecules, each belonging to their own PB
Out: true if the PB appears in the SM list, false otherwise.
*************************************************************************/
bool periodicbox_in_surfmol_list(
struct periodic_image *periodic_box,
struct surface_molecule_list *sml) {
for (struct surface_molecule_list *sml_curr = sml;
sml_curr != NULL;
sml_curr = sml_curr->next) {
struct surface_molecule *sm = sml_curr->sm;
if (sm && periodic_boxes_are_identical(periodic_box, sm->periodic_box)) {
return true;
}
}
return false;
}
| C |
3D | mcellteam/mcell | src/nfsim_func.c | .c | 5,611 | 160 | #include "nfsim_func.h"
#include "map_c.h"
static map_t graph_reaction_map = NULL;
void initialize_rxn_diffusion_functions(struct rxn *mol_ptr);
double get_standard_diffusion(void *self);
double get_nfsim_diffusion(void *self);
double get_standard_space_step(void *self);
double get_nfsim_space_step(void *self);
double get_standard_time_step(void *self);
double get_nfsim_time_step(void *self);
double rxn_get_nfsim_diffusion(struct rxn *, int);
double rxn_get_standard_diffusion(struct rxn *, int);
double rxn_get_nfsim_space_step(struct rxn *, int);
double rxn_get_standard_time_step(struct rxn *, int);
double rxn_get_nfsim_time_step(struct rxn *, int);
double rxn_get_standard_space_step(struct rxn *, int);
void initialize_diffusion_function(struct abstract_molecule *mol_ptr) {
// if nfsim provides spatial parameters...
if (mol_ptr->properties->flags & EXTERNAL_SPECIES &&
mol_ptr->graph_data->graph_diffusion != -1.0) {
mol_ptr->get_diffusion = &get_nfsim_diffusion;
mol_ptr->get_space_step = &get_nfsim_space_step;
mol_ptr->get_time_step = &get_nfsim_time_step;
} else {
mol_ptr->get_diffusion = &get_standard_diffusion;
mol_ptr->get_space_step = &get_standard_space_step;
mol_ptr->get_time_step = &get_standard_time_step;
}
if (mol_ptr->properties->flags & EXTERNAL_SPECIES &&
mol_ptr->graph_data->flags >= 0) {
mol_ptr->get_flags = &get_nfsim_flags;
} else {
mol_ptr->get_flags = &get_standard_flags;
}
}
void initialize_rxn_diffusion_functions(struct rxn *mol_ptr) {
if (mol_ptr->players[0]->flags & EXTERNAL_SPECIES) {
mol_ptr->get_reactant_diffusion = rxn_get_nfsim_diffusion;
mol_ptr->get_reactant_space_step = rxn_get_nfsim_space_step;
mol_ptr->get_reactant_time_step = rxn_get_nfsim_time_step;
} else {
mol_ptr->get_reactant_diffusion = rxn_get_standard_diffusion;
mol_ptr->get_reactant_space_step = rxn_get_standard_space_step;
mol_ptr->get_reactant_time_step = rxn_get_standard_time_step;
}
}
u_int get_standard_flags(void *mol_ptr) {
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
return am->properties->flags;
}
u_int get_nfsim_flags(void *mol_ptr) {
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
if (am->graph_data->flags < 0)
return get_standard_flags(am);
return (unsigned int)am->graph_data->flags;
}
double get_standard_diffusion(void *mol_ptr) {
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
return am->properties->D;
}
double get_nfsim_diffusion(void *mol_ptr) {
// nfsim returns diffusion -1 when the user didnt define any diffusion
// functions
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
if (am->graph_data->graph_diffusion > 0) {
return am->graph_data->graph_diffusion;
}
return get_standard_diffusion(am);
}
double get_standard_space_step(void *mol_ptr) {
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
return am->properties->space_step;
}
double get_nfsim_space_step(void *mol_ptr) {
// nfsim returns diffusion -1 when the user didnt define any diffusion
// functions
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
if (am->graph_data->graph_diffusion >= 0)
return am->graph_data->space_step;
return get_standard_space_step(am);
}
double get_standard_time_step(void *mol_ptr) {
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
return am->properties->time_step;
}
double get_nfsim_time_step(void *mol_ptr) {
// nfsim returns diffusion -1 when the user didnt define any diffusion
// functions
struct abstract_molecule *am = (struct abstract_molecule *)mol_ptr;
if (am->graph_data->graph_diffusion >= 0)
return am->graph_data->time_step;
return get_standard_time_step(am);
}
double rxn_get_standard_diffusion(struct rxn *mol_ptr, int index) {
return mol_ptr->players[index]->D;
}
double rxn_get_nfsim_diffusion(struct rxn *mol_ptr, int index) {
if (mol_ptr->reactant_graph_data &&
mol_ptr->reactant_graph_data[index]->graph_diffusion >= 0) {
return mol_ptr->reactant_graph_data[index]->graph_diffusion;
}
return rxn_get_standard_diffusion(mol_ptr, index);
}
double rxn_get_standard_time_step(struct rxn *mol_ptr, int index) {
return mol_ptr->players[index]->time_step;
}
double rxn_get_nfsim_time_step(struct rxn *mol_ptr, int index) {
if (mol_ptr->reactant_graph_data &&
mol_ptr->reactant_graph_data[index]->graph_diffusion >= 0) {
return mol_ptr->reactant_graph_data[index]->time_step;
}
return rxn_get_standard_time_step(mol_ptr, index);
}
double rxn_get_standard_space_step(struct rxn *mol_ptr, int index) {
return mol_ptr->players[index]->space_step;
}
double rxn_get_nfsim_space_step(struct rxn *mol_ptr, int index) {
if (mol_ptr->reactant_graph_data &&
mol_ptr->reactant_graph_data[index]->graph_diffusion >= 0) {
return mol_ptr->reactant_graph_data[index]->space_step;
}
return rxn_get_standard_space_step(mol_ptr, index);
}
void initialize_graph_hashmap() { graph_reaction_map = hashmap_new(); }
int get_graph_data(unsigned long graph_pattern_hash,
struct graph_data **graph_data) {
return hashmap_get_nohash(graph_reaction_map, graph_pattern_hash,
graph_pattern_hash, (void **)(graph_data));
}
int store_graph_data(unsigned long graph_pattern_hash,
struct graph_data *graph_data) {
return hashmap_put_nohash(graph_reaction_map, graph_pattern_hash,
graph_pattern_hash, graph_data);
}
| C |
3D | mcellteam/mcell | src/mcell_objects.h | .h | 5,194 | 148 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_init.h"
#include "mcell_structs.h"
struct object_creation {
struct name_list *object_name_list;
struct name_list *object_name_list_end;
struct geom_object *current_object;
};
#include "dyngeom_parse_extras.h"
struct poly_object {
const char *obj_name;
struct vertex_list *vertices;
int num_vert;
struct element_connection_list *connections;
int num_conn;
};
struct poly_object_list {
const char *obj_name;
struct vertex_list *vertices;
int num_vert;
struct element_connection_list *connections;
int num_conn;
struct element_list *surf_reg_faces;
const char *reg_name;
struct poly_object_list *next;
};
/* object creation */
MCELL_STATUS mcell_create_instance_object(MCELL_STATE *state, const char *name,
struct geom_object **new_object);
MCELL_STATUS mcell_create_periodic_box(
struct volume *state,
const char *box_name,
struct vector3 *llf,
struct vector3 *urb);
MCELL_STATUS mcell_create_poly_object(MCELL_STATE *state, struct geom_object *parent,
struct poly_object *poly_obj,
struct geom_object **new_object);
struct polygon_object *
new_polygon_list(MCELL_STATE *state, struct geom_object *obj_ptr, int n_vertices,
struct vertex_list *vertices, int n_connections,
struct element_connection_list *connections);
struct geom_object *make_new_object(
struct dyngeom_parse_vars *dg_parse,
struct sym_table_head *obj_sym_table,
const char *obj_name,
int *error_code);
char *push_object_name(struct object_creation *obj_creation, char *name);
void pop_object_name(struct object_creation *obj_creation);
/* helper functions for creating and deleting vertex and
* element_connection lists */
struct vertex_list *mcell_add_to_vertex_list(double x, double y, double z,
struct vertex_list *vertices);
void free_vertex_list(struct vertex_list *vert_list);
struct element_connection_list *
mcell_add_to_connection_list(int v1, int v2, int v3,
struct element_connection_list *elements);
void free_connection_list(struct element_connection_list *elem_conn_list);
int mcell_set_region_elements(struct region *rgn, struct element_list *elements,
int normalize_now);
struct element_list *mcell_add_to_region_list(struct element_list *elements,
u_int region_idx);
/* Adds children to a meta-object, aggregating counts of walls and vertices
* from the children into the specified parent. The children should already
* have their parent pointers set. */
void add_child_objects(struct geom_object *parent, struct geom_object *child_head,
struct geom_object *child_tail);
int mcell_check_for_region(char *region_name, struct geom_object *obj_ptr);
/* create regions */
struct region *mcell_create_region(MCELL_STATE *state, struct geom_object *objp,
const char *name);
struct region *make_new_region(
struct dyngeom_parse_vars *dg_parse,
MCELL_STATE *state,
const char *obj_name,
const char *region_last_name);
/* Clean up the regions on an object, eliminating any removed walls. */
void remove_gaps_from_regions(struct geom_object *obj_ptr);
/* lower level helper functions */
int check_degenerate_polygon_list(struct geom_object *obj_ptr);
struct geom_object *common_ancestor(struct geom_object *a, struct geom_object *b);
struct polygon_object *allocate_polygon_object(char const *desc);
struct element_list *new_element_list(unsigned int begin, unsigned int end);
int normalize_elements(struct region *reg, int existing);
int count_cuboid_elements(struct subdivided_box *sb);
int cuboid_patch_to_bits(struct subdivided_box *subd_box, struct vector3 *v1,
struct vector3 *v2, struct bit_array *bit_arr);
int check_patch(struct subdivided_box *b, struct vector3 *p1,
struct vector3 *p2, double egd);
struct sym_entry *mcell_get_obj_sym(struct geom_object *obj);
struct sym_entry *mcell_get_reg_sym(struct region *reg);
struct sym_entry * mcell_get_all_mol_sym(MCELL_STATE *state);
struct sym_entry * mcell_get_all_volume_mol_sym(MCELL_STATE *state);
struct sym_entry * mcell_get_all_surface_mol_sym(MCELL_STATE *state);
struct poly_object_list* mcell_add_to_poly_obj_list(
struct poly_object_list* poly_obj_list,
char *obj_name,
struct vertex_list *vertices,
int num_vert,
struct element_connection_list *connections,
int num_conn,
struct element_list *surf_reg_faces,
char *reg_name);
| Unknown |
3D | mcellteam/mcell | src/libmcell_test.c | .c | 11,093 | 260 | #include <stdio.h>
#include <stdlib.h>
#include "mcell_structs.h"
#include "mcell_misc.h"
#include "mcell_objects.h"
#include "mcell_react_out.h"
#include "mcell_reactions.h"
#include "mcell_release.h"
#include "mcell_species.h"
#include "mcell_viz.h"
#include "mcell_surfclass.h"
#include "mcell_run.h"
#define CHECKED_CALL_EXIT(function, error_message) \
{ \
if (function) { \
mcell_print(error_message); \
exit(1); \
} \
}
int main(void) {
struct volume *state = mcell_create();
CHECKED_CALL_EXIT(
mcell_init_state(state),
"An error occured during set up of the initial simulation state");
/* set timestep and number of iterations */
CHECKED_CALL_EXIT(mcell_set_time_step(state, 1e-6), "Failed to set timestep");
CHECKED_CALL_EXIT(mcell_set_iterations(state, 1000),
"Failed to set iterations");
/* create range for partitions */
struct num_expr_list_head list = { NULL, NULL, 0, 1 };
mcell_generate_range(&list, -0.5, 0.5, 0.05);
list.shared = 1;
/* set partitions */
CHECKED_CALL_EXIT(mcell_set_partition(state, X_PARTS, &list),
"Failed to set X partition");
CHECKED_CALL_EXIT(mcell_set_partition(state, Y_PARTS, &list),
"Failed to set Y partition");
CHECKED_CALL_EXIT(mcell_set_partition(state, Z_PARTS, &list),
"Failed to set Z partition");
/* create species */
struct mcell_species_spec molA = { "A", 1e-6, 1, 0.0, 0, 0.0, 0.0 };
mcell_symbol *molA_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molA, &molA_ptr),
"Failed to create species A");
struct mcell_species_spec molB = { "B", 1e-5, 0, 0.0, 0, 0.0, 0.0 };
mcell_symbol *molB_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molB, &molB_ptr),
"Failed to create species B");
struct mcell_species_spec molC = { "C", 2e-5, 0, 0.0, 0, 0.0, 0.0 };
mcell_symbol *molC_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molC, &molC_ptr),
"Failed to create species C");
struct mcell_species_spec molD = { "D", 1e-6, 1, 0.0, 0, 0.0, 0.0 };
mcell_symbol *molD_ptr;
CHECKED_CALL_EXIT(mcell_create_species(state, &molD, &molD_ptr),
"Failed to create species D");
/* create reactions */
struct mcell_species *reactants =
mcell_add_to_species_list(molA_ptr, true, 1, NULL);
reactants = mcell_add_to_species_list(molB_ptr, true, -1, reactants);
struct mcell_species *products =
mcell_add_to_species_list(molC_ptr, true, -1, NULL);
struct mcell_species *surfs =
mcell_add_to_species_list(NULL, false, 0, NULL);
struct reaction_arrow arrow = { REGULAR_ARROW, { NULL, NULL, 0, 0 } };
struct reaction_rates rates =
mcell_create_reaction_rates(RATE_CONSTANT, 1e7, RATE_UNSET, 0.0);
if (mcell_add_reaction(state->notify, &state->r_step_release,
state->rxn_sym_table, state->radial_subdivisions,
state->vacancy_search_dist2, reactants, &arrow, surfs,
products, NULL, &rates, NULL, NULL) == MCELL_FAIL) {
mcell_print("error ");
exit(1);
}
mcell_delete_species_list(reactants);
mcell_delete_species_list(products);
mcell_delete_species_list(surfs);
// create surface class
mcell_symbol *sc_ptr;
CHECKED_CALL_EXIT(mcell_create_surf_class(state, "SC_test", &sc_ptr),
"Failed to create surface class SC_test");
// create releases using a surface class (i.e. not a release object)
// mdl equivalent: MOLECULE_DENSITY {A' = 1000}
struct mcell_species *A =
mcell_add_to_species_list(molA_ptr, true, 1, NULL);
struct sm_dat *smd = mcell_add_mol_release_to_surf_class(
state, sc_ptr, A, 1000, 0, NULL);
// mdl equivalent: MOLECULE_NUMBER {D, = 1000}
struct mcell_species *D =
mcell_add_to_species_list(molD_ptr, true, -1, NULL);
mcell_add_mol_release_to_surf_class(state, sc_ptr, D, 1000, 1, smd);
// mdl equivalent: ABSORPTIVE = D
CHECKED_CALL_EXIT(
mcell_add_surf_class_properties(state, SINK, sc_ptr, molD_ptr, 0),
"Failed to add surface class property");
// mdl equivalent: REFLECTIVE = D
/*CHECKED_CALL_EXIT(*/
/* mcell_add_surf_class_properties(state, RFLCT, sc_ptr, molD_ptr, 0),*/
/* "Failed to add surface class property");*/
mcell_delete_species_list(A);
mcell_delete_species_list(D);
/*****************************************************************************
* create world meta object
*****************************************************************************/
struct geom_object *world_object = NULL;
CHECKED_CALL_EXIT(mcell_create_instance_object(state, "world", &world_object),
"could not create meta object");
/****************************************************************************
* begin code for creating a polygon mesh
****************************************************************************/
struct vertex_list *verts = mcell_add_to_vertex_list(0.5, 0.5, -0.5, NULL);
verts = mcell_add_to_vertex_list(0.5, -0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, -0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, 0.5, -0.5, verts);
verts = mcell_add_to_vertex_list(0.5, 0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(0.5, -0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, -0.5, 0.5, verts);
verts = mcell_add_to_vertex_list(-0.5, 0.5, 0.5, verts);
struct element_connection_list *elems =
mcell_add_to_connection_list(1, 2, 3, NULL);
elems = mcell_add_to_connection_list(7, 6, 5, elems);
elems = mcell_add_to_connection_list(0, 4, 5, elems);
elems = mcell_add_to_connection_list(1, 5, 6, elems);
elems = mcell_add_to_connection_list(6, 7, 3, elems);
elems = mcell_add_to_connection_list(0, 3, 7, elems);
elems = mcell_add_to_connection_list(0, 1, 3, elems);
elems = mcell_add_to_connection_list(4, 7, 5, elems);
elems = mcell_add_to_connection_list(1, 0, 5, elems);
elems = mcell_add_to_connection_list(2, 1, 6, elems);
elems = mcell_add_to_connection_list(2, 6, 3, elems);
elems = mcell_add_to_connection_list(4, 0, 7, elems);
struct poly_object polygon = { "aBox", verts, 8, elems, 12 };
struct geom_object *new_mesh = NULL;
CHECKED_CALL_EXIT(
mcell_create_poly_object(state, world_object, &polygon, &new_mesh),
"could not create polygon_object")
/****************************************************************************
* begin code for creating a region
****************************************************************************/
struct region *test_region = mcell_create_region(state, new_mesh, "reg");
struct element_list *region_list = mcell_add_to_region_list(NULL, 0);
region_list = mcell_add_to_region_list(region_list, 1);
CHECKED_CALL_EXIT(mcell_set_region_elements(test_region, region_list, 1),
"could not finish creating region");
/****************************************************************************
* Assign surface class to "test_region"
****************************************************************************/
mcell_assign_surf_class_to_region(sc_ptr, test_region);
/***************************************************************************
* begin code for creating release sites
***************************************************************************/
/*struct object *A_releaser = NULL;*/
/*struct mcell_species *A =*/
/* mcell_add_to_species_list(molA_ptr, true, 1, 0, NULL);*/
/*CHECKED_CALL_EXIT(mcell_create_region_release(state, world_object, new_mesh,*/
/* "A_releaser", "reg", A, 1000, 1,*/
/* NULL, &A_releaser),*/
/* "could not create A_releaser");*/
/*mcell_delete_species_list(A);*/
struct vector3 position = { 0.0, 0.0, 0.0 };
struct vector3 diameter = { 0.00999, 0.00999, 0.00999 };
struct geom_object *B_releaser = NULL;
struct mcell_species *B =
mcell_add_to_species_list(molB_ptr, false, 0, NULL);
CHECKED_CALL_EXIT(mcell_create_geometrical_release_site(
state, world_object, "B_releaser", SHAPE_SPHERICAL,
&position, &diameter, B, 5000, 0, 1, NULL, &B_releaser),
"could not create B_releaser");
mcell_delete_species_list(B);
/***************************************************************************
* begin code for creating count statements
***************************************************************************/
// struct sym_entry *where = NULL; // we count in the world
struct sym_entry *where = new_mesh->sym;
// byte report_flags = REPORT_WORLD;
// report_flags |= REPORT_CONTENTS;
byte report_flags = REPORT_CONTENTS;
struct output_column_list count_list;
CHECKED_CALL_EXIT(mcell_create_count(state, molA_ptr, ORIENT_NOT_SET, where,
report_flags, NULL, &count_list),
"Failed to create COUNT expression");
struct output_set *os =
mcell_create_new_output_set(NULL, 0, count_list.column_head,
FILE_SUBSTITUTE, "react_data/foobar.dat");
struct output_times_inlist outTimes;
outTimes.type = OUTPUT_BY_STEP;
outTimes.step = 1e-5;
struct output_set_list output;
output.set_head = os;
output.set_tail = os;
CHECKED_CALL_EXIT(
mcell_add_reaction_output_block(state, &output, 10000, &outTimes),
"Error setting up the reaction output block");
struct mcell_species *mol_viz_list =
mcell_add_to_species_list(molA_ptr, false, 0, NULL);
mol_viz_list = mcell_add_to_species_list(molB_ptr, false, 0, mol_viz_list);
mol_viz_list = mcell_add_to_species_list(molC_ptr, false, 0, mol_viz_list);
mol_viz_list = mcell_add_to_species_list(molD_ptr, false, 0, mol_viz_list);
CHECKED_CALL_EXIT(mcell_create_viz_output(state, "./viz_data/test",
mol_viz_list, 0, 1000, 2, false),
"Error setting up the viz output block");
mcell_delete_species_list(mol_viz_list);
CHECKED_CALL_EXIT(mcell_init_simulation(state),
"An error occured during simulation creation.");
CHECKED_CALL_EXIT(
mcell_init_read_checkpoint(state),
"An error occured during initialization and reading of checkpoint.");
CHECKED_CALL_EXIT(mcell_init_output(state),
"An error occured during setting up of output.");
CHECKED_CALL_EXIT(mcell_run_simulation(state),
"Error running mcell simulation.");
mcell_print_stats();
return 0;
}
| C |
3D | mcellteam/mcell | src/mcell_objects.c | .c | 47,870 | 1,447 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <assert.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "config.h"
#include "logging.h"
#include "sym_table.h"
#include "mcell_species.h"
#include "mcell_release.h"
#include "mcell_init.h"
#include "mcell_objects.h"
#include "dyngeom_parse_extras.h"
#include "mem_util.h"
/* static helper functions */
static int is_region_degenerate(struct region *reg_ptr);
/*************************************************************************
mcell_create_instance_object:
Create a new instance object.
In: state: the simulation state
object pointer to store created meta object
Out: 0 on success; any other integer value is a failure.
A mesh is created.
*************************************************************************/
MCELL_STATUS
mcell_create_instance_object(MCELL_STATE *state, const char *name,
struct geom_object **new_obj) {
// Create the symbol, if it doesn't exist yet.
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
state->dg_parse, // Need to test that dg_parse actually works here
state->obj_sym_table,
name,
&error_code);
/*struct object *obj_ptr = make_new_object(state, name, &error_code);*/
if (obj_ptr == NULL) {
return MCELL_FAIL;
}
obj_ptr->last_name = (char*)name;
obj_ptr->object_type = META_OBJ;
// instantiate object
obj_ptr->parent = state->root_instance;
add_child_objects(state->root_instance, obj_ptr, obj_ptr);
*new_obj = obj_ptr;
return MCELL_SUCCESS;
}
MCELL_STATUS mcell_create_periodic_box(
struct volume *state,
const char *box_name,
struct vector3 *llf,
struct vector3 *urb) {
double sf = 100.0; // scaling factor
struct vector3 llf_sm = {llf->x/sf,
llf->y/sf,
llf->z/sf,
};
struct vector3 urb_sm = {urb->x/sf,
urb->y/sf,
urb->z/sf,
};
struct vertex_list *verts = mcell_add_to_vertex_list(
urb_sm.x, urb_sm.y, llf_sm.z, NULL);
verts = mcell_add_to_vertex_list(urb_sm.x, llf_sm.y, llf_sm.z, verts);
verts = mcell_add_to_vertex_list(llf_sm.x, llf_sm.y, llf_sm.z, verts);
verts = mcell_add_to_vertex_list(llf_sm.x, urb_sm.y, llf_sm.z, verts);
verts = mcell_add_to_vertex_list(urb_sm.x, urb_sm.y, urb_sm.z, verts);
verts = mcell_add_to_vertex_list(urb_sm.x, llf_sm.y, urb_sm.z, verts);
verts = mcell_add_to_vertex_list(llf_sm.x, llf_sm.y, urb_sm.z, verts);
verts = mcell_add_to_vertex_list(llf_sm.x, urb_sm.y, urb_sm.z, verts);
struct element_connection_list *elems =
mcell_add_to_connection_list(1, 2, 3, NULL);
elems = mcell_add_to_connection_list(7, 6, 5, elems);
elems = mcell_add_to_connection_list(0, 4, 5, elems);
elems = mcell_add_to_connection_list(1, 5, 6, elems);
elems = mcell_add_to_connection_list(6, 7, 3, elems);
elems = mcell_add_to_connection_list(0, 3, 7, elems);
elems = mcell_add_to_connection_list(0, 1, 3, elems);
elems = mcell_add_to_connection_list(4, 7, 5, elems);
elems = mcell_add_to_connection_list(1, 0, 5, elems);
elems = mcell_add_to_connection_list(2, 1, 6, elems);
elems = mcell_add_to_connection_list(2, 6, 3, elems);
elems = mcell_add_to_connection_list(4, 0, 7, elems);
struct subdivided_box *b = CHECKED_MALLOC_STRUCT(
struct subdivided_box, "subdivided box");
if (b == NULL) {
free(verts);
free(elems);
return MCELL_FAIL;
}
b->nx = b->ny = b->nz = 2;
if ((b->x = CHECKED_MALLOC_ARRAY(
double, b->nx, "subdivided box X partitions")) == NULL) {
free(b);
free(verts);
free(elems);
return MCELL_FAIL;
}
if ((b->y = CHECKED_MALLOC_ARRAY(
double, b->ny, "subdivided box Y partitions")) == NULL) {
free(b);
free(verts);
free(elems);
return MCELL_FAIL;
}
if ((b->z = CHECKED_MALLOC_ARRAY(
double, b->nz, "subdivided box Z partitions")) == NULL) {
free(b);
free(verts);
free(elems);
return MCELL_FAIL;
}
b->x[0] = llf->x;
b->x[1] = urb->x;
b->y[0] = llf->y;
b->y[1] = urb->y;
b->z[0] = llf->z;
b->z[1] = urb->z;
struct geom_object *meta_box = NULL;
mcell_create_instance_object(state, "PERIODIC_META_BOX", &meta_box);
struct poly_object polygon = { box_name, verts, 8, elems, 12 };
struct geom_object *new_mesh = NULL;
mcell_create_poly_object(state, meta_box, &polygon, &new_mesh);
new_mesh->periodic_x = true;
new_mesh->periodic_y = true;
new_mesh->periodic_z = true;
new_mesh->object_type = BOX_OBJ;
state->periodic_box_obj = new_mesh;
struct polygon_object* p = (struct polygon_object*)(new_mesh->contents);
p->sb = b;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_create_poly_object:
Create a new polygon object.
In: state: the simulation state
poly_obj: all the information needed to create the polygon object (name,
vertices, connections)
Out: 0 on success; any other integer value is a failure.
A mesh is created.
*************************************************************************/
MCELL_STATUS
mcell_create_poly_object(MCELL_STATE *state, struct geom_object *parent,
struct poly_object *poly_obj,
struct geom_object **new_obj) {
// create qualified object name
char *qualified_name =
CHECKED_SPRINTF("%s.%s", parent->sym->name, poly_obj->obj_name);
// Create the symbol, if it doesn't exist yet.
int error_code = 0;
struct geom_object *obj_ptr = make_new_object(
state->dg_parse, // Need to test that dg_parse actually works here
state->obj_sym_table,
qualified_name,
&error_code);
/*struct object *obj_ptr = make_new_object(state, qualified_name, &error_code);*/
if (obj_ptr == NULL) {
free(qualified_name);
return MCELL_FAIL;
}
obj_ptr->last_name = qualified_name;
// Create the actual polygon object
new_polygon_list(state, obj_ptr, poly_obj->num_vert, poly_obj->vertices,
poly_obj->num_conn, poly_obj->connections);
// Do some clean-up.
remove_gaps_from_regions(obj_ptr);
if (check_degenerate_polygon_list(obj_ptr)) {
return MCELL_FAIL;
}
// Set the parent of the object to be the root object. Not reciprocal until
// add_child_objects is called.
obj_ptr->parent = parent;
add_child_objects(parent, obj_ptr, obj_ptr);
*new_obj = obj_ptr;
return MCELL_SUCCESS;
}
/**************************************************************************
new_polygon_list:
Create a new polygon list object.
In: state: the simulation state
obj_ptr: contains information about the object (name, etc)
n_vertices: count of vertices
vertices: list of vertices
n_connections: count of walls
connections: list of walls
Out: polygon object, or NULL if there was an error
NOTE: This is similar to mdl_new_polygon_list
**************************************************************************/
struct polygon_object *
new_polygon_list(MCELL_STATE *state, struct geom_object *obj_ptr, int n_vertices,
struct vertex_list *vertices, int n_connections,
struct element_connection_list *connections) {
struct vertex_list *vert_list = NULL;
struct element_data *elem_data_ptr = NULL;
struct region *reg_ptr = NULL;
struct polygon_object *poly_obj_ptr =
allocate_polygon_object("polygon list object");
if (poly_obj_ptr == NULL) {
goto failure;
}
obj_ptr->object_type = POLY_OBJ;
obj_ptr->contents = poly_obj_ptr;
poly_obj_ptr->n_walls = n_connections;
poly_obj_ptr->n_verts = n_vertices;
// Allocate and initialize removed sides bitmask
poly_obj_ptr->side_removed = new_bit_array(poly_obj_ptr->n_walls);
if (poly_obj_ptr->side_removed == NULL) {
goto failure;
}
set_all_bits(poly_obj_ptr->side_removed, 0);
// Keep temporarily information about vertices in the form of
// "parsed_vertices"
poly_obj_ptr->parsed_vertices = vertices;
// Copy in vertices and normals
vert_list = poly_obj_ptr->parsed_vertices;
for (int i = 0; i < poly_obj_ptr->n_verts; i++) {
// Rescale vertices coordinates
vert_list->vertex->x *= state->r_length_unit;
vert_list->vertex->y *= state->r_length_unit;
vert_list->vertex->z *= state->r_length_unit;
vert_list = vert_list->next;
}
// Allocate wall elements
if ((elem_data_ptr =
CHECKED_MALLOC_ARRAY(struct element_data, poly_obj_ptr->n_walls,
"polygon list object walls")) == NULL) {
goto failure;
}
poly_obj_ptr->element = elem_data_ptr;
// Copy in wall elements
for (int i = 0; i < poly_obj_ptr->n_walls; i++) {
if (connections->n_verts != 3) {
// mdlerror(parse_state, "All polygons must have three vertices.");
goto failure;
}
struct element_connection_list *elem_conn_list_temp = connections;
memcpy(elem_data_ptr[i].vertex_index, connections->indices,
3 * sizeof(int));
connections = connections->next;
free(elem_conn_list_temp->indices);
free(elem_conn_list_temp);
}
// Create object default region on polygon list object:
if ((reg_ptr = mcell_create_region(state, obj_ptr, "ALL")) == NULL) {
goto failure;
}
if ((reg_ptr->element_list_head =
new_element_list(0, poly_obj_ptr->n_walls - 1)) == NULL) {
goto failure;
}
obj_ptr->n_walls = poly_obj_ptr->n_walls;
obj_ptr->n_verts = poly_obj_ptr->n_verts;
if (normalize_elements(reg_ptr, 0)) {
// mdlerror_fmt(parse_state,
// "Error setting up elements in default 'ALL' region in the "
// "polygon object '%s'.", sym->name);
goto failure;
}
return poly_obj_ptr;
failure:
free_connection_list(connections);
free_vertex_list(vertices);
if (poly_obj_ptr) {
if (poly_obj_ptr->element) {
free(poly_obj_ptr->element);
}
if (poly_obj_ptr->side_removed) {
free_bit_array(poly_obj_ptr->side_removed);
}
free(poly_obj_ptr);
}
return NULL;
}
/*************************************************************************
make_new_object:
Create a new object, adding it to the global symbol table.
In: state: system state
obj_name: fully qualified object name
Out: the newly created object
*************************************************************************/
struct geom_object *make_new_object(
struct dyngeom_parse_vars *dg_parse,
struct sym_table_head *obj_sym_table,
const char *obj_name,
int *error_code) {
struct sym_entry *symbol = retrieve_sym(obj_name, obj_sym_table);
if (symbol != NULL) {
if (symbol->count == 0) {
symbol->count = 1;
return (struct geom_object *)symbol->value;
}
else {
*error_code = 1;
return NULL;
}
}
if ((symbol = store_sym(obj_name, OBJ, obj_sym_table, NULL)) == NULL) {
*error_code = 2;
return NULL;
}
*error_code = 0;
return (struct geom_object *)symbol->value;
}
/*************************************************************************
push_object_name:
Append a name component to the name list. For instance, consider this
portion of an MDL:
INSTANTIATE Scene OBJECT
{
MetaBox OBJECT {
MyBox1 OBJECT MyBox{}
MyBox2 OBJECT MyBox{TRANSLATE = [1, 0, 0]}
}
}
When parsing the line beginning with My_Box1, return Scene.MetaBox.MyBox1
In: obj_creation: information about object being created
name: new name component
Out: object name stack is updated, returns new qualified object name
*************************************************************************/
char *push_object_name(struct object_creation *obj_creation, char *name) {
// Initialize object name list
if (obj_creation->object_name_list == NULL) {
obj_creation->object_name_list =
CHECKED_MALLOC_STRUCT(struct name_list, "object name stack");
if (obj_creation->object_name_list == NULL) {
return NULL;
}
obj_creation->object_name_list->name = NULL;
obj_creation->object_name_list->prev = NULL;
obj_creation->object_name_list->next = NULL;
obj_creation->object_name_list_end = obj_creation->object_name_list;
}
/* If the last element is available, just use it. This typically occurs only
* for the first item in the list. */
if (obj_creation->object_name_list_end->name == NULL) {
obj_creation->object_name_list_end->name = name;
return obj_creation->object_name_list_end->name;
}
// If we've run out of name list components, create a new one
struct name_list *name_list_ptr;
if (obj_creation->object_name_list_end->next == NULL) {
name_list_ptr =
CHECKED_MALLOC_STRUCT(struct name_list, "object name stack");
if (name_list_ptr == NULL) {
return NULL;
}
name_list_ptr->next = NULL;
name_list_ptr->prev = obj_creation->object_name_list_end;
obj_creation->object_name_list_end->next = name_list_ptr;
} else {
name_list_ptr = obj_creation->object_name_list_end->next;
}
// Create new name
name_list_ptr->name =
CHECKED_SPRINTF("%s.%s", obj_creation->object_name_list_end->name, name);
if (name_list_ptr->name == NULL) {
return NULL;
}
obj_creation->object_name_list_end = name_list_ptr;
return name_list_ptr->name;
}
/*************************************************************************
pop_object_name:
Remove the trailing name component from the name list. It is expected that
ownership of the name pointer has passed to someone else, or that the
pointer has been freed already.
In: obj_creation: information about object being created
Out: object name stack is updated
*************************************************************************/
void pop_object_name(struct object_creation *obj_creation) {
/*
original code, possibly a memory leak that this free() was commented out,
but it does not match the comment and causes issues with address sanitizer...
if (obj_creation->object_name_list_end->name != NULL) {
free(obj_creation->object_name_list_end->name);
//obj_creation->object_name_list_end->name = NULL;
}
*/
if (obj_creation->object_name_list_end->prev != NULL) {
obj_creation->object_name_list_end =
obj_creation->object_name_list_end->prev;
} else {
obj_creation->object_name_list_end->name = NULL;
}
}
/**************************************************************************
add_child_objects:
Adds children to a meta-object, aggregating counts of walls and vertices
from the children into the specified parent. The children should already
have their parent pointers set. (This must happen earlier so that we can
resolve and validate region references in certain cases before this
function is called.)
In: parent: the parent object
child_head: pointer to head of child list
child_tail: pointer to tail of child list
Out: parent object is updated; child_tail->next pointer is set to NULL
**************************************************************************/
void add_child_objects(struct geom_object *parent, struct geom_object *child_head,
struct geom_object *child_tail) {
if (parent->first_child == NULL) {
parent->first_child = child_head;
}
if (parent->last_child != NULL) {
parent->last_child->next = child_head;
}
parent->last_child = child_tail;
child_tail->next = NULL;
while (child_head != NULL) {
assert(child_head->parent == parent);
parent->n_walls += child_head->n_walls;
parent->n_walls_actual += child_head->n_walls_actual;
parent->n_verts += child_head->n_verts;
child_head = child_head->next;
}
}
/*************************************************************************
common_ancestor:
Find the nearest common ancestor of two objects
In: a, b: objects
Out: their common ancestor in the object tree, or NULL if none exists
*************************************************************************/
struct geom_object *common_ancestor(struct geom_object *a, struct geom_object *b) {
struct geom_object *pa, *pb;
for (pa = (a->object_type == META_OBJ) ? a : a->parent; pa != NULL;
pa = pa->parent) {
for (pb = (b->object_type == META_OBJ) ? b : b->parent; pb != NULL;
pb = pb->parent) {
if (pa == pb) {
return pa;
}
}
}
return NULL;
}
/*************************************************************************
remove_gaps_from_regions:
Clean up the regions on an object, eliminating any removed walls.
In: obj_ptr: an object with regions
Out: Any walls that have been removed from the object are removed from every
region on that object.
*************************************************************************/
void remove_gaps_from_regions(struct geom_object *obj_ptr) {
if (obj_ptr->object_type != BOX_OBJ && obj_ptr->object_type != POLY_OBJ) {
return;
}
struct polygon_object *poly_obj_ptr =
(struct polygon_object *)obj_ptr->contents;
struct region_list *reg_list;
for (reg_list = obj_ptr->regions; reg_list != NULL;
reg_list = reg_list->next) {
no_printf("Checking region %s\n", reg_list->reg->sym->name);
if (strcmp(reg_list->reg->region_last_name, "REMOVED") == 0) {
no_printf("Found a REMOVED region\n");
reg_list->reg->surf_class = NULL;
bit_operation(poly_obj_ptr->side_removed, reg_list->reg->membership, '+');
set_all_bits(reg_list->reg->membership, 0);
}
}
int missing = 0;
for (int n_side = 0; n_side < poly_obj_ptr->side_removed->nbits; ++n_side) {
if (get_bit(poly_obj_ptr->side_removed, n_side)) {
missing++;
}
}
obj_ptr->n_walls_actual = poly_obj_ptr->n_walls - missing;
for (reg_list = obj_ptr->regions; reg_list != NULL;
reg_list = reg_list->next) {
bit_operation(reg_list->reg->membership, poly_obj_ptr->side_removed, '-');
}
}
/**************************************************************************
check_degenerate_polygon_list:
Check a box or polygon list object for degeneracy.
In: obj_ptr: the object to validate
Out: 0 if valid, 1 if invalid
**************************************************************************/
int check_degenerate_polygon_list(struct geom_object *obj_ptr) {
// Check for a degenerate (empty) object and regions.
struct region_list *reg_list;
for (reg_list = obj_ptr->regions; reg_list != NULL;
reg_list = reg_list->next) {
if (!is_region_degenerate(reg_list->reg)) {
continue;
}
if (strcmp(reg_list->reg->region_last_name, "ALL") == 0) {
return 1;
} else if (strcmp(reg_list->reg->region_last_name, "REMOVED") != 0) {
return 1;
}
}
return 0;
}
/**************************************************************************
allocate_polygon_object:
Allocate a polygon object.
In: desc: object type description
Out: polygon object on success, NULL on failure
**************************************************************************/
struct polygon_object *allocate_polygon_object(char const *desc) {
struct polygon_object *poly_obj_ptr;
if ((poly_obj_ptr = CHECKED_MALLOC_STRUCT(struct polygon_object, desc)) ==
NULL) {
return NULL;
}
poly_obj_ptr->n_verts = 0;
poly_obj_ptr->parsed_vertices = NULL;
poly_obj_ptr->n_walls = 0;
poly_obj_ptr->element = NULL;
poly_obj_ptr->sb = NULL;
poly_obj_ptr->side_removed = NULL;
poly_obj_ptr->references = 0;
return poly_obj_ptr;
}
/**************************************************************************
new_element_list:
Create a new element list for a region description.
In: begin: starting side number for this element
end: ending side number for this element
Out: element list, or NULL if allocation fails
**************************************************************************/
struct element_list *new_element_list(unsigned int begin, unsigned int end) {
struct element_list *elem_list =
CHECKED_MALLOC_STRUCT(struct element_list, "region element");
if (elem_list == NULL) {
return NULL;
}
elem_list->special = NULL;
elem_list->next = NULL;
elem_list->begin = begin;
elem_list->end = end;
return elem_list;
}
/**************************************************************************
free_vertex_list:
Free a vertex list.
In: vert_list: vertex to free
Out: list is freed
**************************************************************************/
void free_vertex_list(struct vertex_list *vert_list) {
while (vert_list) {
struct vertex_list *next = vert_list->next;
free(vert_list->vertex);
free(vert_list);
vert_list = next;
}
}
/**************************************************************************
free_connection_list:
Free a connection list.
In: elem_conn_list: connection list to free
Out: list is freed
**************************************************************************/
void free_connection_list(struct element_connection_list *elem_conn_list) {
while (elem_conn_list) {
struct element_connection_list *next = elem_conn_list->next;
free(elem_conn_list->indices);
free(elem_conn_list);
elem_conn_list = next;
}
}
/*************************************************************************
normalize_elements:
Prepare a region description for use in the simulation by creating a
membership bitmask on the region object.
In: reg: a region
existing: a flag indicating whether the region is being modified or
created
Out: returns 1 on failure, 0 on success. Lists of element specifiers
are converted into bitmasks that specify whether a wall is in or
not in that region. This also handles combinations of regions.
NOTE: This is similar to mdl_normalize_elements
*************************************************************************/
int normalize_elements(struct region *reg, int existing) {
struct bit_array *temp = NULL;
char op;
unsigned int num_elems;
if (reg->element_list_head == NULL) {
return 0;
}
struct polygon_object *poly_obj = NULL;
if (reg->parent->object_type == BOX_OBJ) {
poly_obj = (struct polygon_object *)reg->parent->contents;
num_elems = count_cuboid_elements(poly_obj->sb);
} else {
num_elems = reg->parent->n_walls;
}
struct bit_array *elem_array;
if (reg->membership == NULL) {
elem_array = new_bit_array(num_elems);
if (elem_array == NULL) {
// mcell_allocfailed("Failed to allocate a region membership bitmask.");
return 1;
}
reg->membership = elem_array;
} else {
elem_array = reg->membership;
}
if (reg->element_list_head->special == NULL) {
set_all_bits(elem_array, 0);
}
// Special flag for exclusion
else if ((void *)reg->element_list_head->special ==
(void *)reg->element_list_head) {
set_all_bits(elem_array, 1);
} else {
if (reg->element_list_head->special->exclude) {
set_all_bits(elem_array, 1);
} else {
set_all_bits(elem_array, 0);
}
}
int i = 0;
struct element_list *elem_list;
for (elem_list = reg->element_list_head; elem_list != NULL;
elem_list = elem_list->next) {
if (reg->parent->object_type == BOX_OBJ) {
assert(poly_obj != NULL);
i = elem_list->begin;
switch (i) {
case X_NEG:
elem_list->begin = 0;
elem_list->end =
2 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) - 1;
break;
case X_POS:
elem_list->begin = 2 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1);
elem_list->end =
4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) - 1;
break;
case Y_NEG:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1) -
1;
break;
case Y_POS:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1) -
1;
break;
case Z_NEG:
elem_list->begin = 4 * (poly_obj->sb->ny - 1) * (poly_obj->sb->nz - 1) +
4 * (poly_obj->sb->nx - 1) * (poly_obj->sb->nz - 1);
elem_list->end = elem_list->begin +
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->ny - 1) -
1;
break;
case Z_POS:
elem_list->end = num_elems - 1;
elem_list->begin = elem_list->end + 1 -
2 * (poly_obj->sb->nx - 1) * (poly_obj->sb->ny - 1);
break;
case ALL_SIDES:
elem_list->begin = 0;
elem_list->end = num_elems - 1;
break;
default:
UNHANDLED_CASE(i);
/*return 1;*/
}
} else if (elem_list->begin >= (u_int)num_elems ||
elem_list->end >= (u_int)num_elems) {
// mdlerror_fmt(parse_state,
// "Region element specifier refers to sides %u...%u, but
// polygon has only %u sides.",
// elem_list->begin,
// elem_list->end,
// num_elems);
return 1;
}
if (elem_list->special == NULL) {
set_bit_range(elem_array, elem_list->begin, elem_list->end, 1);
} else if ((void *)elem_list->special == (void *)elem_list) {
set_bit_range(elem_array, elem_list->begin, elem_list->end, 0);
} else {
if (elem_list->special->referent != NULL) {
if (elem_list->special->referent->membership == NULL) {
if (elem_list->special->referent->element_list_head != NULL) {
i = normalize_elements(elem_list->special->referent, existing);
if (i) {
free_bit_array(temp);
return i;
}
}
}
if (elem_list->special->referent->membership != NULL) {
// What does it mean for the membership array to have length zero?
if (elem_list->special->referent->membership->nbits == 0) {
if (elem_list->special->exclude) {
set_all_bits(elem_array, 0);
} else {
set_all_bits(elem_array, 1);
}
} else {
if (elem_list->special->exclude) {
op = '-';
} else {
op = '+';
}
bit_operation(elem_array, elem_list->special->referent->membership,
op);
}
}
} else {
int ii;
if (temp == NULL) {
temp = new_bit_array(num_elems);
if (temp == NULL) {
// mcell_allocfailed("Failed to allocate a region membership
// bitmask.");
return 1;
}
}
if (poly_obj == NULL) {
// mcell_internal_error("Attempt to create a PATCH on a
// POLYGON_LIST.");
free_bit_array(temp);
return 1;
}
if (existing) {
// mcell_internal_error("Attempt to create a PATCH on an already
// triangulated BOX.");
free_bit_array(temp);
return 1;
}
if (elem_list->special->exclude) {
op = '-';
} else {
op = '+';
}
ii = cuboid_patch_to_bits(poly_obj->sb, &(elem_list->special->corner1),
&(elem_list->special->corner2), temp);
if (ii) {
// Something wrong with patch.
free_bit_array(temp);
return 1;
}
bit_operation(elem_array, temp, op);
}
}
}
if (temp != NULL) {
free_bit_array(temp);
}
if (existing) {
bit_operation(
elem_array,
((struct polygon_object *)reg->parent->contents)->side_removed, '-');
}
while (reg->element_list_head) {
struct element_list *next = reg->element_list_head->next;
if (reg->element_list_head->special) {
if (reg->element_list_head->special !=
(struct element_special *)reg->element_list_head) {
free(reg->element_list_head->special);
}
}
free(reg->element_list_head);
reg->element_list_head = next;
}
return 0;
}
/*************************************************************************
count_cuboid_elements:
Trivial utility function that counts # walls in a box
In: sb: a subdivided box
Out: the number of walls in the box
*************************************************************************/
int count_cuboid_elements(struct subdivided_box *sb) {
return 4 * ((sb->nx - 1) * (sb->ny - 1) + (sb->nx - 1) * (sb->nz - 1) +
(sb->ny - 1) * (sb->nz - 1));
}
/*************************************************************************
check_patch:
In: b: a subdivided box (array of subdivision locations along each axis)
p1: 3D vector that is one corner of the patch
p2: 3D vector that is the other corner of the patch
egd: the effector grid density, which limits how fine divisions can be
Out: returns 0 if the patch is broken, or a bitmask saying which coordinates
need to be subdivided in order to represent the new patch, if the
spacings are okay.
Note: the two corners of the patch must be aligned with a Cartesian plane
(i.e. it is a planar patch), and must be on the surface of the subdivided
box. Furthermore, the coordinates in the first corner must be smaller or
the same size as the coordinates in the second corner.
*************************************************************************/
int check_patch(struct subdivided_box *b, struct vector3 *p1,
struct vector3 *p2, double egd) {
int i = 0;
int nbits = 0;
int j;
const double minspacing = sqrt(2.0 / egd);
double d;
if (distinguishable(p1->x, p2->x, EPS_C)) {
i |= BRANCH_X;
nbits++;
}
if (distinguishable(p1->y, p2->y, EPS_C)) {
i |= BRANCH_Y;
nbits++;
}
if (distinguishable(p1->z, p2->z, EPS_C)) {
i |= BRANCH_Z;
nbits++;
}
/* Check that we're a patch on one surface */
if (nbits != 2)
return 0;
if ((i & BRANCH_X) == 0 && (distinguishable(p1->x, b->x[0], EPS_C)) &&
(distinguishable(p1->x, b->x[b->nx - 1], EPS_C))) {
return 0;
}
if ((i & BRANCH_Y) == 0 && (distinguishable(p1->y, b->y[0], EPS_C)) &&
(distinguishable(p1->y, b->y[b->ny - 1], EPS_C))) {
return 0;
}
if ((i & BRANCH_Z) == 0 && (distinguishable(p1->z, b->z[0], EPS_C)) &&
(distinguishable(p1->z, b->z[b->nz - 1], EPS_C))) {
return 0;
}
/* Sanity checks for sizes */
if ((i & BRANCH_X) != 0 &&
(p1->x > p2->x || p1->x < b->x[0] || p2->x > b->x[b->nx - 1]))
return 0;
if ((i & BRANCH_Y) != 0 &&
(p1->y > p2->y || p1->y < b->y[0] || p2->y > b->y[b->ny - 1]))
return 0;
if ((i & BRANCH_Z) != 0 &&
(p1->z > p2->z || p1->z < b->z[0] || p2->z > b->z[b->nz - 1]))
return 0;
/* Check for sufficient spacing */
if (i & BRANCH_X) {
d = p2->x - p1->x;
if (d > 0 && d < minspacing)
return 0;
for (j = 0; j < b->nx; j++) {
d = fabs(b->x[j] - p1->x);
if (d > 0 && d < minspacing)
return 0;
d = fabs(b->x[j] - p2->x);
if (d > 0 && d < minspacing)
return 0;
}
}
if (i & BRANCH_Y) {
d = p2->y - p1->y;
if (d > 0 && d < minspacing)
return 0;
for (j = 0; j < b->ny; j++) {
d = fabs(b->y[j] - p1->y);
if (d > 0 && d < minspacing)
return 0;
d = fabs(b->y[j] - p2->y);
if (d > 0 && d < minspacing)
return 0;
}
}
if (i & BRANCH_Z) {
d = p2->z - p1->z;
if (d > 0 && d < minspacing)
return 0;
for (j = 0; j < b->nz; j++) {
d = fabs(b->z[j] - p1->z);
if (d > 0 && d < minspacing)
return 0;
d = fabs(b->z[j] - p2->z);
if (d > 0 && d < minspacing)
return 0;
}
}
return i;
}
/*************************************************************************
cuboid_patch_to_bits:
Convert a patch on a cuboid into a bit array representing membership.
In: subd_box: a subdivided box upon which the patch is located
v1: the lower-valued corner of the patch
v2: the other corner
bit_arr: a bit array to store the results.
Out: returns 1 on failure, 0 on success. The surface of the box is considered
to be tiled with triangles in a particular order, and an array of bits is
set to be 0 for each triangle that is not in the patch and 1 for each
triangle that is. (This is the internal format for regions.)
*************************************************************************/
int cuboid_patch_to_bits(struct subdivided_box *subd_box, struct vector3 *v1,
struct vector3 *v2, struct bit_array *bit_arr) {
int dir_val;
int patch_bitmask = check_patch(subd_box, v1, v2, GIGANTIC);
if (!patch_bitmask)
return 1;
if ((patch_bitmask & BRANCH_X) == 0) {
if (!distinguishable(subd_box->x[0], v1->x, EPS_C))
dir_val = X_NEG;
else
dir_val = X_POS;
} else if ((patch_bitmask & BRANCH_Y) == 0) {
if (!distinguishable(subd_box->y[0], v1->y, EPS_C))
dir_val = Y_NEG;
else
dir_val = Y_POS;
} else {
if (!distinguishable(subd_box->z[0], v1->z, EPS_C))
dir_val = Z_NEG;
else
dir_val = Z_POS;
}
int a_lo, a_hi, b_lo, b_hi;
int line, base;
switch (dir_val) {
case X_NEG:
a_lo = bisect_near(subd_box->y, subd_box->ny, v1->y);
a_hi = bisect_near(subd_box->y, subd_box->ny, v2->y);
b_lo = bisect_near(subd_box->z, subd_box->nz, v1->z);
b_hi = bisect_near(subd_box->z, subd_box->nz, v2->z);
if (distinguishable(subd_box->y[a_lo], v1->y, EPS_C))
return 1;
if (distinguishable(subd_box->y[a_hi], v2->y, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_lo], v1->z, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_hi], v2->z, EPS_C))
return 1;
line = subd_box->ny - 1;
base = 0;
break;
case X_POS:
a_lo = bisect_near(subd_box->y, subd_box->ny, v1->y);
a_hi = bisect_near(subd_box->y, subd_box->ny, v2->y);
b_lo = bisect_near(subd_box->z, subd_box->nz, v1->z);
b_hi = bisect_near(subd_box->z, subd_box->nz, v2->z);
if (distinguishable(subd_box->y[a_lo], v1->y, EPS_C))
return 1;
if (distinguishable(subd_box->y[a_hi], v2->y, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_lo], v1->z, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_hi], v2->z, EPS_C))
return 1;
line = subd_box->ny - 1;
base = (subd_box->ny - 1) * (subd_box->nz - 1);
break;
case Y_NEG:
a_lo = bisect_near(subd_box->x, subd_box->nx, v1->x);
a_hi = bisect_near(subd_box->x, subd_box->nx, v2->x);
b_lo = bisect_near(subd_box->z, subd_box->nz, v1->z);
b_hi = bisect_near(subd_box->z, subd_box->nz, v2->z);
if (distinguishable(subd_box->x[a_lo], v1->x, EPS_C))
return 1;
if (distinguishable(subd_box->x[a_hi], v2->x, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_lo], v1->z, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_hi], v2->z, EPS_C))
return 1;
line = subd_box->nx - 1;
base = 2 * (subd_box->ny - 1) * (subd_box->nz - 1);
break;
case Y_POS:
a_lo = bisect_near(subd_box->x, subd_box->nx, v1->x);
a_hi = bisect_near(subd_box->x, subd_box->nx, v2->x);
b_lo = bisect_near(subd_box->z, subd_box->nz, v1->z);
b_hi = bisect_near(subd_box->z, subd_box->nz, v2->z);
if (distinguishable(subd_box->x[a_lo], v1->x, EPS_C))
return 1;
if (distinguishable(subd_box->x[a_hi], v2->x, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_lo], v1->z, EPS_C))
return 1;
if (distinguishable(subd_box->z[b_hi], v2->z, EPS_C))
return 1;
line = subd_box->nx - 1;
base = 2 * (subd_box->ny - 1) * (subd_box->nz - 1) +
(subd_box->nx - 1) * (subd_box->nz - 1);
break;
case Z_NEG:
a_lo = bisect_near(subd_box->x, subd_box->nx, v1->x);
a_hi = bisect_near(subd_box->x, subd_box->nx, v2->x);
b_lo = bisect_near(subd_box->y, subd_box->ny, v1->y);
b_hi = bisect_near(subd_box->y, subd_box->ny, v2->y);
if (distinguishable(subd_box->x[a_lo], v1->x, EPS_C))
return 1;
if (distinguishable(subd_box->x[a_hi], v2->x, EPS_C))
return 1;
if (distinguishable(subd_box->y[b_lo], v1->y, EPS_C))
return 1;
if (distinguishable(subd_box->y[b_hi], v2->y, EPS_C))
return 1;
line = subd_box->nx - 1;
base = 2 * (subd_box->ny - 1) * (subd_box->nz - 1) +
2 * (subd_box->nx - 1) * (subd_box->nz - 1);
break;
case Z_POS:
a_lo = bisect_near(subd_box->x, subd_box->nx, v1->x);
a_hi = bisect_near(subd_box->x, subd_box->nx, v2->x);
b_lo = bisect_near(subd_box->y, subd_box->ny, v1->y);
b_hi = bisect_near(subd_box->y, subd_box->ny, v2->y);
if (distinguishable(subd_box->x[a_lo], v1->x, EPS_C))
return 1;
if (distinguishable(subd_box->x[a_hi], v2->x, EPS_C))
return 1;
if (distinguishable(subd_box->y[b_lo], v1->y, EPS_C))
return 1;
if (distinguishable(subd_box->y[b_hi], v2->y, EPS_C))
return 1;
line = subd_box->nx - 1;
base = 2 * (subd_box->ny - 1) * (subd_box->nz - 1) +
2 * (subd_box->nx - 1) * (subd_box->nz - 1) +
(subd_box->nx - 1) * (subd_box->ny - 1);
break;
default:
UNHANDLED_CASE(dir_val);
/*return 1;*/
}
set_all_bits(bit_arr, 0);
if (a_lo == 0 && a_hi == line) {
set_bit_range(bit_arr, 2 * (base + line * b_lo + a_lo),
2 * (base + line * (b_hi - 1) + (a_hi - 1)) + 1, 1);
} else {
for (int i = b_lo; i < b_hi; i++) {
set_bit_range(bit_arr, 2 * (base + line * i + a_lo),
2 * (base + line * i + (a_hi - 1)) + 1, 1);
}
}
return 0;
}
int mcell_check_for_region(char *region_name, struct geom_object *obj_ptr) {
struct region_list *reg_list;
for (reg_list = obj_ptr->regions; reg_list != NULL;
reg_list = reg_list->next) {
if (strcmp(region_name, reg_list->reg->sym->name) == 0) {
return 1;
}
}
return 0;
}
/**************************************************************************
mcell_create_region:
Create a named region on an object.
In: state: the simulation state
obj_ptr: object upon which to create a region
name: region name to create
Out: region object, or NULL if there was an error (region already exists or
allocation failed)
NOTE: This is similar to mdl_create_region
**************************************************************************/
struct region *mcell_create_region(MCELL_STATE *state, struct geom_object *obj_ptr,
const char *name) {
struct region *reg_ptr;
struct region_list *reg_list_ptr;
no_printf("Creating new region: %s\n", name);
if ((reg_ptr = make_new_region(state->dg_parse, state, obj_ptr->sym->name, name)) == NULL) {
return NULL;
}
if ((reg_list_ptr =
CHECKED_MALLOC_STRUCT(struct region_list, "region list")) == NULL) {
// mdlerror_fmt(parse_state,
// "Out of memory while creating object region '%s'",
// rp->sym->name);
return NULL;
}
reg_ptr->region_last_name = name;
reg_ptr->parent = obj_ptr;
char *region_name = CHECKED_SPRINTF("%s,%s", obj_ptr->sym->name, name);
if (!mcell_check_for_region(region_name, obj_ptr)) {
reg_list_ptr->reg = reg_ptr;
reg_list_ptr->next = obj_ptr->regions;
obj_ptr->regions = reg_list_ptr;
obj_ptr->num_regions++;
}
else {
free(reg_list_ptr);
}
free(region_name);
return reg_ptr;
}
/*************************************************************************
make_new_region:
Create a new region, adding it to the global symbol table. The region must
not be defined yet. The region is not added to the object's list of
regions.
full region names of REG type symbols stored in main symbol table have the
form:
metaobj.metaobj.poly,region_last_name
In: state: the simulation state
obj_name: fully qualified object name
region_last_name: name of the region to define
Out: The newly created region
NOTE: This is similar to mdl_make_new_region
*************************************************************************/
struct region *make_new_region(
struct dyngeom_parse_vars *dg_parse,
MCELL_STATE *state,
const char *obj_name,
const char *region_last_name) {
char *region_name;
region_name = CHECKED_SPRINTF("%s,%s", obj_name, region_last_name);
if (region_name == NULL) {
return NULL;
}
struct sym_entry *sym_ptr;
if (((sym_ptr = retrieve_sym(region_name, state->reg_sym_table)) != NULL) && (sym_ptr->count == 0)) {
free(region_name);
if (sym_ptr->count == 0) {
sym_ptr->count = 1;
return (struct region *)sym_ptr->value;
}
else {
return NULL;
}
}
if ((sym_ptr = store_sym(region_name, REG, state->reg_sym_table, NULL)) ==
NULL) {
free(region_name);
return NULL;
}
free(region_name);
return (struct region *)sym_ptr->value;
}
/*****************************************************************************
*
* mcell_add_to_vertex_list creates a linked list of mesh vertices belonging
* to a polygon object
*
* During the first invocation of this function, NULL should be provided for
* vertices to initialize a new vertex list. On subsecquent invocations the
* current vertex_list should be provided as parameter vertices to which the
* new vertex will be appended.
*
*****************************************************************************/
struct vertex_list *mcell_add_to_vertex_list(double x, double y, double z,
struct vertex_list *vertices) {
struct vertex_list *verts = (struct vertex_list *)CHECKED_MALLOC_STRUCT(
struct vertex_list, "vertex list");
if (verts == NULL) {
return NULL;
}
struct vector3 *v =
(struct vector3 *)CHECKED_MALLOC_STRUCT(struct vector3, "vector");
if (v == NULL) {
free(verts);
return NULL;
}
v->x = x;
v->y = y;
v->z = z;
verts->vertex = v;
verts->next = vertices;
return verts;
}
/*****************************************************************************
*
* mcell_add_to_connection_list creates a linked list of element connections
* describing a polygon object.
*
* During the first invocation of this function, NULL should be provided for
* elements to initialize a new element connection list. On subsecquent
* invocations the current element_connection_list should be provided as
* parameter elements to which the new element connection will be appended.
*
*****************************************************************************/
struct element_connection_list *
mcell_add_to_connection_list(int v1, int v2, int v3,
struct element_connection_list *elements) {
struct element_connection_list *elems =
(struct element_connection_list *)CHECKED_MALLOC_STRUCT(
struct element_connection_list, "element connection list");
if (elems == NULL) {
return NULL;
}
int *e = (int *)CHECKED_MALLOC_ARRAY(int, 3, "element connections");
if (e == NULL) {
free(elems);
return NULL;
}
e[0] = v1;
e[1] = v2;
e[2] = v3;
elems->n_verts = 3;
elems->indices = e;
elems->next = elements;
return elems;
}
/**************************************************************************
mcell_set_region_elements:
Set the elements for a region, normalizing the region if it's on a polygon
list object.
In: rgn: region to receive elements
elements: elements comprising region
normalize_now: flag indicating whether to normalize right now
Out: returns 1 on failure, 0 on success.
NOTE: Almost the same as mdl_set_region_elements
**************************************************************************/
int mcell_set_region_elements(struct region *rgn, struct element_list *elements,
int normalize_now) {
rgn->element_list_head = elements;
if (normalize_now)
return normalize_elements(rgn, 0);
else
return 0;
}
/**************************************************************************
mcell_add_to_region_list:
In: elements: the list of elements for a region
region_idx: the index of the region
Out: the updated list of elements for a region
**************************************************************************/
struct element_list *mcell_add_to_region_list(struct element_list *elements,
u_int region_idx) {
struct element_list *elem = (struct element_list *)CHECKED_MALLOC_STRUCT(
struct element_list, "element list");
if (elem == NULL) {
return NULL;
}
elem->next = elements;
elem->begin = region_idx;
elem->end = region_idx;
elem->special = NULL;
return elem;
}
/****************************************************************************
*
* static helper functions
*
****************************************************************************/
/**************************************************************************
is_region_degenerate:
Check a region for degeneracy.
In: reg_ptr: region to check
Out: 1 if degenerate, 0 if not
**************************************************************************/
int is_region_degenerate(struct region *reg_ptr) {
for (int i = 0; i < reg_ptr->membership->nbits; i++) {
if (get_bit(reg_ptr->membership, i)) {
return 0;
}
}
return 1;
}
struct sym_entry *
mcell_get_obj_sym(struct geom_object *obj) {
return obj->sym;
}
struct sym_entry *
mcell_get_reg_sym(struct region *reg) {
return reg->sym;
}
struct sym_entry *
mcell_get_all_mol_sym(MCELL_STATE *state) {
return state->all_mols->sym;
}
struct sym_entry *
mcell_get_all_volume_mol_sym(MCELL_STATE *state) {
return state->all_volume_mols->sym;
}
struct sym_entry *
mcell_get_all_surface_mol_sym(MCELL_STATE *state) {
return state->all_surface_mols->sym;
}
struct poly_object_list* mcell_add_to_poly_obj_list(
struct poly_object_list* poly_obj_list,
char *obj_name,
struct vertex_list *vertices,
int num_vert,
struct element_connection_list *connections,
int num_conn,
struct element_list *surf_reg_faces,
char *reg_name) {
struct poly_object_list *pobj_list = (struct poly_object_list *)CHECKED_MALLOC_STRUCT(
struct poly_object_list, "poly obj list");
if (pobj_list == NULL) {
return NULL;
}
char *object_name = CHECKED_STRDUP(obj_name, "object name");
char *region_name = CHECKED_STRDUP(reg_name, "object name");
pobj_list->vertices = vertices;
pobj_list->num_vert = num_vert;
pobj_list->connections = connections;
pobj_list->num_conn = num_conn;
pobj_list->surf_reg_faces = surf_reg_faces;
pobj_list->reg_name = region_name;
pobj_list->obj_name = object_name;
pobj_list->next = poly_obj_list;
return pobj_list;
}
| C |
3D | mcellteam/mcell | src/react_util.c | .c | 24,719 | 630 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
/**************************************************************************\
** File: react_util.c **
** **
** Purpose: Functionality related to setting up reactions **
** **
\**************************************************************************/
#include "config.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <assert.h>
#include "logging.h"
#include "mcell_structs.h"
#include "react_util.h"
/*************************************************************************
*
* function for computing the probability factor (pb_factor) used to
* convert reaction rate constants into probabilities
*
* in: mcell state
* rx to compute pb_factor for
* maximum number of expected surface products for this reaction
*
* out: pb_factor
*
************************************************************************/
double compute_pb_factor(double time_unit,
double length_unit,
double grid_density,
double rx_radius_3d,
struct reaction_flags *rxn_flags,
int *create_shared_walls_info_flag,
struct rxn *rx,
int max_num_surf_products) {
/* determine the number of volume and surface reactants as well
* as the number of surfaces */
int num_vol_reactants = 0;
int num_surf_reactants = 0;
int num_surfaces = 0;
for (unsigned int n_reactant = 0; n_reactant < rx->n_reactants;
n_reactant++) {
if ((rx->players[n_reactant]->flags & ON_GRID) != 0) {
num_surf_reactants++;
} else if ((rx->players[n_reactant]->flags & NOT_FREE) == 0) {
num_vol_reactants++;
} else if (rx->players[n_reactant]->flags & IS_SURFACE) {
num_surfaces++;
}
}
/* probability for this reaction */
double pb_factor = 0.0;
/* determine reaction probability by proper conversion of the reaction
* rate constant */
if (rx->n_reactants == 1) {
pb_factor = time_unit;
if (max_num_surf_products > 0)
*create_shared_walls_info_flag = 1;
} /* end if (rx->reactants == 1) */
else if (((rx->n_reactants == 2) &&
(num_surf_reactants >= 1 || num_surfaces == 1)) ||
((rx->n_reactants == 3) && (num_surfaces == 1))) {
if ((num_surf_reactants == 2) && (num_vol_reactants == 0) &&
(num_surfaces < 2)) {
/* this is a reaction between two surface molecules */
/* with an optional SURFACE */
rxn_flags->surf_surf_reaction_flag = 1;
*create_shared_walls_info_flag = 1;
if (rx->players[0]->flags & rx->players[1]->flags & CANT_INITIATE)
mcell_error("Reaction between %s and %s listed, but both are marked "
"TARGET_ONLY.",
rx->players[0]->sym->name, rx->players[1]->sym->name);
else if ((rx->players[0]->flags | rx->players[1]->flags) &
CANT_INITIATE) {
pb_factor =
time_unit * grid_density / 3; /* 3 neighbors */
} else {
pb_factor = time_unit * grid_density /
6; /* 2 molecules, 3 neighbors each */
}
} else if ((((rx->players[0]->flags & IS_SURFACE) != 0 &&
(rx->players[1]->flags & ON_GRID) != 0) ||
((rx->players[1]->flags & IS_SURFACE) != 0 &&
(rx->players[0]->flags & ON_GRID) != 0)) &&
(rx->n_reactants == 2)) {
/* This is actually a unimolecular reaction in disguise! */
pb_factor = time_unit;
if (max_num_surf_products > 0)
*create_shared_walls_info_flag = 1;
} else if (((rx->n_reactants == 2) && (num_vol_reactants == 1) &&
(num_surfaces == 1)) ||
((rx->n_reactants == 2) && (num_vol_reactants == 1) &&
(num_surf_reactants == 1)) ||
((rx->n_reactants == 3) && (num_vol_reactants == 1) &&
(num_surf_reactants == 1) && (num_surfaces == 1))) {
/* this is a reaction between "vol_mol" and "surf_mol" */
/* with an optional SURFACE */
/* or reaction between "vol_mol" and SURFACE */
if (max_num_surf_products > 0)
*create_shared_walls_info_flag = 1;
if (((rx->n_reactants == 2) && (num_vol_reactants == 1) &&
(num_surfaces == 1))) {
/* do not take into acccount SPECIAL reactions */
if (rx->n_pathways > RX_SPECIAL) {
rxn_flags->vol_wall_reaction_flag = 1;
}
} else {
rxn_flags->vol_surf_reaction_flag = 1;
}
double D_tot = 0.0;
double t_step = 0.0;
if ((rx->players[0]->flags & NOT_FREE) == 0) {
D_tot = rx->get_reactant_diffusion(rx, 0);
t_step = rx->get_reactant_time_step(rx,0) * time_unit;
} else if ((rx->players[1]->flags & NOT_FREE) == 0) {
D_tot = rx->get_reactant_diffusion(rx, 1);
t_step = rx->get_reactant_time_step(rx,1) * time_unit;
} else {
/* Should never happen. */
D_tot = 1.0;
t_step = 1.0;
}
if (D_tot <= 0.0)
pb_factor = 0; /* Reaction can't happen! */
else
pb_factor = 1.0e11 * grid_density / (2.0 * N_AV) *
sqrt(MY_PI * t_step / D_tot);
if ((rx->geometries[0] + rx->geometries[1]) *
(rx->geometries[0] - rx->geometries[1]) ==
0 &&
rx->geometries[0] * rx->geometries[1] != 0) {
pb_factor *= 2.0;
}
} /* end else */
} else if ((rx->n_reactants == 2) && (num_vol_reactants == 2)) {
/* This is the reaction between two "vol_mols" */
rxn_flags->vol_vol_reaction_flag = 1;
double eff_vel_a = rx->get_reactant_space_step(rx,0) / rx->get_reactant_time_step(rx,0);
double eff_vel_b = rx->get_reactant_space_step(rx,1) / rx->get_reactant_time_step(rx,1);
double eff_vel;
if (rx->players[0]->flags & rx->players[1]->flags & CANT_INITIATE)
mcell_error(
"Reaction between %s and %s listed, but both are marked TARGET_ONLY.",
rx->players[0]->sym->name, rx->players[1]->sym->name);
else if (rx->players[0]->flags & CANT_INITIATE)
eff_vel_a = 0;
else if (rx->players[1]->flags & CANT_INITIATE)
eff_vel_b = 0;
if (eff_vel_a + eff_vel_b > 0) {
eff_vel = (eff_vel_a + eff_vel_b) * length_unit /
time_unit; /* Units=um/sec */
pb_factor = 1.0 / (2.0 * sqrt(MY_PI) * rx_radius_3d *
rx_radius_3d * eff_vel);
pb_factor *= 1.0e15 / N_AV; /* Convert L/mol.s to um^3/number.s */
} else
pb_factor = 0.0; /* No rxn possible */
} else if ((rx->n_reactants == 3) && (num_vol_reactants == 3)) {
/* This is the reaction between three "vol_mols" */
rxn_flags->vol_vol_vol_reaction_flag = 1;
double eff_dif_a, eff_dif_b, eff_dif_c,
eff_dif; /* effective diffusion constants*/
eff_dif_a = rx->get_reactant_diffusion(rx, 0);
eff_dif_b = rx->get_reactant_diffusion(rx, 1);
eff_dif_c = rx->get_reactant_diffusion(rx, 2);
if (rx->players[0]->flags & rx->players[1]->flags & rx->players[2]->flags &
CANT_INITIATE)
mcell_error("Reaction between %s and %s and %s listed, but all marked "
"TARGET_ONLY.",
rx->players[0]->sym->name, rx->players[1]->sym->name,
rx->players[2]->sym->name);
if (rx->players[0]->flags & CANT_INITIATE)
eff_dif_a = 0;
if (rx->players[1]->flags & CANT_INITIATE)
eff_dif_b = 0;
if (rx->players[2]->flags & CANT_INITIATE)
eff_dif_c = 0;
if (eff_dif_a + eff_dif_b + eff_dif_c > 0) {
eff_dif = (eff_dif_a + eff_dif_b + eff_dif_c) *
1.0e8; /* convert from cm^2/sec to um^2/sec */
pb_factor =
1.0 / (6.0 * (MY_PI) * rx_radius_3d * rx_radius_3d *
(MY_PI) * rx_radius_3d * rx_radius_3d * eff_dif);
pb_factor *=
1.0e30 / (N_AV * N_AV); /* Convert (L/mol)^2/s to (um^3/number)^2/s */
} else
pb_factor = 0.0; /* No rxn possible */
} else if ((rx->n_reactants == 3) && (num_vol_reactants == 2) &&
(num_surf_reactants == 1)) {
/* This is a reaction between 2 volume_molecules and */
/* one surface_molecule */
rxn_flags->vol_vol_surf_reaction_flag = 1;
if (max_num_surf_products > 0)
*create_shared_walls_info_flag = 1;
/* find out what reactants are volume_molecules */
/* and what is surface_molecule */
struct species *vol_reactant1 = NULL, *vol_reactant2 = NULL;
struct species *surf_reactant = NULL;
/* geometries of the reactants */
int vol_react1_geom = 0, vol_react2_geom = 0, surf_react_geom = 0;
if ((rx->players[0]->flags & NOT_FREE) == 0) {
vol_reactant1 = rx->players[0];
vol_react1_geom = rx->geometries[0];
if ((rx->players[1]->flags & NOT_FREE) == 0) {
vol_reactant2 = rx->players[1];
vol_react2_geom = rx->geometries[1];
surf_reactant = rx->players[2];
surf_react_geom = rx->geometries[2];
} else if ((rx->players[2]->flags & NOT_FREE) == 0) {
vol_reactant2 = rx->players[2];
vol_react2_geom = rx->geometries[2];
surf_reactant = rx->players[1];
surf_react_geom = rx->geometries[1];
}
} else if ((rx->players[1]->flags & NOT_FREE) == 0) {
vol_reactant1 = rx->players[1];
vol_react1_geom = rx->geometries[1];
if ((rx->players[0]->flags & NOT_FREE) == 0) {
vol_reactant2 = rx->players[0];
vol_react2_geom = rx->geometries[0];
surf_reactant = rx->players[2];
surf_react_geom = rx->geometries[2];
} else if ((rx->players[2]->flags & NOT_FREE) == 0) {
vol_reactant2 = rx->players[2];
vol_react2_geom = rx->geometries[2];
surf_reactant = rx->players[0];
surf_react_geom = rx->geometries[0];
}
}
/* volume reactants should be aligned - it means that
they should be in the same orientation class and have
the same sign */
if (vol_react1_geom != vol_react2_geom)
mcell_error("In 3-way reaction %s + %s + %s ---> [...] volume reactants "
"%s and %s are either in different orientation classes or "
"have opposite orientation sign.",
rx->players[0]->sym->name, rx->players[1]->sym->name,
rx->players[2]->sym->name, vol_reactant1->sym->name,
vol_reactant2->sym->name);
double eff_dif_1, eff_dif_2, eff_dif; /* effective diffusion constants*/
eff_dif_1 = rx->get_reactant_diffusion(rx, 0);
eff_dif_2 = rx->get_reactant_diffusion(rx, 1);
if (vol_reactant1->flags & vol_reactant2->flags & surf_reactant->flags &
CANT_INITIATE) {
mcell_error("Reaction between %s and %s and %s listed, but all marked "
"TARGET_ONLY.",
vol_reactant1->sym->name, vol_reactant2->sym->name,
surf_reactant->sym->name);
} else if (vol_reactant1->flags & vol_reactant2->flags & CANT_INITIATE) {
mcell_error("Reaction between %s and %s and %s listed, but both volume "
"molecules %s and %s marked TARGET_ONLY.",
vol_reactant1->sym->name, vol_reactant2->sym->name,
surf_reactant->sym->name, vol_reactant1->sym->name,
vol_reactant2->sym->name);
} else {
if (vol_reactant1->flags & CANT_INITIATE)
eff_dif_1 = 0;
if (vol_reactant2->flags & CANT_INITIATE)
eff_dif_2 = 0;
}
if ((eff_dif_1 + eff_dif_2) > 0) {
eff_dif = (eff_dif_1 + eff_dif_2) *
1.0e8; /* convert from cm^2/sec to um^2/sec */
pb_factor =
2.0 * grid_density /
(3.0 * (MY_PI) * rx_radius_3d * rx_radius_3d * eff_dif);
pb_factor *=
1.0e30 / (N_AV * N_AV); /* Convert (L/mol)^2/s to (um^3/number)^2/s */
} else
pb_factor = 0.0; /* No rxn possible */
/* The value of pb_factor above is calculated for the case
when surface_molecule can be hit from either side Otherwise the
reaction_rate should be doubled. So we check whether both of the
volume_molecules are in the same orientation class as
surface_molecule.
*/
/* flags that show whether volume reactants are in the same
orientation classes as surface reactant */
int vol_react1_and_surf_react = 0, vol_react2_and_surf_react = 0;
if ((vol_react1_geom + surf_react_geom) *
(vol_react1_geom - surf_react_geom) ==
0 &&
vol_react1_geom * surf_react_geom != 0) {
vol_react1_and_surf_react = 1;
}
if ((vol_react2_geom + surf_react_geom) *
(vol_react2_geom - surf_react_geom) ==
0 &&
vol_react2_geom * surf_react_geom != 0) {
vol_react2_and_surf_react = 1;
}
if (vol_react1_and_surf_react && vol_react2_and_surf_react) {
pb_factor *= 2.0;
}
} else if ((rx->n_reactants == 3) && (num_vol_reactants == 1) &&
(num_surf_reactants == 2)) {
/* one volume reactant and two surface reactants */
rxn_flags->vol_surf_surf_reaction_flag = 1;
*create_shared_walls_info_flag = 1;
/* find out what reactants are volume_molecules
and what reactant is a surface_molecule */
struct species *surf_reactant1 = NULL, *surf_reactant2 = NULL;
struct species *vol_reactant = NULL;
/* geometries of the reactants */
int vol_react_geom = 0, surf_react1_geom = 0, surf_react2_geom = 0;
int volume_index = -1;
if ((rx->players[0]->flags & NOT_FREE) == 0) {
vol_reactant = rx->players[0];
volume_index = 0;
vol_react_geom = rx->geometries[0];
surf_reactant1 = rx->players[1];
surf_react1_geom = rx->geometries[1];
surf_reactant2 = rx->players[2];
surf_react2_geom = rx->geometries[2];
} else if ((rx->players[1]->flags & NOT_FREE) == 0) {
vol_reactant = rx->players[1];
volume_index = 1;
vol_react_geom = rx->geometries[1];
surf_reactant1 = rx->players[0];
surf_react1_geom = rx->geometries[0];
surf_reactant2 = rx->players[2];
surf_react2_geom = rx->geometries[2];
} else if ((rx->players[2]->flags & NOT_FREE) == 0) {
vol_reactant = rx->players[2];
volume_index = 2;
vol_react_geom = rx->geometries[2];
surf_reactant1 = rx->players[0];
surf_react1_geom = rx->geometries[0];
surf_reactant2 = rx->players[1];
surf_react2_geom = rx->geometries[1];
}
assert(vol_reactant != NULL);
if (vol_reactant->flags & CANT_INITIATE)
mcell_error("3-way reaction between %s and %s and %s listed, but the "
"only volume reactant %s is marked TARGET_ONLY",
vol_reactant->sym->name, surf_reactant1->sym->name,
surf_reactant2->sym->name, vol_reactant->sym->name);
double eff_vel = rx->get_reactant_space_step(rx, volume_index) / rx->get_reactant_time_step(rx, volume_index);
if (eff_vel > 0) {
eff_vel =
eff_vel * length_unit / time_unit; /* Units=um/sec */
pb_factor = (sqrt(MY_PI) * grid_density * grid_density) /
(6.0 * eff_vel);
/* NOTE: the reaction rate should be in units of
volume * area * #^(-2) * s^(-1) that means
(um)^5 * #^(-2) * s^(-1),
otherwise if the reaction rate is in
(um^2/(M*#*s) units conversion is necessary
*/
} else
pb_factor = 0.0; /* No rxn possible */
/* The value of pb_factor above is calculated for the case
when surface_molecule can be hit from either side
Otherwise the reaction_rate should be doubled.
So we check whether the volume_molecule
is in the same orientation class as surface_molecules.
*/
/* flags that show whether volume reactant is in the same
orientation class as surface reactants */
int vol_react_and_surf_react1 = 0, vol_react_and_surf_react2 = 0;
if ((vol_react_geom + surf_react1_geom) *
(vol_react_geom - surf_react1_geom) ==
0 &&
vol_react_geom * surf_react1_geom != 0) {
vol_react_and_surf_react1 = 1;
}
if ((vol_react_geom + surf_react2_geom) *
(vol_react_geom - surf_react2_geom) ==
0 &&
vol_react_geom * surf_react2_geom != 0) {
vol_react_and_surf_react2 = 1;
}
if (vol_react_and_surf_react1 && vol_react_and_surf_react2) {
pb_factor *= 2.0;
}
} else if ((rx->n_reactants == 3) && (num_surf_reactants == 3)) {
rxn_flags->surf_surf_surf_reaction_flag = 1;
*create_shared_walls_info_flag = 1;
int num_active_reactants = 0;
for (int i = 0; i < 3; i++) {
if (rx->players[i]->flags & CANT_INITIATE)
continue;
else
num_active_reactants++;
}
/* Calculation of pb_factor below should
account for possible number of outcomes with TARGET_ONLY
specification. E.g. when mols A,B,C are all active there are 6
possible combinations = number of permutations out of 3. When e.g. C
mol is TARGET_ONLY there are only 4 combinations (ABC,ACB,BCA,BAC).
When both B and C mols are TARGET_ONLY there are two possible
combinations - (ABC, ACB). */
if (num_active_reactants == 0) {
mcell_error("Reaction between %s and %s and %s listed, but all marked "
"TARGET_ONLY.",
rx->players[0]->sym->name, rx->players[1]->sym->name,
rx->players[2]->sym->name);
} else if (num_active_reactants == 3) {
/* basic case */
pb_factor =
(grid_density * grid_density * time_unit) / 6.0;
} else if (num_active_reactants == 2) {
pb_factor =
(grid_density * grid_density * time_unit) / 4.0;
} else if (num_active_reactants == 1) {
pb_factor =
(grid_density * grid_density * time_unit) / 2.0;
}
/* NOTE: the reaction rate should be in units of
(um)^4 * #^(-2) * s^(-1),
otherwise the units conversion is necessary
*/
}
return pb_factor;
}
/****************************************************************************
*
* function determining the reaction (struct rxn*) and pathway corresponding
* to the given reaction name or NULL otherwise.
*
* in: reaction hash
* size of reaction hash
* named reaction to look for
* pointer to found reaction (if any)
* pointer to pathway of found reaction (if any)
* out: returns 0 on success and 1 on failure
*
***************************************************************************/
int get_rxn_by_name(struct rxn **reaction_hash, int hashsize,
const char *rx_name, struct rxn **found_rx, int *path_id) {
for (int i = 0; i < hashsize; ++i) {
struct rxn *rx = NULL;
struct rxn *rx_array = reaction_hash[i];
for (rx = rx_array; rx != NULL; rx = rx->next) {
for (int j = 0; j < rx->n_pathways; ++j) {
struct rxn_pathname *path = rx->info[j].pathname;
if (path != NULL && strcmp(path->sym->name, rx_name) == 0) {
*found_rx = rx;
// XXX below we convert from u_int to int which is bad
// unfortunately MCell internally mixes u_int and int for
// the pathway id.
*path_id = path->path_num;
return 0;
}
}
}
}
return 1;
}
/*************************************************************************
*
* function changing the probability for the given reaction according
* to the provided reaction rate constant. The probability change happens
* instantaneously at the time of calling this function.
*
* NOTE: This function will only change functions with a fixed reaction
* rate constants. If called on functions with time varying rates
* the function will do nothing.
*
* in: reaction_prob_limit_flag:
* notify:
* rx: reaction to change rates of
* path_id:
* new_rate: new reaction rate
* out: returns 1 on success and 0 on failure
*
*************************************************************************/
int change_reaction_probability(byte *reaction_prob_limit_flag,
struct notifications *notify, struct rxn *rx,
int path_id, double new_rate) {
/* don't do anything with time dependend rate */
if (rx->prob_t != NULL) {
return 1;
}
// compute change in probabilities from current value
double prob = new_rate * rx->pb_factor;
double delta_prob = 0.0;
if (path_id == 0) {
delta_prob = prob - rx->cum_probs[0];
} else {
delta_prob = prob - (rx->cum_probs[path_id] - rx->cum_probs[path_id - 1]);
}
// update cummulative probabilities
for (int i = path_id; i < rx->n_pathways; i++) {
rx->cum_probs[i] += delta_prob;
}
// update probability trackers
rx->max_fixed_p += delta_prob;
rx->min_noreaction_p += delta_prob;
// print update message
if (rx->n_reactants == 1) {
mcell_log_raw("Probability %.4e set for %s[%d] -> ", prob,
rx->players[0]->sym->name, rx->geometries[0]);
} else if (rx->n_reactants == 2) {
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] -> ", prob,
rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1]);
} else {
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] + %s[%d] -> ", prob,
rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
}
for (unsigned int n_product = rx->product_idx[path_id];
n_product < rx->product_idx[path_id + 1]; n_product++) {
if (rx->players[n_product] != NULL) {
mcell_log_raw("%s[%d] ", rx->players[n_product]->sym->name,
rx->geometries[n_product]);
}
}
mcell_log_raw("\n");
if ((prob > 1.0) && (!*reaction_prob_limit_flag)) {
*reaction_prob_limit_flag = 1;
}
issue_reaction_probability_warnings(notify, rx);
return 0;
}
/*************************************************************************
*
* function printing warnings for high reaction probabilties (if
* requested) for the given reaction.
*
*************************************************************************/
void issue_reaction_probability_warnings(
struct notifications *notify, struct rxn *rx) {
if (rx->cum_probs[rx->n_pathways - 1] > notify->reaction_prob_warn) {
FILE *warn_file = mcell_get_log_file();
if (notify->high_reaction_prob != WARN_COPE) {
if (notify->high_reaction_prob == WARN_ERROR) {
warn_file = mcell_get_error_file();
fprintf(warn_file, "Error: High ");
} else {
fprintf(warn_file, "Warning: High ");
}
if (rx->n_reactants == 1) {
fprintf(warn_file, "total probability %.4e for %s[%d] -> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0]);
} else if (rx->n_reactants == 2) {
fprintf(warn_file, "total probability %.4e for %s[%d] + %s[%d] "
"-> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name,
rx->geometries[1]);
} else {
fprintf(warn_file, "total probability %.4e for %s[%d] + %s[%d] + "
"%s[%d] -> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
}
}
if (notify->high_reaction_prob == WARN_ERROR) {
mcell_die();
}
}
return;
}
| C |
3D | mcellteam/mcell | src/react_trig_nfsim.c | .c | 16,137 | 480 | #include "config.h"
//#include "hashmap.h"
#include "map_c.h"
#include "logging.h"
#include "mcell_structs.h"
#include "nfsim_func.h"
#include "react.h"
#include "react_nfsim.h"
#include "react_util.h"
#include "sym_table.h"
#include <stdlib.h>
#include <string.h>
//#include "lru.h"
map_t reaction_map = NULL;
map_t reaction_preliminary_map = NULL;
void clear_maps() {
hashmap_clear(reaction_map);
hashmap_clear(reaction_preliminary_map);
}
// struct rxn *rx;
unsigned long lhash(const char *keystring) {
unsigned long key = crc32((unsigned char *)(keystring), strlen(keystring));
/* Robert Jenkins' 32 bit Mix Function */
key += (key << 12);
key ^= (key >> 22);
key += (key << 4);
key ^= (key >> 9);
key += (key << 10);
key ^= (key >> 2);
key += (key << 7);
key ^= (key >> 12);
/* Knuth's Multiplicative Method */
key = (key >> 3) * 2654435761;
return key;
}
queryOptions initializeNFSimQueryForBimolecularReactions(
struct graph_data *graph1, struct graph_data *graph2, const char *onlyActive) {
// constant settings
static const char *optionKeys[2] = {"numReactants", "onlyActive"};
static char *optionValues[2];
optionValues[0] = (char *)"2";
optionValues[1] = (char *)onlyActive;
static const int optionSeeds[2] = {1, 1};
static char *speciesArray[2];
// initialize speciesArray with the string we are going to query
speciesArray[0] = graph1->graph_pattern;
if (graph2)
speciesArray[1] = graph2->graph_pattern;
// copy these settings to the options object
queryOptions options;
options.initKeys = speciesArray;
options.initValues = optionSeeds;
// we can potentially query just for the bimolecular reactions a single
// reactant is involved in
// the only active flag would need to be off though
if (graph2)
options.numOfInitElements = 2;
else
options.numOfInitElements = 1;
options.optionKeys = optionKeys;
options.optionValues = optionValues;
options.numOfOptions = 2;
return options;
}
/**********************************************************************
*
* This function creates a queryOptions object for designing an NFSim
* experiment query
*
* In: The abstract molecule whose nfsim status we are going to verify
*
* Out: the queryOptions object we will use to interact with nfsim
*
**********************************************************************/
queryOptions
initializeNFSimQueryForUnimolecularReactions(struct abstract_molecule *am) {
// constant settings
static const char *optionKeys[1] = {"numReactants"};
static char *optionValues[1] = {(char *)"1"};
static const int optionSeeds[1] = {1};
static char *speciesArray[1];
// initialize speciesArray with the string we are going to query
// const char** speciesArray = CHECKED_MALLOC_ARRAY(char*, 1, "string array of
// patterns");
speciesArray[0] = am->graph_data->graph_pattern;
// copy these settings to the options object
queryOptions options;
options.initKeys = speciesArray;
options.initValues = optionSeeds;
options.numOfInitElements = 1;
options.optionKeys = optionKeys;
options.optionValues = optionValues;
options.numOfOptions = 1;
// free(speciesArray);
return options;
}
/*************************************************************************
In: hashA - hash value for first molecule
hashB - hash value for second molecule
reacA - species of first molecule
reacB - species of second molecule
Out: 1 if any reaction exists naming the two specified reactants, 0
otherwise.
Note: This is a quick test used to determine which per-species lists to
traverse when checking for mol-mol collisions.
*************************************************************************/
long rxnfound = 0;
long rxnmissed = 0;
int trigger_bimolecular_preliminary_nfsim(struct abstract_molecule *reacA,
struct abstract_molecule *reacB) {
if (reaction_preliminary_map == NULL)
reaction_preliminary_map = hashmap_new();
bool *isValidReaction = NULL;
unsigned long reactionHash = reacA->graph_data->graph_pattern_hash +
reacB->graph_data->graph_pattern_hash;
int error = hashmap_get_nohash(reaction_preliminary_map, reactionHash,
reactionHash, (void **)(&isValidReaction));
// error = find_in_cache(reaction_key, rx);
// XXX: it might be worth it to return the rx object since we already queried
// it
if (error == MAP_OK) {
if (isValidReaction != NULL)
return 1;
rxnfound++;
return 0;
}
rxnmissed++;
queryOptions options = initializeNFSimQueryForBimolecularReactions(
reacA->graph_data, reacB->graph_data, "1");
void *results = mapvectormap_create();
initAndQueryByNumReactant_c(options, results);
// if we have reactions great! although we can't decide what to do with them
// yet. bummer.
if (mapvectormap_size(results) > 0) {
isValidReaction = CHECKED_MALLOC_ARRAY(bool, 1, "this is a valid reaction");
*isValidReaction = true;
mapvectormap_delete(results);
error = hashmap_put_nohash(reaction_preliminary_map, reactionHash,
reactionHash, isValidReaction);
return 1;
} else {
// if we know there's no reactions there's no need to check again later
mapvectormap_delete(results);
error = hashmap_put_nohash(reaction_preliminary_map, reactionHash,
reactionHash, NULL);
return 0;
}
}
/***********
********/
int trigger_bimolecular_nfsim(struct volume *state,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB, short orientA,
short orientB, struct rxn **matching_rxns) {
int error;
int num_matching_rxns = 0;
if (reaction_map == NULL)
reaction_map = hashmap_new();
// memset(&reaction_key[0], 0, sizeof(reaction_key));
struct rxn *rx = NULL;
unsigned long reactionHash = reacA->graph_data->graph_pattern_hash +
reacB->graph_data->graph_pattern_hash;
// sprintf(reaction_key,"%lu",reacA->graph_pattern_hash +
// reacB->graph_pattern_hash);
// mcell_log("reaction_key %s %s %s",reacA->graph_pattern,
// reacB->graph_pattern, reaction_key);
// A + B ->C is the same as B +A -> C
// if (strcmp(reacA->graph_pattern, reacB->graph_pattern) < 0)
// sprintf(reaction_key,"%s-%s",reacA->graph_pattern,reacB->graph_pattern);
// else
// sprintf(reaction_key,"%s-%s",reacB->graph_pattern,reacA->graph_pattern);
error = hashmap_get_nohash(reaction_map, reactionHash, reactionHash,
(void **)(&rx));
// error = find_in_cache(reaction_key, rx);
if (error == MAP_OK) {
// if(error != -1){
if (rx != NULL) {
int result = process_bimolecular(reacA, reacB, rx, orientA, orientB,
matching_rxns, num_matching_rxns);
if (result == 1)
num_matching_rxns++;
}
return num_matching_rxns;
}
// mcell_log("+++++ %s %s %s",reacA->graph_pattern, reacB->graph_pattern,
// reaction_key);
queryOptions options = initializeNFSimQueryForBimolecularReactions(
reacA->graph_data, reacB->graph_data, "1");
// reset, init, query the nfsim system
void *results = mapvectormap_create();
initAndQueryByNumReactant_c(options, results);
// XXX: it would probably would be more natural to make a method that queries
// all the reactions
// associated with a given species
if (mapvectormap_size(results) > 0) {
rx = new_reaction();
initializeNFSimReaction(state, rx, 2, results, reacA, reacB);
/*int result = process_bimolecular(reacA, reacB, rx, orientA, orientB,*/
/* matching_rxns, num_matching_rxns, 0);*/
int result = process_bimolecular(reacA, reacB, rx, orientA, orientB,
matching_rxns, num_matching_rxns);
if (result == 1)
num_matching_rxns++;
}
// store value in hashmap
error = hashmap_put_nohash(reaction_map, reactionHash, reactionHash, rx);
// add_to_cache(reaction_key, rx);
// CLEANUP
// delete_reactantQueryResults(query2);
mapvectormap_delete(results);
return num_matching_rxns;
}
/*
is_surface: true if there is a surface reactant
*/
int adjust_rates_nfsim(struct volume *state, struct rxn *rx, bool is_surface) {
double pb_factor = 0.0;
// int max_num_surf_products = set_product_geometries(path, rx, prod);
pb_factor = compute_pb_factor(
state->time_unit, state->length_unit, state->grid_density,
state->rx_radius_3d /
state->r_length_unit, // transform back to a unitless scale
&state->rxn_flags,
&state->create_shared_walls_info_flag, rx,
is_surface); // max_num_surf_products);
rx->pb_factor = pb_factor;
// mcell_log("!!!pb_factor %.10e",pb_factor);
// JJT: balance out rate (code from scale_rxn_probabilities)
// extracted because we only want to change the rate for one path
double rate;
for (int i = 0; i < rx->n_pathways; i++) {
// if (!rx->rates || !rx->rates[i]) {
rate = pb_factor * rx->cum_probs[i];
//mcell_log("!!%s %.10e %.10e", rx->external_reaction_data[i].reaction_name,
// rx->cum_probs[i], rate);
//} else
// rate = 0.0;
rx->cum_probs[i] = rate;
}
return 0;
/*if (scale_rxn_probabilities(&state->reaction_prob_limit_flag, state->notify,
path, rx, pb_factor))
return 1;*/
}
int initializeNFSimReaction(struct volume *state, struct rxn *r,
int n_reactants, void *results,
struct abstract_molecule *reacA,
struct abstract_molecule *reacB) {
char **resultKeys = mapvectormap_getKeys(results);
void *headComplex = mapvectormap_get(results, resultKeys[0]);
// we know that it only contains one result
int keysize = mapvectormap_size(results);
int headNumAssociatedReactions = mapvector_size(headComplex);
state->n_NFSimPReactions += headNumAssociatedReactions;
r->cum_probs = CHECKED_MALLOC_ARRAY(double, headNumAssociatedReactions,
"cumulative probabilities");
r->external_reaction_data = CHECKED_MALLOC_ARRAY(
struct external_reaction_datastruct, headNumAssociatedReactions,
"external reaction names");
r->n_pathways = headNumAssociatedReactions;
r->product_idx = CHECKED_MALLOC_ARRAY(u_int, headNumAssociatedReactions + 1,
"the different possible products");
r->product_idx_aux = CHECKED_MALLOC_ARRAY(int, headNumAssociatedReactions + 1,
"the different possible products");
// r->product_graph_pattern =
// CHECKED_MALLOC_ARRAY(char**,query2.numOfAssociatedReactions[0],
// "graph patterns of the possible
// products");
r->reactant_graph_data =
CHECKED_MALLOC_ARRAY(struct graph_data *, n_reactants,
"graph patterns of the possible products");
r->reactant_graph_data[0] = reacA->graph_data;
if (reacB) {
r->reactant_graph_data[1] = reacB->graph_data;
}
r->product_graph_data =
CHECKED_MALLOC_ARRAY(struct graph_data **, headNumAssociatedReactions,
"graph patterns of the possible products");
r->nfsim_players =
CHECKED_MALLOC_ARRAY(struct species **, headNumAssociatedReactions,
"products associated to each path");
r->nfsim_geometries =
CHECKED_MALLOC_ARRAY(short *, headNumAssociatedReactions,
"geometries associated to each path");
memset(r->nfsim_players, 0,
sizeof(struct species **) * headNumAssociatedReactions);
r->n_reactants = n_reactants;
// XXX:do we really have to go over all of them or do we need to filter out
// repeats?
// for (int i=0; i<query2.numOfResults; i++){
void *pathInformation;
for (int path = 0; path < headNumAssociatedReactions; path++) {
pathInformation = mapvector_get(headComplex, path);
r->cum_probs[path] = atof(map_get(pathInformation, "rate"));
r->external_reaction_data[path].reaction_name =
strdup(map_get(pathInformation, "name"));
r->external_reaction_data[path].resample = 0;
if (strcmp(map_get(pathInformation, "resample"), "true") == 0)
r->external_reaction_data[path].resample = 1;
r->product_idx[path] = 0;
r->product_idx_aux[path] = -1;
}
// XXX: is this necessary?
// temporarily initialize reaction list with nfsim_players
r->players = CHECKED_MALLOC_ARRAY(struct species *, n_reactants,
"reaction players array");
r->geometries =
CHECKED_MALLOC_ARRAY(short, n_reactants, "geometry players array");
r->players[0] = reacA->properties;
r->geometries[0] = 0;
if (reacB != NULL) {
r->players[1] = reacB->properties;
r->geometries[1] = 0;
}
// nfsim diffusion function, depending on whether the user wants us to do
// this.
initialize_rxn_diffusion_functions(r);
bool orientation_flag1 = 0, orientation_flag2 = 0;
int reactantOrientation1, reactantOrientation2;
calculate_reactant_orientation(reacA, reacB, &orientation_flag1,
&orientation_flag2, &reactantOrientation1,
&reactantOrientation2);
if (orientation_flag1) {
r->geometries[0] = reactantOrientation1;
}
if (reacB && orientation_flag2) {
r->geometries[1] = reactantOrientation2;
}
// adjust reaction probabilities
/*if (reacB != NULL)
mcell_log("++++ %s %s", reacA->graph_data->graph_pattern,
reacB->graph_data->graph_pattern);
else
mcell_log("---- %s ", reacA->graph_data->graph_pattern);*/
adjust_rates_nfsim(state, r, orientation_flag1 & orientation_flag2);
// calculate cummulative probabilities
for (int n_pathway = 1; n_pathway < r->n_pathways; ++n_pathway) {
r->cum_probs[n_pathway] += r->cum_probs[n_pathway - 1];
}
// assert(r->cum_probs[r->n_pathways-1] <= 1.0);
if (r->n_pathways > 0)
r->min_noreaction_p = r->max_fixed_p = r->cum_probs[r->n_pathways - 1];
else
r->min_noreaction_p = r->max_fixed_p = 1.0;
// cleanup
for (int i = 0; i < keysize; i++)
free(resultKeys[i]);
free(resultKeys);
return 0;
}
struct rxn *pick_unimolecular_reaction_nfsim(struct volume *state,
struct abstract_molecule *am) {
int error;
struct rxn *rx = NULL;
if (reaction_map == NULL)
reaction_map = hashmap_new();
// memset(&reaction_key[0], 0, sizeof(reaction_key));
// sprintf(reaction_key,"%s",am->graph_pattern);
// sprintf(reaction_key,"%lu",am->graph_pattern_hash);
// check in the hashmap in case this is a reaction we have encountered before
error =
hashmap_get_nohash(reaction_map, am->graph_data->graph_pattern_hash,
am->graph_data->graph_pattern_hash, (void **)(&rx));
// error = find_in_cache(reaction_key, rx);
if (error == MAP_OK) {
return rx;
}
// if(error != -1)
// return rx;
// otherwise build the object
queryOptions options = initializeNFSimQueryForUnimolecularReactions(am);
// reset, init, query the nfsim system
void *results = mapvectormap_create();
initAndQueryByNumReactant_c(options, results);
// XXX: it would probably would be more natural to make a method that queries
// all the reactions
// associated with a given species
if (mapvectormap_size(results) > 0) {
rx = new_reaction();
initializeNFSimReaction(state, rx, 1, results, am, NULL);
}
// store newly created reaction in the hashmap
error = hashmap_put_nohash(reaction_map, am->graph_data->graph_pattern_hash,
am->graph_data->graph_pattern_hash, rx);
// add_to_cache(reaction_key, rx);
// CLEANUP
mapvectormap_delete(results);
return rx;
// delete_reactantQueryResults(query2);
}
| C |
3D | mcellteam/mcell | src/mcell_viz.c | .c | 8,245 | 230 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include "sym_table.h"
#include "mcell_species.h"
#include "mcell_viz.h"
#include "mcell_misc.h"
#include "logging.h"
static int select_viz_molecules(struct mcell_species *mol_viz_list,
struct viz_output_block *vizblk);
static struct frame_data_list *create_viz_frame(long long iterations,
long long start, long long end,
long long step);
/*************************************************************************
mcell_create_viz_output:
Create a new set of viz output.
In: state: MCell state
filename: the path and filename prefix where the viz data will be
(e.g. "./viz_data/my_viz")
mol_viz_list: a list of the molecules to be visualized
start: the first frame of the viz data
end: the last frame of the viz data
step: the delta between iterations
Out: Returns 1 on error and 0 on success
Note: Right now, only iterations (not time points) can be specified.
*************************************************************************/
MCELL_STATUS
mcell_create_viz_output(MCELL_STATE *state, const char *filename,
struct mcell_species *mol_viz_list, long long start,
long long end, long long step, bool ascii_output) {
struct viz_output_block *vizblk = CHECKED_MALLOC_STRUCT(
struct viz_output_block, "visualization data output parameters");
if (vizblk == NULL)
return MCELL_FAIL;
mcell_new_viz_output_block(vizblk);
// In principal, it's possible to have multiple viz blocks, but this isn't
// supported in the API yet.
vizblk->next = state->viz_blocks;
state->viz_blocks = vizblk;
// Only CELLBLENDER mode is supported right now
vizblk->viz_mode = ascii_output ? ASCII_MODE : CELLBLENDER_MODE_V1;
// Set the viz output path and filename prefix
vizblk->file_prefix_name = CHECKED_STRDUP(filename, "file_prefix_name");
// Select which molecules will be visualized
if (select_viz_molecules(mol_viz_list, vizblk))
return MCELL_FAIL;
// Select which iterations will be visualized
struct frame_data_list *new_frame =
create_viz_frame(state->iterations, start, end, step);
if (new_frame == NULL)
return MCELL_FAIL;
new_frame->next = NULL;
state->viz_blocks->frame_data_head = new_frame;
return MCELL_SUCCESS;
}
/**************************************************************************
mcell_new_viz_output_block:
Build a new VIZ output block, containing parameters for an output set for
visualization.
**************************************************************************/
void mcell_new_viz_output_block(struct viz_output_block *vizblk) {
vizblk->frame_data_head = NULL;
vizblk->viz_mode = VIZ_MODE_INVALID;
vizblk->file_prefix_name = NULL;
vizblk->viz_output_flag = 0;
vizblk->species_viz_states = NULL;
if (pointer_hash_init(&vizblk->parser_species_viz_states, 32))
mcell_allocfailed("Failed to initialize viz species states table.");
}
/**************************************************************************
mcell_mcell_create_viz_frame:
Create a frame for output in the visualization.
In: time_type: either OUTPUT_BY_TIME_LIST or OUTPUT_BY_ITERATION_LIST
type: the type (MOL_POS, etc.)
iteration_list: list of iterations/times at which to output
Out: the frame_data_list object, if successful, or NULL if we ran out of
memory
**************************************************************************/
struct frame_data_list *
mcell_create_viz_frame(int time_type, int type,
struct num_expr_list *iteration_list) {
struct frame_data_list *fdlp;
fdlp = CHECKED_MALLOC_STRUCT(struct frame_data_list, "VIZ_OUTPUT frame data");
if (fdlp == NULL)
return NULL;
fdlp->list_type = (enum output_timer_type_t)time_type;
fdlp->type = (enum viz_frame_type_t)type;
fdlp->viz_iteration = -1;
fdlp->n_viz_iterations = 0;
fdlp->iteration_list = iteration_list;
fdlp->curr_viz_iteration = iteration_list;
return fdlp;
}
/**************************************************************************
mcell_set_molecule_viz_state:
Sets a flag on a viz block, requesting that a molecule is visualized.
In: vizblk: the viz block to check
specp: the molecule species
viz_state: the desired viz state
Out: 0 on success, 1 on failure
**************************************************************************/
MCELL_STATUS
mcell_set_molecule_viz_state(struct viz_output_block *vizblk,
struct species *specp, int viz_state) {
/* Make sure not to override a specific state with a generic state. */
if (viz_state == INCLUDE_OBJ) {
void *const exclude = (void *)(intptr_t)EXCLUDE_OBJ;
void *oldval = pointer_hash_lookup_ext(&vizblk->parser_species_viz_states,
specp, specp->hashval, exclude);
if (oldval != exclude)
return 0;
} else
vizblk->viz_output_flag |= VIZ_MOLECULES_STATES;
/* Store new value in the hashtable or die trying. */
void *val = (void *)(intptr_t)viz_state;
assert(viz_state == (int)(intptr_t)val);
if (pointer_hash_add(&vizblk->parser_species_viz_states, specp,
specp->hashval, val)) {
mcell_allocfailed(
"Failed to store viz state for molecules of species '%s'.",
specp->sym->name);
return MCELL_FAIL;
}
return MCELL_SUCCESS;
}
/******************************************************************************
*
* static helper functions
*
******************************************************************************/
int select_viz_molecules(struct mcell_species *mol_viz_list,
struct viz_output_block *vizblk) {
// Select individual molecules to visualize
struct mcell_species *current_molecule;
for (current_molecule = mol_viz_list; current_molecule != NULL;
current_molecule = current_molecule->next) {
struct species *specp = (struct species *)current_molecule->mol_type->value;
if (mcell_set_molecule_viz_state(vizblk, specp, INCLUDE_OBJ))
return 1;
}
return 0;
}
struct frame_data_list *create_viz_frame(long long iterations, long long start,
long long end, long long step) {
struct num_expr_list_head *list =
CHECKED_MALLOC_STRUCT(struct num_expr_list_head, "numeric list head");
if (list == NULL)
return NULL;
list->value_head = NULL;
list->value_tail = NULL;
list->value_count = 0;
list->shared = 0;
// Build a list of iterations for VIZ output
if (end > iterations)
end = iterations;
for (long long current = start; current <= end; current += step) {
struct num_expr_list *nel =
CHECKED_MALLOC_STRUCT(struct num_expr_list, "VIZ_OUTPUT iteration");
if (nel == NULL) {
mcell_free_numeric_list(list->value_head);
free(list);
return NULL;
}
++list->value_count;
if (list->value_tail)
list->value_tail = list->value_tail->next = nel;
else
list->value_head = list->value_tail = nel;
list->value_tail->value = current;
list->value_tail->next = NULL;
}
// Sorting is unnecessary at the moment
// mcell_sort_numeric_list(list->value_head);
// struct num_expr_list *times_sorted = list->value_head;
// Create the viz frames using the list of sorted times
struct frame_data_list *new_frame;
if ((new_frame = mcell_create_viz_frame(
OUTPUT_BY_ITERATION_LIST, ALL_MOL_DATA, list->value_head)) == NULL) {
free(list);
return NULL;
}
free(list);
return new_frame;
}
| C |
3D | mcellteam/mcell | src/mcell_init.h | .h | 1,765 | 55 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include "mcell_structs.h"
/* status of libMCell API calls */
typedef int MCELL_STATUS;
#define MCELL_SUCCESS 0
#define MCELL_FAIL 1
/* state of mcell simulation */
typedef struct volume MCELL_STATE;
void mcell_set_seed(MCELL_STATE *state, int seed);
void mcell_set_with_checks_flag(MCELL_STATE *state, int value);
void mcell_set_randomize_smol_pos(MCELL_STATE *state, int value);
MCELL_STATE *mcell_create(void);
MCELL_STATUS mcell_init_state(MCELL_STATE *state);
MCELL_STATUS mcell_init_simulation(MCELL_STATE *state);
MCELL_STATUS mcell_redo_geom(MCELL_STATE *state);
MCELL_STATUS mcell_init_read_checkpoint_time_and_iteration(MCELL_STATE *state);
MCELL_STATUS mcell_init_read_checkpoint(MCELL_STATE *state);
MCELL_STATUS mcell_init_output(MCELL_STATE *state);
MCELL_STATUS mcell_set_partition(MCELL_STATE *state, int dim,
struct num_expr_list_head *head);
MCELL_STATUS mcell_set_time_step(MCELL_STATE *state, double step);
MCELL_STATUS mcell_set_iterations(MCELL_STATE *state, long long iterations);
MCELL_STATUS mcell_silence_notifications(MCELL_STATE *state);
MCELL_STATUS mcell_enable_notifications(MCELL_STATE *state);
MCELL_STATUS mcell_silence_warnings(MCELL_STATE *state);
MCELL_STATUS mcell_enable_warnings(MCELL_STATE *state);
| Unknown |
3D | mcellteam/mcell | src/react_cond.c | .c | 22,391 | 629 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "logging.h"
#include "rng.h"
#include "react.h"
#include "vol_util.h"
#include "debug_config.h"
/*************************************************************************
timeof_unimolecular:
In: the reaction we're testing
Out: double containing the number of timesteps until the reaction occurs
*************************************************************************/
double timeof_unimolecular(struct rxn *rx, struct abstract_molecule *a,
struct rng_state *rng) {
double k_tot = rx->max_fixed_p;
double p = rng_dbl(rng);
if ((k_tot <= 0) || (!distinguishable(p, 0, EPS_C)))
return FOREVER;
return -log(p) / k_tot;
}
/*************************************************************************
which_unimolecular:
In: the reaction we're testing
Out: int containing which unimolecular reaction occurs (one must occur)
*************************************************************************/
int which_unimolecular(struct rxn *rx, struct abstract_molecule *a,
struct rng_state *rng) {
if (rx->n_pathways == 1
#ifdef MCELL3_UNIMOL_RX_ABSORB_NO_RNG
|| rx->n_pathways == RX_ABSORB_REGION_BORDER
#endif
) {
return 0;
}
int max = rx->n_pathways - 1;
double match = rng_dbl(rng);
if (rx->n_pathways < 0) {
// related to MCELL3_UNIMOL_RX_ABSORB_NO_RNG
// calling RNG to maintain compatibility but we must avoid invalid memory access
return 0;
}
match = match * rx->cum_probs[max];
return binary_search_double(rx->cum_probs, match, max, 1);
}
/*************************************************************************
binary_search_double
In: A: A pointer to an array of doubles
match: The value to match in the array
max_idx: Initially, the size of the array
mult: A multiplier for the comparison to the match.
Set to 1 if not needed.
Out: Returns the index of the match in the array
Note: This should possibly be moved to util.c
*************************************************************************/
int binary_search_double(double *A, double match, int max_idx, double mult) {
int min_idx = 0;
while (max_idx - min_idx > 1) {
int mid_idx = (max_idx + min_idx) / 2;
if (match > (A[mid_idx] * mult))
min_idx = mid_idx;
else
max_idx = mid_idx;
}
if (match > A[min_idx] * mult)
return max_idx;
else
return min_idx;
}
/*************************************************************************
test_bimolecular
In: the reaction we're testing
a scaling coefficient depending on how many timesteps we've
moved at once (1.0 means one timestep) and/or missing interaction area
local probability factor (positive only for the reaction between two
surface molecules, otherwise equal to zero)
reaction partners
Out: RX_NO_RX if no reaction occurs
int containing which reaction pathway to take if one does occur
Note: If this reaction does not return RX_NO_RX, then we update
counters appropriately assuming that the reaction does take place.
*************************************************************************/
int test_bimolecular(struct rxn *rx, double scaling, double local_prob_factor,
struct abstract_molecule *a1, struct abstract_molecule *a2,
struct rng_state *rng) {
if (a1 != NULL && a2 != NULL) {
assert(periodic_boxes_are_identical(a1->periodic_box, a2->periodic_box));
}
/* rescale probabilities for the case of the reaction
between two surface molecules */
double min_noreaction_p = rx->min_noreaction_p;
if (local_prob_factor > 0) {
min_noreaction_p = rx->min_noreaction_p * local_prob_factor;
}
/* Check if we missed any reactions
Instead of scaling rx->cum_probs array we scale random probability */
double p = 0.0; /* random number probability */
if (min_noreaction_p < scaling) /* Definitely CAN scale enough */
{
/* Instead of scaling rx->cum_probs array we scale random probability */
p = rng_dbl(rng) * scaling;
if (p >= min_noreaction_p)
return RX_NO_RX;
} else /* May or may not scale enough. check varying pathways. */
{
double max_p = rx->cum_probs[rx->n_pathways - 1];
if (local_prob_factor > 0)
max_p *= local_prob_factor;
if (max_p >= scaling) /* we cannot scale enough. add missed rxns */
{
/* How may reactions will we miss? */
if (scaling == 0.0)
rx->n_skipped += GIGANTIC;
else
rx->n_skipped += (max_p / scaling) - 1.0;
/* Keep the proportions of outbound pathways the same. */
p = rng_dbl(rng) * max_p;
} else /* we can scale enough */
{
/* Instead of scaling rx->cum_probs array we scale random probability */
p = rng_dbl(rng) * scaling;
if (p >= max_p)
return RX_NO_RX;
}
}
#ifdef DEBUG_REACTION_PROBABILITIES
mcell_log(
"test_bimolecular: p = %.8f, scaling = %.8f, min_noreaction_p = %.8f, local_prob_factor = %.8f",
p, scaling, min_noreaction_p, local_prob_factor
);
#endif
/* If we have only fixed pathways... */
int M = rx->n_pathways - 1;
if (local_prob_factor > 0)
return binary_search_double(rx->cum_probs, p, M, local_prob_factor);
else
return binary_search_double(rx->cum_probs, p, M, 1);
}
/*************************************************************************
test_many_bimolecular:
In: an array of reactions we're testing
scaling coefficients depending on how many timesteps we've moved
at once (1.0 means one timestep) and/or missing interaction areas
local probability factor for the corresponding reactions
the number of elements in the array of reactions
placeholder for the chosen pathway in the reaction (works as return
value)
a flag to indicate if
Out: RX_NO_RX if no reaction occurs
index in the reaction array corresponding to which reaction occurs
if one does occur
Note: If this reaction does not return RX_NO_RX, then we update
counters appropriately assuming that the reaction does take place.
Note: this uses only one call to get a random double, so you can't
effectively sample events that happen less than 10^-9 of the
time (for 32 bit random number).
NOTE: This function was merged with test_many_bimolecular_all_neighbors.
These two functions were almost identical, and the behavior of the
"all_neighbors" version is preserved with a flag that can be passed in.
For reactions between two surface molecules, set this flag to 1. For
such reactions local_prob_factor > 0.
*************************************************************************/
int test_many_bimolecular(struct rxn **rx, double *scaling,
double local_prob_factor, int n, int *chosen_pathway,
struct rng_state *rng,
int all_neighbors_flag) {
std::vector<double> rxp(2 * n); /* array of cumulative rxn probabilities */
struct rxn *my_rx;
int i; /* index in the array of reactions - return value */
int m, M;
double p, f;
if (all_neighbors_flag && local_prob_factor <= 0)
mcell_internal_error("Local probability factor = %g in the function "
"'test_many_bimolecular_all_neighbors().",
local_prob_factor);
if (n == 1) {
if (all_neighbors_flag)
return test_bimolecular(rx[0], scaling[0], local_prob_factor, NULL, NULL, rng);
else
return test_bimolecular(rx[0], 0, scaling[0], NULL, NULL, rng);
}
/* Note: lots of division here, if we're CPU-bound,could invert the
definition of scaling_coefficients */
if (all_neighbors_flag && local_prob_factor > 0) {
rxp[0] = (rx[0]->max_fixed_p) * local_prob_factor / scaling[0];
} else {
rxp[0] = rx[0]->max_fixed_p / scaling[0];
}
for (i = 1; i < n; i++) {
if (all_neighbors_flag && local_prob_factor > 0) {
rxp[i] =
rxp[i - 1] + (rx[i]->max_fixed_p) * local_prob_factor / scaling[i];
} else {
rxp[i] = rxp[i - 1] + rx[i]->max_fixed_p / scaling[i];
}
}
if (rxp[n - 1] > 1.0) {
f = rxp[n - 1] - 1.0; /* Number of failed reactions */
for (i = 0; i < n; i++) /* Distribute failures */
{
if (all_neighbors_flag && local_prob_factor > 0) {
rx[i]->n_skipped += f * ((rx[i]->cum_probs[rx[i]->n_pathways - 1]) *
local_prob_factor) /
rxp[n - 1];
} else {
rx[i]->n_skipped +=
f * (rx[i]->cum_probs[rx[i]->n_pathways - 1]) / rxp[n - 1];
}
}
p = rng_dbl(rng) * rxp[n - 1];
} else {
p = rng_dbl(rng);
if (p > rxp[n - 1])
return RX_NO_RX;
}
/* Pick the reaction that happens */
i = binary_search_double(&rxp[0], p, n - 1, 1);
my_rx = rx[i];
if (i > 0)
p = (p - rxp[i - 1]);
p = p * scaling[i];
/* Now pick the pathway within that reaction */
M = my_rx->n_pathways - 1;
if (all_neighbors_flag && local_prob_factor > 0)
m = binary_search_double(my_rx->cum_probs, p, M, local_prob_factor);
else
m = binary_search_double(my_rx->cum_probs, p, M, 1);
*chosen_pathway = m;
return i;
}
/*************************************************************************
test_intersect
In: the reaction we're testing
a probability multiplier depending on how many timesteps we've
moved at once (1.0 means one timestep)
Out: RX_NO_RX if no reaction occurs (assume reflection)
int containing which reaction occurs if one does occur
Note: If not RX_NO_RX, and not the trasparency shortcut, then we
update counters assuming the reaction will take place.
*************************************************************************/
int test_intersect(struct rxn *rx, double scaling, struct rng_state *rng) {
double p;
if (rx->n_pathways <= RX_SPECIAL)
return rx->n_pathways;
if (rx->cum_probs[rx->n_pathways - 1] > scaling) {
if (scaling <= 0.0)
rx->n_skipped += GIGANTIC;
else
rx->n_skipped += rx->cum_probs[rx->n_pathways - 1] / scaling - 1.0;
p = rng_dbl(rng) * rx->cum_probs[rx->n_pathways - 1];
} else {
p = rng_dbl(rng) * scaling;
if (p > rx->cum_probs[rx->n_pathways - 1])
return RX_NO_RX;
}
int M = rx->n_pathways - 1;
if (p > rx->cum_probs[M])
return RX_NO_RX;
int max = rx->n_pathways - 1;
double match = rng_dbl(rng);
match = match * rx->cum_probs[max];
return binary_search_double(rx->cum_probs, match, max, 1);
}
/*************************************************************************
test_many_intersect:
In: an array of reactions we're testing
a probability multiplier depending on how many timesteps we've
moved at once (1.0 means one timestep)
the number of elements in the array of reactions
placeholder for the chosen pathway in the reaction (return value)
Out: RX_NO_RX if no reaction occurs (assume reflection)
index in the reaction array if reaction does occur
Note: If not RX_NO_RX, and not the trasparency shortcut, then we
update counters assuming the reaction will take place.
*************************************************************************/
int test_many_intersect(struct rxn **rx, double scaling, int n,
int *chosen_pathway, struct rng_state *rng) {
if (n == 1)
return test_intersect(rx[0], scaling, rng);
// array of cumulative rxn probabilities
std::vector<double> rxp(n);
rxp[0] = rx[0]->max_fixed_p / scaling;
int i; /* index in the array of reactions - return value */
for (i = 1; i < n; i++) {
rxp[i] = rxp[i - 1] + rx[i]->max_fixed_p / scaling;
}
double p;
if (rxp[n - 1] > 1.0) {
double f = rxp[n - 1] - 1.0; /* Number of failed reactions */
for (i = 0; i < n; i++) /* Distribute failures */
{
rx[i]->n_skipped +=
f * (rx[i]->cum_probs[rx[i]->n_pathways - 1]) / rxp[n - 1];
}
p = rng_dbl(rng) * rxp[n - 1];
} else {
p = rng_dbl(rng);
if (p > rxp[n - 1])
return RX_NO_RX;
}
/* Pick the reaction that happens */
i = binary_search_double(&rxp[0], p, n - 1, 1);
struct rxn *my_rx = rx[i];
if (i > 0)
p = (p - rxp[i - 1]);
p = p * scaling;
/* Now pick the pathway within that reaction */
*chosen_pathway =
binary_search_double(my_rx->cum_probs, p, my_rx->n_pathways - 1, 1);
return i;
}
/*************************************************************************
test_many_unimol:
In: an array of reactions we're testing
the number of elements in the array of reactions
abstract molecule that undergoes reaction
Out: NULL if no reaction occurs (safety check, do not expect to happen),
reaction object otherwise (one must always occur)
*************************************************************************/
struct rxn *test_many_unimol(struct rxn **rx, int n,
struct abstract_molecule *a,
struct rng_state *rng) {
if (n == 0) {
return NULL;
}
if (n == 1) {
return rx[0];
}
std::vector<double> rxp(n); /* array of cumulative rxn probabilities */
rxp[0] = rx[0]->max_fixed_p;
int i; /* index in the array of reactions - return value */
for (i = 1; i < n; i++) {
rxp[i] = rxp[i - 1] + rx[i]->max_fixed_p;
}
double p = rng_dbl(rng) * rxp[n - 1];
/* Pick the reaction that happens */
i = binary_search_double(&rxp[0], p, n - 1, 1);
return rx[i];
}
/*************************************************************************
check_probs:
In: A reaction struct
The current time
Out: No return value. Probabilities are updated if necessary.
Memory isn't reclaimed.
Note: This isn't meant for really heavy-duty use (multiple pathways
with rapidly changing rates)--if you want that, the code should
probably be rewritten to accumulate probability changes from the
list as it goes (and the list should be sorted by pathway, too).
Note: We're still displaying geometries here, rather than orientations.
Perhaps that should be fixed.
*************************************************************************/
void update_probs(struct volume *world, struct rxn *rx, double t) {
int j, k;
double dprob;
struct t_func *tv;
int did_something = 0;
double new_prob = 0;
for (tv = rx->prob_t; tv != NULL && tv->time < t; tv = tv->next) {
j = tv->path;
if (j == 0)
dprob = tv->value - rx->cum_probs[0];
else
dprob = tv->value - (rx->cum_probs[j] - rx->cum_probs[j - 1]);
for (k = tv->path; k < rx->n_pathways; k++)
rx->cum_probs[k] += dprob;
rx->max_fixed_p += dprob;
rx->min_noreaction_p += dprob;
did_something++;
/* Changing probabilities is easy. Now lots of logic to notify user, or
* not. */
if (world->notify->time_varying_reactions == NOTIFY_FULL &&
rx->cum_probs[j] >= world->notify->reaction_prob_notify) {
if (j == 0)
new_prob = rx->cum_probs[0];
else
new_prob = rx->cum_probs[j] - rx->cum_probs[j - 1];
if (world->chkpt_seq_num > 1) {
if (tv->next != NULL) {
if (tv->next->time < t)
continue; /* do not print messages */
}
}
if (rx->n_reactants == 1) {
mcell_log_raw("Probability %.4e set for %s[%d] -> ", new_prob,
rx->players[0]->sym->name, rx->geometries[0]);
} else if (rx->n_reactants == 2) {
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] -> ", new_prob,
rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1]);
} else {
mcell_log_raw("Probability %.4e set for %s[%d] + %s[%d] + %s[%d] -> ",
new_prob, rx->players[0]->sym->name, rx->geometries[0],
rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
}
for (unsigned int n_product = rx->product_idx[j];
n_product < rx->product_idx[j + 1]; n_product++) {
if (rx->players[n_product] != NULL)
mcell_log_raw("%s[%d] ", rx->players[n_product]->sym->name,
rx->geometries[n_product]);
}
double time_secs = convert_iterations_to_seconds(
world->start_iterations, world->time_unit,
world->simulation_start_seconds, world->current_iterations);
mcell_log_raw("at iteration %lld with time %.9f", world->current_iterations, time_secs);
mcell_log_raw("\n");
}
if ((new_prob > 1.0) && (!world->reaction_prob_limit_flag)) {
world->reaction_prob_limit_flag = 1;
}
}
rx->prob_t = tv;
if (!did_something)
return;
/* Now we have to see if we need to warn the user. */
if (rx->cum_probs[rx->n_pathways - 1] > world->notify->reaction_prob_warn) {
FILE *warn_file = mcell_get_log_file();
if (world->notify->high_reaction_prob != WARN_COPE) {
if (world->notify->high_reaction_prob == WARN_ERROR) {
warn_file = mcell_get_error_file();
fprintf(warn_file, "Error: High ");
} else
fprintf(warn_file, "Warning: High ");
if (rx->n_reactants == 1) {
fprintf(warn_file, "total probability %.4e for %s[%d] -> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0]);
} else if (rx->n_reactants == 2) {
fprintf(
warn_file, "total probability %.4e for %s[%d] + %s[%d] -> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name, rx->geometries[1]);
} else {
fprintf(warn_file,
"total probability %.4e for %s[%d] + %s[%d] + %s[%d] -> ...\n",
rx->cum_probs[rx->n_pathways - 1], rx->players[0]->sym->name,
rx->geometries[0], rx->players[1]->sym->name, rx->geometries[1],
rx->players[2]->sym->name, rx->geometries[2]);
}
}
if (world->notify->high_reaction_prob == WARN_ERROR)
mcell_die();
}
return;
}
/*************************************************************************
test_many_reactions_all_neighbors:
In: an array of reactions we're testing
an array of scaling coefficients depending on how many timesteps
we've moved at once (1.0 means one timestep) and/or missing
interaction areas
an array of local probability factors for the corresponding reactions
the number of elements in the array of reactions
placeholder for the chosen pathway in the reaction (works as return
value)
Out: RX_NO_RX if no reaction occurs
index in the reaction array corresponding to which reaction occurs
if one does occur
Note: If this reaction does not return RX_NO_RX, then we update
counters appropriately assuming that the reaction does take place.
Note: this uses only one call to get a random double, so you can't
effectively sample events that happen less than 10^-9 of the
time (for 32 bit random number).
NOTE: This function should be used for now only for the reactions
between three surface molecules.
*************************************************************************/
int test_many_reactions_all_neighbors(struct rxn **rx, double *scaling,
double *local_prob_factor, int n,
int *chosen_pathway,
struct rng_state *rng) {
if (local_prob_factor == NULL)
mcell_internal_error("There is no local probability factor information in "
"the function 'test_many_reactions_all_neighbors().");
if (n == 1)
return test_bimolecular(rx[0], scaling[0], local_prob_factor[0], NULL, NULL, rng);
std::vector<double> rxp(n); /* array of cumulative rxn probabilities */
if (local_prob_factor[0] > 0) {
rxp[0] = (rx[0]->max_fixed_p) * local_prob_factor[0] / scaling[0];
} else {
rxp[0] = rx[0]->max_fixed_p / scaling[0];
}
// i: index in the array of reactions - return value
for (int i = 1; i < n; i++) {
if (local_prob_factor[i] > 0) {
rxp[i] =
rxp[i - 1] + (rx[i]->max_fixed_p) * local_prob_factor[i] / scaling[i];
} else {
rxp[i] = rxp[i - 1] + rx[i]->max_fixed_p / scaling[i];
}
}
double p;
if (rxp[n - 1] > 1.0) {
double f = rxp[n - 1] - 1.0; /* Number of failed reactions */
for (int i = 0; i < n; i++) /* Distribute failures */
{
if (local_prob_factor[i] > 0) {
rx[i]->n_skipped += f * ((rx[i]->cum_probs[rx[i]->n_pathways - 1]) *
local_prob_factor[i]) /
rxp[n - 1];
} else {
rx[i]->n_skipped +=
f * (rx[i]->cum_probs[rx[i]->n_pathways - 1]) / rxp[n - 1];
}
}
p = rng_dbl(rng) * rxp[n - 1];
} else {
p = rng_dbl(rng);
if (p > rxp[n - 1])
return RX_NO_RX;
}
/* Pick the reaction that happens */
int i = binary_search_double(&rxp[0], p, n - 1, 1);
struct rxn *my_rx = rx[i];
double my_local_prob_factor = local_prob_factor[i];
if (i > 0)
p = (p - rxp[i - 1]);
p = p * scaling[i];
/* Now pick the pathway within that reaction */
int M = my_rx->n_pathways - 1;
if (my_local_prob_factor > 0) {
*chosen_pathway =
binary_search_double(my_rx->cum_probs, p, M, my_local_prob_factor);
} else {
*chosen_pathway = binary_search_double(my_rx->cum_probs, p, M, 1);
}
return i;
}
| C |
3D | mcellteam/mcell | src/mcell_init.c | .c | 23,925 | 720 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#if defined(__linux__)
#define _GNU_SOURCE 1
#endif
#ifndef _WIN64
#include <sys/resource.h>
#endif
#include <stdlib.h>
#if defined(__linux__)
#include <fenv.h>
#endif
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <math.h>
#include "config.h"
#include "mcell_structs.h"
#include "chkpt.h"
#include "count_util.h"
#include "init.h"
#include "logging.h"
#include "sym_table.h"
#include "mcell_init.h"
#include "mcell_misc.h"
#include "mcell_reactions.h"
#include "dyngeom.h"
#include "chkpt.h"
//for nfsim initialization
#include "nfsim_func.h"
/* simple wrapper for executing the supplied function call. In case
* of an error returns with MCELL_FAIL and prints out error_message */
#define CHECKED_CALL(function, error_message) \
{ \
if (function) { \
mcell_log(error_message); \
return MCELL_FAIL; \
} \
}
// static helper functions
static int install_usr_signal_handlers(void);
static bool has_micro_rev_and_trimol_rxns(struct species **species_list,
int n_species, byte has_vol_rev, byte has_surf_rev);
/************************************************************************
*
* change the seed
*
************************************************************************/
void mcell_set_seed(MCELL_STATE *state, int seed) {
u_int signed_seed = (u_int) seed;
state->seed_seq = signed_seed;
rng_init(state->rng, state->seed_seq);
}
/************************************************************************
*
* set diverse flags
*
************************************************************************/
void mcell_set_with_checks_flag(MCELL_STATE *state, int value) {
assert(value == 0 || value == 1);
state->with_checks_flag = value;
}
void mcell_set_randomize_smol_pos(MCELL_STATE *state, int value) {
assert(value == 0 || value == 1);
state->randomize_smol_pos = value;
}
/************************************************************************
*
* function for initializing the main mcell simulator. MCELL_STATE
* keeps track of the state of the simulation.
*
* Returns NULL on error and a pointer to MCELL_STATE otherwise
*
************************************************************************/
MCELL_STATE *mcell_create() {
#ifdef _NDEBUG
// signal handlers
if (install_usr_signal_handlers()) {
return NULL;
}
#endif
// logging
mcell_set_log_file(stdout);
mcell_set_error_file(stderr);
MCELL_STATE *state = CHECKED_MALLOC_STRUCT_NODIE(struct volume, "world");
if (state == NULL) {
return NULL;
}
memset(state, 0, sizeof(struct volume));
#if defined(__linux__)
feenableexcept(FE_DIVBYZERO);
#endif
state->procnum = 0;
state->rx_hashsize = 0;
state->iterations = INT_MIN; /* indicates iterations not set */
state->chkpt_infile = NULL;
state->chkpt_outfile = NULL;
state->chkpt_init = 1;
state->log_freq =
ULONG_MAX; /* Indicates that this value has not been set by user */
state->seed_seq = 1;
state->with_checks_flag = 1;
state->nfsim_flag = 0; //JJT: NFsim flag
state->use_mcell4 = 0;
time_t begin_time_of_day;
time(&begin_time_of_day);
state->begin_timestamp = begin_time_of_day;
state->initialization_state = "initializing";
if (!(state->var_sym_table = init_symtab(1024))) {
mcell_log("Failed to initialize MDL variable symbol table.");
return NULL;
}
return state;
}
/************************************************************************
*
* function for initializing the intial simulation state (variables,
* notifications, data structures)
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_init_state(MCELL_STATE *state) {
CHECKED_CALL(
init_notifications(state),
"Unknown error while initializing user-notification data structures.");
CHECKED_CALL(init_variables(state),
"Unknown error while initializing system variables.");
CHECKED_CALL(init_data_structures(state),
"Unknown error while initializing system data structures.");
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for setting up all the internal data structure to get the
* simulation into a runnable state.
*
* NOTE: Before this function can be called the engine user code
* either needs to call
* - parse_input() to parse a valid MDL file or
* - the individiual API functions for adding model elements
* (molecules, geometry, ...)
*
* Returns 0 on sucess and 1 on error
*
************************************************************************/
MCELL_STATUS
mcell_init_simulation(MCELL_STATE *state) {
CHECKED_CALL(init_reactions(state), "Error initializing reactions.");
CHECKED_CALL(init_species(state), "Error initializing species.");
if (has_micro_rev_and_trimol_rxns(state->species_list, state->n_species,
state->volume_reversibility, state->surface_reversibility)) {
mcell_error("Tri-molecular reactions can not be combined with microscopic "
"reversibility turned on. Please set MICROSCOPIC_REVESIBILITY = NO");
}
if (state->notify->progress_report != NOTIFY_NONE)
mcell_log("Creating geometry (this may take some time)");
CHECKED_CALL(init_bounding_box(state), "Error initializing bounding box.");
CHECKED_CALL(init_partitions(state), "Error initializing partitions.");
CHECKED_CALL(init_vertices_walls(state),
"Error initializing vertices and walls.");
CHECKED_CALL(init_regions(state), "Error initializing regions.");
if (state->place_waypoints_flag) {
CHECKED_CALL(place_waypoints(state), "Error while placing waypoints.");
}
if (state->with_checks_flag && !state->use_mcell4 && !state->mdl2datamodel4) {
CHECKED_CALL(check_for_overlapped_walls(
state->rng, state->n_subvols, state->subvol),
"Error while checking for overlapped walls.");
}
if (!state->use_mcell4) {
// must not be called for mcell4 - this is done through releases
// and we must not have additional rng calls
CHECKED_CALL(init_surf_mols(state),
"Error while placing surface molecules on regions.");
}
CHECKED_CALL(init_releases(state->releaser), "Error while initializing release sites.");
// Only used with dynamic geometries
CHECKED_CALL(init_species_mesh_transp(state),
"Error while initializing species-mesh transparency list.");
CHECKED_CALL(init_counter_name_hash(
&state->counter_by_name, state->output_block_head),
"Error while initializing counter name hash.");
/*CHECKED_CALL(init_dynamic_geometry(state),*/
/* "Error while initializing scheduled changes in geometry.");*/
//hashmap where nfsim struct graph_data is stored
if(state->nfsim_flag){
initialize_graph_hashmap();
}
return MCELL_SUCCESS;
}
/************************************************************************
*
* Function for recreating the geometry when using dynamic meshes.
*
* NOTE: This entails destroying the existing geometry (and a number of related
* dependencies), reparsing the appropriate MDLs, and re-initializing the
* partitions, geometry, etc.
*
* Returns 1 on error and 0 on success
*
* NOTE: This is doing a little more than just destroying and reinitializing
* geometry, so it probably makes sense to rename this and/or split it up into
* multiple functions.
*
************************************************************************/
MCELL_STATUS
mcell_redo_geom(MCELL_STATE *state) {
// We set this mainly to take care of some issues with counting, triggers,
// memory cleanup.
state->dynamic_geometry_flag = 1;
CHECKED_CALL(reset_current_counts(
state->mol_sym_table,
state->count_hashmask,
state->count_hash),
"Error when reseting counters.");
struct vector3 llf;
struct vector3 urb;
if (state->periodic_box_obj) {
struct polygon_object* p = (struct polygon_object*)(state->periodic_box_obj->contents);
struct subdivided_box* sb = p->sb;
llf.x = sb->x[0];
llf.y = sb->y[0];
llf.z = sb->z[0];
urb.x = sb->x[1];
urb.y = sb->y[1];
urb.z = sb->z[1];
}
CHECKED_CALL(destroy_everything(state), "Error when freeing memory.");
// We need to reenable the ability to parse geometry
state->disable_polygon_objects = 0;
// Reparse the geometry and instantiations. Nothing else should be included
// in these other MDLs.
#ifdef NOSWIG
CHECKED_CALL(parse_input(state),
"An error occured during parsing of the mdl file.");
#endif
CHECKED_CALL(init_bounding_box(state), "Error initializing bounding box.");
// This should ideally be in destroy_everything
free(state->subvol);
if (state->periodic_box_obj) {
mcell_create_periodic_box(state, "PERIODIC_BOX_INST", &llf, &urb);
}
CHECKED_CALL(init_partitions(state), "Error initializing partitions.");
CHECKED_CALL(init_vertices_walls(state),
"Error initializing vertices and walls.");
CHECKED_CALL(init_regions(state), "Error initializing regions.");
if (state->place_waypoints_flag) {
CHECKED_CALL(place_waypoints(state), "Error while placing waypoints.");
}
if (state->with_checks_flag && !state->use_mcell4) {
CHECKED_CALL(check_for_overlapped_walls(
state->rng, state->n_subvols, state->subvol),
"Error while checking for overlapped walls.");
}
CHECKED_CALL(init_species_mesh_transp(state),
"Error while initializing species-mesh transparency list.");
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for reading elapsed time and iteration of our checkpoint
* if one should be loaded or exists
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_init_read_checkpoint_time_and_iteration(MCELL_STATE *state) {
if (state->chkpt_infile) {
CHECKED_CALL(load_checkpoint(state, true),
"Error while loading time and iteration from previous checkpoint.");
}
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for reading and initializing the checkpoint if requested
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_init_read_checkpoint(MCELL_STATE *state) {
// set up global state in chkpt.c. This is needed to provided
// the state for the signal triggered checkpointing
CHECKED_CALL(set_checkpoint_state(state),
"An error occured during setting the state of the checkpointing routine.");
if (state->chkpt_infile) { //state->chkpt_flag == 1) {
CHECKED_CALL(load_checkpoint(state, false),
"Error while loading previous checkpoint.");
long long exec_iterations;
CHECKED_CALL(init_checkpoint_state(state, &exec_iterations),
"Error while initializing checkpoint.");
CHECKED_CALL(reschedule_release_events(state),
"Error while rescheduling release events");
/* XXX This is a hack to be backward compatible with the previous
* MCell behaviour. Basically, as soon as exec_iterations <= 0
* MCell will stop and we emulate this by returning 1 even though
* this is not an error (as implied by returning 1). */
if (exec_iterations <= 0) {
mem_dump_stats(mcell_get_log_file());
return MCELL_FAIL;
}
} else {
state->chkpt_seq_num = 1;
}
if (state->chkpt_infile) {
}
// set the iteration time to the start time of the checkpoint
state->current_iterations = state->start_iterations;
return MCELL_SUCCESS;
}
/************************************************************************
*
* function for initializing the viz and reaction data output
*
* XXX: This function has to be called last, i.e. after the
* simulation has been initialized and checkpoint information
* been read.
*
* Returns 1 on error and 0 on success
*
************************************************************************/
MCELL_STATUS
mcell_init_output(MCELL_STATE *state) {
CHECKED_CALL(init_viz_data(state), "Error while initializing viz data.");
CHECKED_CALL(init_reaction_data(state),
"Error while initializing reaction data.");
CHECKED_CALL(init_timers(state), "Error initializing the simulation timers.");
// signal successful end of simulation
state->initialization_state = NULL;
return MCELL_SUCCESS;
}
// only for mcell4 initialization
static void set_vec3(struct vector3 *v, int dim_index, double value) {
switch (dim_index) {
case 0:
v->x = value;
break;
case 1:
v->y = value;
break;
case 2:
v->z = value;
break;
default:
assert(false);
}
}
/*************************************************************************
mcell_set_partition:
Set the partitioning in a particular dimension.
In: state: the simulation state
dim: the dimension whose partitions we'll set
head: the partitioning
Out: 0 on success, 1 on failure
*************************************************************************/
MCELL_STATUS mcell_set_partition(MCELL_STATE *state, int dim,
struct num_expr_list_head *head) {
/* Allocate array for partitions */
double *dblp = CHECKED_MALLOC_ARRAY(double, (head->value_count + 2),
"volume partitions");
if (dblp == NULL)
return MCELL_FAIL;
// MCell4
if (head->start_end_step_set) {
state->partitions_initialized = true; // setting for all dimensions, expecting that all partition dims are set
// ok, we got values directly from the parser, no problem to determine partition setup
double llf = head->start * state->r_length_unit;
double urb = head->end * state->r_length_unit;
// get approximate number of subparts the user requested
set_vec3(&state->num_subparts, dim, round((head->end - head->start) / head->step));
set_vec3(&state->partition_llf, dim, llf);
set_vec3(&state->partition_urb, dim, urb);
}
/* Copy partitions in sorted order to the array */
unsigned int num_values = 0;
dblp[num_values++] = -GIGANTIC;
struct num_expr_list *nel;
for (nel = head->value_head; nel != NULL; nel = nel->next)
dblp[num_values++] = nel->value * state->r_length_unit;
dblp[num_values++] = GIGANTIC;
qsort(dblp, num_values, sizeof(double), &double_cmp);
/* Copy the partitions into the model */
switch (dim) {
case X_PARTS:
if (state->x_partitions != NULL)
free(state->x_partitions);
state->nx_parts = num_values;
state->x_partitions = dblp;
break;
case Y_PARTS:
if (state->y_partitions != NULL)
free(state->y_partitions);
state->ny_parts = num_values;
state->y_partitions = dblp;
break;
case Z_PARTS:
if (state->z_partitions != NULL)
free(state->z_partitions);
state->nz_parts = num_values;
state->z_partitions = dblp;
break;
default:
UNHANDLED_CASE(dim);
}
if (!head->shared)
mcell_free_numeric_list(head->value_head);
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_set_iterations:
Set the number of iterations for the simulation.
In: state: the simulation state
iterations: number of iterations to run
Out: 0 on success; 1 on failure.
number of iterations is set.
*************************************************************************/
MCELL_STATUS
mcell_set_iterations(MCELL_STATE *state, long long iterations) {
if (iterations < 0) {
return MCELL_FAIL;
}
state->iterations = iterations;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_set_time_step:
Set the global timestep for the simulation.
In: state: the simulation state
step: timestep to set
Out: 0 on success; any other integer value is a failure.
global timestep is updated.
*************************************************************************/
MCELL_STATUS
mcell_set_time_step(MCELL_STATE *state, double step) {
if (step <= 0) {
return 2;
}
// Timestep was already set. Could introduce subtle problems if we let it
// change after defining the species, since it is used in calculations there.
if (distinguishable(state->time_unit, 0, EPS_C)) {
return 3;
}
state->time_unit = step;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_silence_notifications:
Silence notifications
In: state: the simulation state
Out: 0 on success; any other integer value is a failure.
*************************************************************************/
MCELL_STATUS
mcell_silence_notifications(MCELL_STATE *state) {
/*state->quiet_flag = 1;*/
state->notify->progress_report = NOTIFY_NONE;
state->notify->diffusion_constants = NOTIFY_NONE;
state->notify->reaction_probabilities = NOTIFY_NONE;
state->notify->time_varying_reactions = NOTIFY_NONE;
state->notify->reaction_prob_notify = 0.0;
state->notify->partition_location = NOTIFY_NONE;
state->notify->box_triangulation = NOTIFY_NONE;
state->notify->iteration_report = NOTIFY_NONE;
state->notify->custom_iteration_value = 0;
state->notify->release_events = NOTIFY_NONE;
state->notify->file_writes = NOTIFY_NONE;
state->notify->final_summary = NOTIFY_NONE;
state->notify->throughput_report = NOTIFY_NONE;
state->notify->checkpoint_report = NOTIFY_NONE;
state->notify->reaction_output_report = NOTIFY_NONE;
state->notify->volume_output_report = NOTIFY_NONE;
state->notify->viz_output_report = NOTIFY_NONE;
state->notify->molecule_collision_report = NOTIFY_NONE;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_enable_notifications:
Enable notifications
In: state: the simulation state
Out: 0 on success; any other integer value is a failure.
*************************************************************************/
MCELL_STATUS
mcell_enable_notifications(MCELL_STATE *state) {
state->notify->progress_report = NOTIFY_FULL;
state->notify->diffusion_constants = NOTIFY_BRIEF;
state->notify->reaction_probabilities = NOTIFY_FULL;
state->notify->time_varying_reactions = NOTIFY_FULL;
state->notify->reaction_prob_notify = 0.0;
state->notify->partition_location = NOTIFY_NONE;
state->notify->box_triangulation = NOTIFY_NONE;
state->notify->iteration_report = NOTIFY_FULL;
state->notify->custom_iteration_value = 0;
state->notify->release_events = NOTIFY_FULL;
state->notify->file_writes = NOTIFY_NONE;
state->notify->final_summary = NOTIFY_FULL;
state->notify->throughput_report = NOTIFY_FULL;
state->notify->checkpoint_report = NOTIFY_FULL;
state->notify->reaction_output_report = NOTIFY_NONE;
state->notify->volume_output_report = NOTIFY_NONE;
state->notify->viz_output_report = NOTIFY_NONE;
state->notify->molecule_collision_report = NOTIFY_NONE;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_enable_warnings:
Enable warnings
In: state: the simulation state
Out: 0 on success; any other integer value is a failure.
*************************************************************************/
MCELL_STATUS
mcell_enable_warnings(MCELL_STATE *state) {
state->notify->neg_diffusion = WARN_WARN;
state->notify->neg_reaction = WARN_WARN;
state->notify->high_reaction_prob = WARN_COPE;
state->notify->reaction_prob_warn = 1.0;
state->notify->close_partitions = WARN_WARN;
state->notify->degenerate_polys = WARN_WARN;
state->notify->overwritten_file = WARN_COPE;
state->notify->short_lifetime = WARN_WARN;
state->notify->short_lifetime_value = 50;
state->notify->missed_reactions = WARN_WARN;
state->notify->missed_reaction_value = 0.001;
state->notify->missed_surf_orient = WARN_ERROR;
state->notify->useless_vol_orient = WARN_WARN;
state->notify->mol_placement_failure = WARN_WARN;
state->notify->invalid_output_step_time = WARN_WARN;
state->notify->large_molecular_displacement = WARN_WARN;
state->notify->add_remove_mesh_warning = WARN_WARN;
return MCELL_SUCCESS;
}
/*************************************************************************
mcell_silence_warnings:
Silence warnings
In: state: the simulation state
Out: 0 on success; any other integer value is a failure.
*************************************************************************/
MCELL_STATUS
mcell_silence_warnings(MCELL_STATE *state) {
state->notify->neg_diffusion = WARN_COPE;
state->notify->neg_reaction = WARN_COPE;
state->notify->high_reaction_prob = WARN_COPE;
state->notify->close_partitions = WARN_COPE;
state->notify->degenerate_polys = WARN_COPE;
state->notify->overwritten_file = WARN_COPE;
state->notify->short_lifetime = WARN_COPE;
state->notify->missed_reactions = WARN_COPE;
state->notify->missed_surf_orient = WARN_ERROR;
state->notify->useless_vol_orient = WARN_COPE;
state->notify->mol_placement_failure = WARN_COPE;
state->notify->invalid_output_step_time = WARN_COPE;
state->notify->large_molecular_displacement = WARN_COPE;
state->notify->add_remove_mesh_warning = WARN_COPE;
return MCELL_SUCCESS;
}
/*****************************************************************************
*
* static helper functions
*
*****************************************************************************/
/***********************************************************************
* install_usr_signal_handlers:
*
* Set signal handlers for checkpointing on SIGUSR signals.
*
* In: None
* Out: 0 on success, 1 on failure.
***********************************************************************/
int install_usr_signal_handlers(void) {
#ifndef _WIN64 /* fixme: Windows does not support USR signals */
struct sigaction sa, saPrev;
sa.sa_sigaction = NULL;
sa.sa_handler = &chkpt_signal_handler;
sa.sa_flags = SA_RESTART;
sigfillset(&sa.sa_mask);
if (sigaction(SIGUSR1, &sa, &saPrev) != 0) {
mcell_error("Failed to install USR1 signal handler.");
/*return 1;*/
}
if (sigaction(SIGUSR2, &sa, &saPrev) != 0) {
mcell_error("Failed to install USR2 signal handler.");
/*return 1;*/
}
#endif
return 0;
}
/*
* has_micro_rev_and_trimol_rxns tests if the model has surface or
* volume reversibility selected and also contains trimolecular reactions.
* In that case it returns true and false otherwise.
*/
bool has_micro_rev_and_trimol_rxns(struct species **species_list,
int n_species, byte has_vol_rev, byte has_surf_rev) {
if (!has_vol_rev && !has_surf_rev) {
return false;
}
for (int i = 0; i < n_species; i++) {
struct species *sp = species_list[i];
if (sp->flags & (CAN_VOLVOLVOL | CAN_VOLVOLSURF | CAN_VOLSURFSURF |
CAN_SURFSURFSURF)) {
return true;
}
}
return false;
}
| C |
3D | mcellteam/mcell | src/mcell_release.c | .c | 32,595 | 928 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "sym_table.h"
#include "logging.h"
#include "mcell_species.h"
#include "mcell_release.h"
#include "mcell_objects.h"
/* static helper functions */
static struct release_site_obj *new_release_site(
MCELL_STATE *state, char *name);
static struct release_evaluator *
pack_release_expr(
struct release_evaluator *rel_eval_L,
struct release_evaluator *rel_eval_R,
byte op);
/******************************************************************************
*
* mcell_create_list_release_site is the main API function for creating
* release sites from a list of points (LIST based).
* INPUT:
* state = world
* parent = scene
* site_name
* mol = really a list of all the mcell_species, constructed using the
* inconvenient mcell_add_to_species_list command
* x,y,z pos
* number of sites
* diameter to search for release
* release object
*
******************************************************************************/
MCELL_STATUS mcell_create_list_release_site(
MCELL_STATE *state, struct geom_object *parent, char *site_name, struct
mcell_species *mol, double *x_pos, double *y_pos, double *z_pos, int n_site,
struct vector3 *diameter, struct geom_object **new_obj) {
// Create a qualified object name
// Note: stolen from below. How does this yield a qualified name?
char qualified_name[20];
sprintf(qualified_name, "Scene.%s", site_name);
// Make a new release object - this is later copied into new_obj
int error_code = 0;
struct dyngeom_parse_vars *dg_parse = state->dg_parse;
struct geom_object *release_object = make_new_object(
dg_parse, state->obj_sym_table, qualified_name, &error_code);
// Add it to the scene
// Set the parent of the object to be the root object. Not reciprocal until
// add_child_objects is called.
release_object->parent = parent;
add_child_objects(parent, release_object, release_object);
/////
// "Start" the new release site - just like we do in MDL land
/////
struct geom_object *dummy = NULL;
mcell_start_release_site(state, release_object->sym, &dummy);
// Get a release_site_obj
struct release_site_obj *releaser = (struct release_site_obj *)release_object->contents;
// Set it to be a list shape (DOES THIS MATTER?)
releaser->release_shape = SHAPE_LIST;
// Set the initial count
releaser->release_number = 0;
// Set the diameter - this is the diameter it uses to search for where to place surface mols
// Note: can be NULL => search diameter = 0, but this means we likely fail to place a lot of surface mols
releaser->diameter = CHECKED_MALLOC_STRUCT(struct vector3, "release site diameter");
if (releaser->diameter == NULL)
{
/*free(qualified_name);*/
return MCELL_FAIL;
}
releaser->diameter->x = diameter->x * state->r_length_unit;
releaser->diameter->y = diameter->y * state->r_length_unit;
releaser->diameter->z = diameter->z * state->r_length_unit;
// Go through all the molecules
int i_site=0;
struct release_single_molecule *curr_rsm = NULL;
struct release_single_molecule *rsm = NULL;
while(i_site < n_site)
{
rsm = CHECKED_MALLOC_STRUCT(struct release_single_molecule, "release site molecule position");
if (rsm == NULL) {
// Out of memory reading molecule positions
return MCELL_FAIL;
}
// Set release properties
rsm->orient = mol->orient;
rsm->loc.x = x_pos[i_site] * state->r_length_unit;
rsm->loc.y = y_pos[i_site] * state->r_length_unit;
rsm->loc.z = z_pos[i_site] * state->r_length_unit;
rsm->mol_type = (struct species *)(mol->mol_type->value);
rsm->next = NULL;
// mcell_log_raw("Released: %d %s\n", i_site, mol->mol_type->name);
// If its the first mol, start off the list
if (i_site == 0)
{
releaser->mol_list = rsm; // The head
curr_rsm = rsm; // For linking the list
}
else
{
curr_rsm->next = rsm; // Link the previous element to this one
curr_rsm = rsm; // Advance by one to the tail of the list in anticipation of more linking
}
releaser->release_number++; // The count
// Go to the next site
i_site++;
// Make sure to grab the next mol
mol = mol->next;
}
/////
// "Finish" the release site - yay?
/////
mcell_finish_release_site(release_object->sym, &dummy);
// Copy the new release object into what was passed into the function
// There probably is something better to do here?
*new_obj = release_object;
return MCELL_SUCCESS;
}
/******************************************************************************
*
* mcell_create_geometrical_release_site is the main API function for creating
* geometrical release sites (SHAPE based).
*
******************************************************************************/
MCELL_STATUS mcell_create_geometrical_release_site(
MCELL_STATE *state, struct geom_object *parent, const char *site_name, int shape,
struct vector3 *position, struct vector3 *diameter,
struct mcell_species *mol, double num, int num_type, double rel_prob,
struct release_pattern *rpatp, struct geom_object **new_obj) {
assert(shape != SHAPE_REGION && shape != SHAPE_LIST);
assert((((struct species *)mol->mol_type->value)->flags & NOT_FREE) == 0);
// create qualified object name
// ecc replaced by sprintf for swig function (macros are bad)
char *qualified_name = CHECKED_SPRINTF("%s.%s", parent->sym->name, site_name);
/*char qualified_name[20];*/
/*sprintf(qualified_name, "Scene.%s", site_name);*/
int error_code = 0;
struct dyngeom_parse_vars *dg_parse = state->dg_parse;
struct geom_object *release_object = make_new_object(
dg_parse,
state->obj_sym_table,
qualified_name,
&error_code);
// release_object->parent = state->root_instance;
// Set the parent of the object to be the root object. Not reciprocal until
// add_child_objects is called.
release_object->parent = parent;
add_child_objects(parent, release_object, release_object);
struct geom_object *dummy = NULL;
mcell_start_release_site(state, release_object->sym, &dummy);
// release site geometry and locations
struct release_site_obj *releaser =
(struct release_site_obj *)release_object->contents;
releaser->release_shape = shape;
set_release_site_location(state, releaser, position);
releaser->diameter =
CHECKED_MALLOC_STRUCT(struct vector3, "release site diameter");
if (releaser->diameter == NULL) {
/*free(qualified_name);*/
return MCELL_FAIL;
}
releaser->diameter->x = diameter->x * state->r_length_unit;
releaser->diameter->y = diameter->y * state->r_length_unit;
releaser->diameter->z = diameter->z * state->r_length_unit;
// release probability and release patterns
if (rel_prob < 0 || rel_prob > 1) {
/*free(qualified_name);*/
return MCELL_FAIL;
}
if (rpatp != NULL) {
releaser->pattern = rpatp;
} else {
releaser->release_prob = rel_prob;
}
/* molecule and molecule number */
if (num_type == 0) {
set_release_site_constant_number(releaser, num);
} else if (num_type == 1) {
set_release_site_concentration(releaser, num);
} else {
return MCELL_FAIL;
}
releaser->mol_type = (struct species *)mol->mol_type->value;
releaser->orientation = mol->orient;
mcell_finish_release_site(release_object->sym, &dummy);
*new_obj = release_object;
//ecc removed for swig function
// free(qualified_name);
return MCELL_SUCCESS;
}
/**************************************************************************
start_release_site:
Start parsing the innards of a release site.
In: state: system state
sym_ptr: symbol for the release site
Out: 0 on success, 1 on failure
**************************************************************************/
MCELL_STATUS mcell_start_release_site(MCELL_STATE *state,
struct sym_entry *sym_ptr,
struct geom_object **obj) {
struct geom_object *obj_ptr = (struct geom_object *)sym_ptr->value;
obj_ptr->object_type = REL_SITE_OBJ;
obj_ptr->contents = new_release_site(state, sym_ptr->name);
if (obj_ptr->contents == NULL) {
return MCELL_FAIL;
}
*obj = obj_ptr;
return MCELL_SUCCESS;
}
/**************************************************************************
finish_release_site:
Finish parsing the innards of a release site.
In: sym_ptr: symbol for the release site
Out: the object, on success, or NULL on failure
**************************************************************************/
MCELL_STATUS mcell_finish_release_site(struct sym_entry *sym_ptr,
struct geom_object **obj) {
struct geom_object *obj_ptr_new = (struct geom_object *)sym_ptr->value;
no_printf("Release site %s defined:\n", sym_ptr->name);
if (is_release_site_valid((struct release_site_obj *)obj_ptr_new->contents)) {
return MCELL_FAIL;
}
*obj = obj_ptr_new;
return MCELL_SUCCESS;
}
/******************************************************************************
*
* mcell_create_region_release is the main API function for creating release
* sites on regions.
*
******************************************************************************/
MCELL_STATUS
mcell_create_region_release(MCELL_STATE *state, struct geom_object *parent,
struct geom_object *release_on_in, char *site_name,
char *reg_name, struct mcell_species *mol,
double num, int num_type, double rel_prob,
struct release_pattern *rpatp, struct geom_object **new_obj) {
// create qualified release object name
char *qualified_name = CHECKED_SPRINTF("%s.%s", parent->sym->name, site_name);
int error_code = 0;
struct dyngeom_parse_vars *dg_parse = state->dg_parse;
struct geom_object *release_object = make_new_object(
dg_parse,
state->obj_sym_table,
qualified_name,
&error_code);
// Set the parent of the object to be the root object. Not reciprocal until
// add_child_objects is called.
release_object->parent = parent;
add_child_objects(parent, release_object, release_object);
struct geom_object *dummy = NULL;
mcell_start_release_site(state, release_object->sym, &dummy);
struct release_site_obj *releaser =
(struct release_site_obj *)release_object->contents;
struct sym_entry *sym_ptr =
existing_region(state, release_on_in->sym, reg_name);
struct release_evaluator *rel_eval = new_release_region_expr_term(sym_ptr);
mcell_set_release_site_geometry_region(state, releaser, release_on_in,
rel_eval);
// release probability and release patterns
if (rel_prob < 0 || rel_prob > 1) {
free(qualified_name);
return MCELL_FAIL;
}
if (rpatp != NULL) {
releaser->pattern = rpatp;
} else {
releaser->release_prob = rel_prob;
}
/* molecule and molecule number */
if (num_type == 0) {
set_release_site_constant_number(releaser, num);
} else if (num_type == 1) {
set_release_site_concentration(releaser, num);
} else {
return MCELL_FAIL;
}
releaser->mol_type = (struct species *)mol->mol_type->value;
releaser->orientation = mol->orient;
mcell_finish_release_site(release_object->sym, &dummy);
*new_obj = release_object;
free(qualified_name);
return MCELL_SUCCESS;
}
/******************************************************************************
*
* mcell_create_region_release_boolean is the main API function for creating release
* sites on regions with boolean logic.
*
******************************************************************************/
MCELL_STATUS
mcell_create_region_release_boolean(MCELL_STATE *state, struct geom_object *parent,
char *site_name, struct mcell_species *mol,
double num, int num_type, double rel_prob,
struct release_pattern *rpatp, struct release_evaluator *rel_eval,
struct geom_object **new_obj) {
// create qualified release object name
char *qualified_name = CHECKED_SPRINTF("%s.%s", parent->sym->name, site_name);
int error_code = 0;
struct dyngeom_parse_vars *dg_parse = state->dg_parse;
struct geom_object *release_object = make_new_object(
dg_parse,
state->obj_sym_table,
qualified_name,
&error_code);
// Set the parent of the object to be the root object. Not reciprocal until
// add_child_objects is called.
release_object->parent = parent;
add_child_objects(parent, release_object, release_object);
struct geom_object *obj_ptr = NULL;
mcell_start_release_site(state, release_object->sym, &obj_ptr);
struct release_site_obj *releaser =
(struct release_site_obj *)release_object->contents;
mcell_set_release_site_geometry_region(state, releaser, (struct geom_object *)obj_ptr->contents,
rel_eval);
// release probability and release patterns
if (rel_prob < 0 || rel_prob > 1) {
free(qualified_name);
return MCELL_FAIL;
}
if (rpatp != NULL) {
releaser->pattern = rpatp;
} else {
releaser->release_prob = rel_prob;
}
/* molecule and molecule number */
if (num_type == 0) {
set_release_site_constant_number(releaser, num);
} else if (num_type == 1) {
set_release_site_concentration(releaser, num);
} else {
return MCELL_FAIL;
}
releaser->mol_type = (struct species *)mol->mol_type->value;
releaser->orientation = mol->orient;
mcell_finish_release_site(release_object->sym, &obj_ptr);
*new_obj = release_object;
free(qualified_name);
return MCELL_SUCCESS;
}
/******************************************************************************
*
* mcell_new_release_pattern is the main API function for creating a new
* release pattern.
*
******************************************************************************/
struct sym_entry *mcell_new_release_pattern(MCELL_STATE *state, char *name) {
struct sym_entry *st;
if (retrieve_sym(name, state->rpat_sym_table) != NULL) {
// Release pattern already defined
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
// free(name);
mcell_log_raw("ERROR: Release pattern already defined.");
return NULL;
} else if ((st = store_sym(name, RPAT, state->rpat_sym_table,
NULL)) == NULL) {
// Out of memory while creating release pattern
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
// free(name);
mcell_log_raw("ERROR: Out of memory while creating release pattern.");
return NULL;
}
// free(name);
return st;
}
/**************************************************************************
* mcell_create_release_pattern:
* Create a release pattern
**************************************************************************/
struct release_pattern *mcell_create_release_pattern(MCELL_STATE *state, char *name, double delay,
double release_interval, double train_interval,
double train_duration, int number_of_trains) {
struct sym_entry *rpat_sym = mcell_new_release_pattern(state,name);
if (rpat_sym == NULL) {
mcell_log_raw("ERROR: Could not create release pattern.");
return NULL;
}
struct release_pattern *rpatp = (struct release_pattern *)rpat_sym->value;
if (release_interval/state->time_unit <= 0) {
// Release interval must be set to a positive number
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
mcell_log_raw("ERROR: Release interval must be set to a positive number.");
return NULL;
}
if (train_interval/state->time_unit <= 0) {
// Train interval must be set to a positive number
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
mcell_log_raw("ERROR: Train interval must be set to a positive number.");
return NULL;
}
if (train_duration/state->time_unit > train_interval/state->time_unit) {
// Train duration must not be longer than the train interval
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
mcell_log_raw("ERROR: Train duration must not be longer than the train interval.");
return NULL;
}
if (train_duration/state->time_unit <= 0) {
// Train duration must be set to a positive number
// TO-DO: Ich verlange anstaendige Meldungen, verdammt noch mal!
mcell_log_raw("ERROR: Train duration must be set to a positive number.");
return NULL;
}
/* Copy in release pattern */
if (distinguishable(delay, 0.0, EPS_C)) {
rpatp->delay = delay/state->time_unit;
}
else {
rpatp->delay = 0;
}
if (distinguishable(release_interval, FOREVER, EPS_C)) {
rpatp->release_interval = release_interval/state->time_unit;
}
else {
rpatp->release_interval = FOREVER;
}
if (distinguishable(train_interval, FOREVER, EPS_C)) {
rpatp->train_interval = train_interval/state->time_unit;
}
else {
rpatp->train_interval = FOREVER;
}
if (distinguishable(train_duration, FOREVER, EPS_C)) {
rpatp->train_duration = train_duration/state->time_unit;
}
else {
rpatp->train_duration = FOREVER;
}
rpatp->number_of_trains = number_of_trains;
no_printf("Release pattern %s defined:\n", rpat_sym->name);
no_printf("\tdelay = %f\n", rpatp->delay);
no_printf("\trelease_interval = %f\n", rpatp->release_interval);
no_printf("\ttrain_interval = %f\n", rpatp->train_interval);
no_printf("\ttrain_duration = %f\n", rpatp->train_duration);
no_printf("\tnumber_of_trains = %d\n", rpatp->number_of_trains);
return rpatp;
}
/*************************************************************************
In: state: system state
rel_site_obj_ptr: the release site object to validate
obj_ptr: the object representing this release site
rel_eval: the release evaluator representing the region of release
Out: 0 on success, 1 on failure
**************************************************************************/
int mcell_set_release_site_geometry_region(
MCELL_STATE *state, struct release_site_obj *rel_site_obj_ptr,
struct geom_object *obj_ptr, struct release_evaluator *rel_eval) {
rel_site_obj_ptr->release_shape = SHAPE_REGION;
state->place_waypoints_flag = 1;
struct release_region_data *rel_reg_data = CHECKED_MALLOC_STRUCT(
struct release_region_data, "release site on region");
if (rel_reg_data == NULL) {
return 1;
}
rel_reg_data->n_walls_included = -1; /* Indicates uninitialized state */
rel_reg_data->cum_area_list = NULL;
rel_reg_data->wall_index = NULL;
rel_reg_data->obj_index = NULL;
rel_reg_data->n_objects = -1;
rel_reg_data->owners = NULL;
rel_reg_data->in_release = NULL;
rel_reg_data->self = obj_ptr;
rel_reg_data->expression = rel_eval;
if (check_release_regions(rel_eval, obj_ptr, state->root_instance)) {
// Trying to release on a region that the release site cannot see! Try
// grouping the release site and the corresponding geometry with an OBJECT.
free(rel_reg_data);
return 2;
}
rel_site_obj_ptr->region_data = rel_reg_data;
return 0;
}
/**************************************************************************
set_release_site_location:
Set the location of a release site.
In: state: system state
rel_site_obj_ptr: release site
location: location for release site
Out: none
**************************************************************************/
void set_release_site_location(MCELL_STATE *state,
struct release_site_obj *rel_site_obj_ptr,
struct vector3 *location) {
rel_site_obj_ptr->location = location;
rel_site_obj_ptr->location->x *= state->r_length_unit;
rel_site_obj_ptr->location->y *= state->r_length_unit;
rel_site_obj_ptr->location->z *= state->r_length_unit;
}
/**************************************************************************
set_release_site_constant_number:
Set a constant release quantity from this release site, in units of
molecules.
In: rel_site_obj_ptr: the release site
num: count of molecules to release
Out: none. release site object is updated
**************************************************************************/
void set_release_site_constant_number(struct release_site_obj *rel_site_obj_ptr,
double num) {
rel_site_obj_ptr->release_number_method = CONSTNUM;
rel_site_obj_ptr->release_number = num;
}
/**************************************************************************
set_release_site_gaussian_number:
Set a gaussian-distributed release quantity from this release site, in
units of molecules.
In: rel_site_obj_ptr: the release site
mean: mean value of distribution
stdev: std. dev. of distribution
Out: none. release site object is updated
**************************************************************************/
void set_release_site_gaussian_number(struct release_site_obj *rel_site_obj_ptr,
double mean, double stdev) {
rel_site_obj_ptr->release_number_method = GAUSSNUM;
rel_site_obj_ptr->release_number = mean;
rel_site_obj_ptr->standard_deviation = stdev;
}
/**************************************************************************
new_release_region_expr_binary:
Set the geometry for a particular release site to be a region expression.
In: parse_state: parser state
reL: release evaluation tree (set operations) for left side of expression
reR: release evaluation tree for right side of expression
op: flags indicating the operation performed by this node
Out: the release expression, or NULL if an error occurs
**************************************************************************/
struct release_evaluator *
new_release_region_expr_binary(struct release_evaluator *rel_eval_L,
struct release_evaluator *rel_eval_R, int op) {
return pack_release_expr(rel_eval_L, rel_eval_R, op);
}
/*************************************************************************
check_release_regions:
In: state: system state
rel_eval: an release evaluator (set operations applied to regions)
parent: the object that owns this release evaluator
instance: the root object that begins the instance tree
Out: 0 if all regions refer to instanced objects or to a common ancestor of
the object with the evaluator, meaning that the object can be found. 1 if
any referred-to region cannot be found.
*************************************************************************/
int check_release_regions(struct release_evaluator *rel_eval,
struct geom_object *parent, struct geom_object *instance) {
struct geom_object *obj_ptr;
if (rel_eval->left != NULL) {
if (rel_eval->op & REXP_LEFT_REGION) {
obj_ptr =
common_ancestor(parent, ((struct region *)rel_eval->left)->parent);
if (obj_ptr == NULL || (obj_ptr->parent == NULL && obj_ptr != instance)) {
obj_ptr = common_ancestor(instance,
((struct region *)rel_eval->left)->parent);
}
if (obj_ptr == NULL) {
// Region neither instanced nor grouped with release site
return 2;
}
} else if (check_release_regions((struct release_evaluator *)rel_eval->left, parent, instance)) {
return 1;
}
}
if (rel_eval->right != NULL) {
if (rel_eval->op & REXP_RIGHT_REGION) {
obj_ptr =
common_ancestor(parent, ((struct region *)rel_eval->right)->parent);
if (obj_ptr == NULL || (obj_ptr->parent == NULL && obj_ptr != instance)) {
obj_ptr = common_ancestor(instance,
((struct region *)rel_eval->right)->parent);
}
if (obj_ptr == NULL) {
// Region not grouped with release site.
return 3;
}
} else if (check_release_regions((struct release_evaluator *)rel_eval->right, parent, instance)) {
return 1;
}
}
return 0;
}
/**************************************************************************
is_release_site_valid:
Validate a release site.
In: rel_site_obj_ptr: the release site object to validate
Out: 0 if it is valid, 1 if not
**************************************************************************/
int is_release_site_valid(struct release_site_obj *rel_site_obj_ptr) {
// Unless it's a list release, user must specify MOL type
if (rel_site_obj_ptr->release_shape != SHAPE_LIST) {
// Must specify molecule to release using MOLECULE=molecule_name.
if (rel_site_obj_ptr->mol_type == NULL) {
return 2;
}
// Make sure it's not a surface class
if ((rel_site_obj_ptr->mol_type->flags & IS_SURFACE) != 0) {
return 3;
}
}
/* Check that concentration/density status of release site agrees with
* volume/grid status of molecule */
if (rel_site_obj_ptr->release_number_method == CCNNUM) {
// CONCENTRATION may only be used with molecules that can diffuse in 3D.
if ((rel_site_obj_ptr->mol_type->flags & NOT_FREE) != 0) {
return 4;
}
} else if (rel_site_obj_ptr->release_number_method == DENSITYNUM) {
// DENSITY may only be used with molecules that can diffuse in 2D.
if ((rel_site_obj_ptr->mol_type->flags & NOT_FREE) == 0) {
return 5;
}
}
/* Molecules can only be removed via a region release */
if (rel_site_obj_ptr->release_shape != SHAPE_REGION &&
rel_site_obj_ptr->release_number < 0) {
return 2;
}
/* Unless it's a region release we must have a location */
if (rel_site_obj_ptr->release_shape != SHAPE_REGION) {
if (rel_site_obj_ptr->location == NULL) {
// Release site is missing location.
if (rel_site_obj_ptr->release_shape != SHAPE_LIST ||
rel_site_obj_ptr->mol_list == NULL) {
return 6;
} else {
// Give it a default location of (0, 0, 0)
rel_site_obj_ptr->location =
CHECKED_MALLOC_STRUCT(struct vector3, "release site location");
if (rel_site_obj_ptr->location == NULL)
return 1;
rel_site_obj_ptr->location->x = 0;
rel_site_obj_ptr->location->y = 0;
rel_site_obj_ptr->location->z = 0;
}
}
no_printf("\tLocation = [%f,%f,%f]\n", rel_site_obj_ptr->location->x,
rel_site_obj_ptr->location->y, rel_site_obj_ptr->location->z);
}
return 0;
}
/**************************************************************************
set_release_site_concentration:
Set a release quantity from this release site based on a fixed
concentration within the release-site's area.
In: rel_site_obj_ptr: the release site
conc: concentration for release
Out: 0 on success, 1 on failure. release site object is updated
**************************************************************************/
int set_release_site_concentration(struct release_site_obj *rel_site_obj_ptr,
double conc) {
if (rel_site_obj_ptr->release_shape == SHAPE_SPHERICAL_SHELL) {
return 1;
}
rel_site_obj_ptr->release_number_method = CCNNUM;
rel_site_obj_ptr->concentration = conc;
return 0;
}
/**************************************************************************
mdl_new_release_region_expr_term:
Create a new "release on region" expression term.
In: my_sym: the symbol for the region comprising this term in the expression
Out: the release evaluator on success, or NULL if allocation fails
**************************************************************************/
struct release_evaluator *
new_release_region_expr_term(struct sym_entry *my_sym) {
struct release_evaluator *rel_eval =
CHECKED_MALLOC_STRUCT(struct release_evaluator, "release site on region");
if (rel_eval == NULL) {
return NULL;
}
rel_eval->op = REXP_NO_OP | REXP_LEFT_REGION;
rel_eval->left = my_sym->value;
rel_eval->right = NULL;
((struct region *)rel_eval->left)->flags |= COUNT_CONTENTS;
return rel_eval;
}
/******************************************************************************
*
* static helper functions
*
*****************************************************************************/
/*************************************************************************
existing_region:
Find an existing region. Print an error message if it isn't found.
In: obj_symp: object on which to find the region
name: region name
Out: the region, or NULL if not found
NOTE: This is similar to mdl_existing_region
*************************************************************************/
struct sym_entry *existing_region(MCELL_STATE *state,
struct sym_entry *obj_symp,
char *region_name) {
char *full_name = CHECKED_SPRINTF("%s,%s", obj_symp->name, region_name);
if (full_name == NULL) {
// free(full_name);
return NULL;
}
struct sym_entry *symp = retrieve_sym(full_name, state->reg_sym_table);
free(full_name);
return symp;
}
/**************************************************************************
new_release_site:
Create a new release site.
In: state: system state
name: name for the new site
Out: an empty release site, or NULL if allocation failed
**************************************************************************/
struct release_site_obj *new_release_site(MCELL_STATE *state, char *name) {
struct release_site_obj *rel_site_obj_ptr;
if ((rel_site_obj_ptr = CHECKED_MALLOC_STRUCT(struct release_site_obj,
"release site")) == NULL)
return NULL;
rel_site_obj_ptr->location = NULL;
rel_site_obj_ptr->mol_type = NULL;
rel_site_obj_ptr->release_number_method = CONSTNUM;
rel_site_obj_ptr->release_shape = SHAPE_UNDEFINED;
rel_site_obj_ptr->orientation = 0;
rel_site_obj_ptr->release_number = 0;
rel_site_obj_ptr->mean_diameter = 0;
rel_site_obj_ptr->concentration = 0;
rel_site_obj_ptr->standard_deviation = 0;
rel_site_obj_ptr->diameter = NULL;
rel_site_obj_ptr->region_data = NULL;
rel_site_obj_ptr->mol_list = NULL;
rel_site_obj_ptr->release_prob = 1.0;
rel_site_obj_ptr->pattern = state->default_release_pattern;
struct periodic_image *periodic_box = CHECKED_MALLOC_STRUCT(
struct periodic_image, "periodic image descriptor");
rel_site_obj_ptr->periodic_box = periodic_box;
rel_site_obj_ptr->periodic_box->x = 0;
rel_site_obj_ptr->periodic_box->y = 0;
rel_site_obj_ptr->periodic_box->z = 0;
// if ((rel_site_obj_ptr->name = mdl_strdup(name)) == NULL)
if ((rel_site_obj_ptr->name = strdup(name)) == NULL) {
free(rel_site_obj_ptr);
return NULL;
}
return rel_site_obj_ptr;
}
/*************************************************************************
pack_release_expr:
In: rel_eval_L: release evaluation tree (set operations) for left side of
expression
rel_eval_R: release evaluation tree for right side of expression
op: flags indicating the operation performed by this node
Out: release evaluation tree containing the two subtrees and the
operation
Note: singleton elements (with REXP_NO_OP operation) are compacted by
this function and held simply as the corresponding region, not
the NO_OP operation of that region (the operation is needed for
efficient parsing)
*************************************************************************/
struct release_evaluator *
pack_release_expr(struct release_evaluator *rel_eval_L,
struct release_evaluator *rel_eval_R, byte op) {
struct release_evaluator *rel_eval = NULL;
if ((rel_eval_R->op & REXP_MASK) == REXP_NO_OP &&
(rel_eval_R->op & REXP_LEFT_REGION) != 0) {
if ((rel_eval_L->op & REXP_MASK) == REXP_NO_OP &&
(rel_eval_L->op & REXP_LEFT_REGION) != 0) {
rel_eval = rel_eval_L;
rel_eval->right = rel_eval_R->left;
rel_eval->op = op | REXP_LEFT_REGION | REXP_RIGHT_REGION;
free(rel_eval_R);
} else {
rel_eval = rel_eval_R;
rel_eval->right = rel_eval->left;
rel_eval->left = (void *)rel_eval_L;
rel_eval->op = op | REXP_RIGHT_REGION;
}
} else if ((rel_eval_L->op & REXP_MASK) == REXP_NO_OP &&
(rel_eval_L->op & REXP_LEFT_REGION) != 0) {
rel_eval = rel_eval_L;
rel_eval->right = (void *)rel_eval_R;
rel_eval->op = op | REXP_LEFT_REGION;
} else {
rel_eval = CHECKED_MALLOC_STRUCT(struct release_evaluator,
"release region expression");
if (rel_eval == NULL) {
return NULL;
}
rel_eval->left = (void *)rel_eval_L;
rel_eval->right = (void *)rel_eval_R;
rel_eval->op = op;
}
return rel_eval;
}
| C |
3D | mcellteam/mcell | src/mcell_viz.h | .h | 1,113 | 28 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
MCELL_STATUS mcell_create_viz_output(MCELL_STATE *state, const char *filename,
struct mcell_species *mol_viz_list,
long long start, long long end,
long long step, bool ascii_output);
void mcell_new_viz_output_block(struct viz_output_block *vizblk);
struct frame_data_list *
mcell_create_viz_frame(int time_type, int type,
struct num_expr_list *iteration_list);
int mcell_set_molecule_viz_state(struct viz_output_block *vizblk,
struct species *specp, int viz_state);
| Unknown |
3D | mcellteam/mcell | src/map_c.cpp | .cpp | 10,046 | 238 |
#include <unordered_map>
#include <boost/container/small_vector.hpp>
#include <iostream>
#include <vector>
#include "map_c.h"
#include <assert.h>
using namespace std;
const unsigned long INITIAL_SIZE = 0x4;
const unsigned long BASE_ITEMS = 0x100; // this value might need to be tweaked
const unsigned long MASK = (BASE_ITEMS -1);
typedef boost::container::small_vector<boost::container::small_vector<pair<unsigned long, any_t>, INITIAL_SIZE>, BASE_ITEMS> cpp_map_t;
/*
* Return an empty hashmap, or NULL on failure.
*/
map_t hashmap_new() {
// TODO: free
cpp_map_t* vec = new cpp_map_t();
vec->resize(BASE_ITEMS);
return vec;
}
// TODO: free after simulation terminates
void hashmap_clear(map_t in) {
// TODO: free
//delete ((cpp_map_t*)in);
((cpp_map_t*)in)->clear();
}
int hashmap_put_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t value) {
assert(in != nullptr);
assert(key == key_hash);
cpp_map_t* m = (cpp_map_t*)in;
((*m)[key_hash & MASK]).push_back( pair<unsigned long, any_t>(key_hash, value));
return 0; // ignored
}
int hashmap_get_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t* value) {
assert(in != nullptr);
assert(key == key_hash);
cpp_map_t* m = (cpp_map_t*)in;
const auto& internal_vec = ((*m)[key_hash & MASK]);
size_t sz = internal_vec.size();
if (sz == 1 && internal_vec[0].first == key_hash) {
*value = internal_vec[0].second;
return MAP_OK;
}
else if (sz == 0) {
return MAP_MISSING;
}
else {
for (const auto& item: internal_vec) {
if (item.first == key_hash) {
*value = item.second;
return MAP_OK;
}
}
return MAP_MISSING;
}
}
#if 0
// the most versatile solution with also good performance
typedef boost::container::flat_map<unsigned long, any_t> cpp_map_t;
//typedef boost::container::map<unsigned long, any_t> cpp_map_t;
/*
* Return an empty hashmap, or NULL on failure.
*/
map_t hashmap_new() {
// TODO: free
return (map_t) new cpp_map_t();
}
void hashmap_clear(map_t in) {
// TODO: free
//delete ((cpp_map_t*)in);
((cpp_map_t*)in)->clear();
}
int hashmap_put_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t value) {
assert(in != nullptr);
assert(key == key_hash);
cout << "INS 0x" << hex << key_hash << "\n";
((cpp_map_t*)in)->insert( pair<unsigned long, any_t>(key_hash, value));
return 0; // ignored
}
int hashmap_get_nohash(map_t in, unsigned long key, unsigned long key_hash, any_t* value) {
assert(in != nullptr);
assert(key == key_hash);
cpp_map_t* m = ((cpp_map_t*)in);
auto it = m->find(key);
if (it != m->end()) {
*value = it->second;
return MAP_OK;
}
else {
return MAP_MISSING;
}
}
#endif
/* The implementation here was originally done by Gary S. Brown. I have
borrowed the tables directly, and made some minor changes to the
crc32-function (including changing the interface). //ylo */
/* ============================================================= */
/* COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or */
/* code or tables extracted from it, as desired without restriction. */
/* */
/* First, the polynomial itself and its table of feedback terms. The */
/* polynomial is */
/* X^32+X^26+X^23+X^22+X^16+X^12+X^11+X^10+X^8+X^7+X^5+X^4+X^2+X^1+X^0 */
/* */
/* Note that we take it "backwards" and put the highest-order term in */
/* the lowest-order bit. The X^32 term is "implied"; the LSB is the */
/* X^31 term, etc. The X^0 term (usually shown as "+1") results in */
/* the MSB being 1. */
/* */
/* Note that the usual hardware shift register implementation, which */
/* is what we're using (we're merely optimizing it by doing eight-bit */
/* chunks at a time) shifts bits into the lowest-order term. In our */
/* implementation, that means shifting towards the right. Why do we */
/* do it this way? Because the calculated CRC must be transmitted in */
/* order from highest-order term to lowest-order term. UARTs transmit */
/* characters in order from LSB to MSB. By storing the CRC this way, */
/* we hand it to the UART in the order low-byte to high-byte; the UART */
/* sends each low-bit to hight-bit; and the result is transmission bit */
/* by bit from highest- to lowest-order term without requiring any bit */
/* shuffling on our part. Reception works similarly. */
/* */
/* The feedback terms table consists of 256, 32-bit entries. Notes: */
/* */
/* The table can be generated at runtime if desired; code to do so */
/* is shown later. It might not be obvious, but the feedback */
/* terms simply represent the results of eight shift/xor opera- */
/* tions for all combinations of data and CRC register values. */
/* */
/* The values must be right-shifted by eight bits by the "updcrc" */
/* logic; the shift must be unsigned (bring in zeroes). On some */
/* hardware you could probably optimize the shift in assembler by */
/* using byte-swap instructions. */
/* polynomial $edb88320 */
/* */
/* -------------------------------------------------------------------- */
static unsigned long crc32_tab[] = {
0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
0x2d02ef8dL
};
/* Return a 32-bit CRC of the contents of the buffer. */
unsigned long crc32(const unsigned char *s, unsigned int len)
{
unsigned int i;
unsigned long crc32val;
crc32val = 0;
for (i = 0; i < len; i ++)
{
crc32val =
crc32_tab[(crc32val ^ s[i]) & 0xff] ^
(crc32val >> 8);
}
return crc32val;
}
| C++ |
3D | mcellteam/mcell | src/version_info.h | .h | 819 | 28 | /******************************************************************************
*
* Copyright (C) 2006-2025 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#pragma once
#include <stdio.h>
/* MCell version as a string */
extern char const mcell_version[];
/* Write the credits to a file handle */
void print_credits(FILE *f);
/* Write the version info to a file handle */
void print_version(FILE *f);
/* Write the version info to a file handle */
void print_full_version(FILE *f);
| Unknown |
3D | mcellteam/mcell | src/logging.c | .c | 7,632 | 278 | /******************************************************************************
*
* Copyright (C) 2006-2017 by
* The Salk Institute for Biological Studies and
* Pittsburgh Supercomputing Center, Carnegie Mellon University
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*
******************************************************************************/
#include "config.h"
#include "logging.h"
#include "mem_util.h"
#include <stdlib.h>
#undef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#include <string.h>
/* Our log file */
static FILE *mcell_log_file = NULL;
/* Our warning/error file */
static FILE *mcell_error_file = NULL;
/* Get the log file. */
FILE *mcell_get_log_file(void) {
if (mcell_log_file == NULL) {
#ifdef DEBUG
setvbuf(stdout, NULL, _IONBF, 0);
#endif
mcell_log_file = stdout;
}
return mcell_log_file;
}
/* Get the error file. */
FILE *mcell_get_error_file(void) {
if (mcell_error_file == NULL) {
#ifdef DEBUG
setvbuf(stderr, NULL, _IONBF, 0);
#endif
mcell_error_file = stderr;
}
return mcell_error_file;
}
/* Set the log file. */
void mcell_set_log_file(FILE *f) {
if (mcell_log_file != NULL && mcell_log_file != stdout &&
mcell_log_file != stderr)
fclose(mcell_log_file);
mcell_log_file = f;
#ifdef DEBUG
setvbuf(mcell_log_file, NULL, _IONBF, 0);
#else
setvbuf(mcell_log_file, NULL, _IOLBF, 128);
#endif
}
/* Set the error file. */
void mcell_set_error_file(FILE *f) {
if (mcell_error_file != NULL && mcell_error_file != stdout &&
mcell_error_file != stderr)
fclose(mcell_error_file);
mcell_error_file = f;
#ifdef DEBUG
setvbuf(mcell_error_file, NULL, _IONBF, 0);
#else
setvbuf(mcell_error_file, NULL, _IOLBF, 128);
#endif
}
/* Log a message. */
void mcell_log_raw(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_logv_raw(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_logv_raw(char const *fmt, va_list args) {
vfprintf(mcell_get_log_file(), fmt, args);
}
/* Log a message. */
void mcell_error_raw(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv_raw(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_errorv_raw(char const *fmt, va_list args) {
vfprintf(mcell_get_error_file(), fmt, args);
}
/* Log a message. */
void mcell_log(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_logv(fmt, args);
va_end(args);
}
/* Log a message (va_list version). */
void mcell_logv(char const *fmt, va_list args) {
mcell_logv_raw(fmt, args);
fprintf(mcell_get_log_file(), "\n");
}
/* Log a warning. */
void mcell_warn(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_warnv(fmt, args);
va_end(args);
}
/* Log a warning (va_list version). */
void mcell_warnv(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Warning: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
}
/* Log an error and carry on. */
void mcell_error_nodie(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv_nodie(fmt, args);
va_end(args);
}
/* Log an error and carry on (va_list version). */
// This will either be called by mcell_errorv (which dies) or mcell_error_nodie
// (which obviously doesn't die), so we shouldn't list this as a fatal error.
void mcell_errorv_nodie(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Error: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
}
/* Log an error and exit. */
void mcell_error(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_errorv(fmt, args);
va_end(args);
}
/* Log an error and exit (va_list version). */
void mcell_errorv(char const *fmt, va_list args) {
mcell_errorv_nodie(fmt, args);
mcell_die();
}
/* Log an internal error and exit. */
void mcell_internal_error_(char const *file, unsigned int line,
char const *func, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_internal_errorv_(file, line, func, fmt, args);
va_end(args);
}
/* Log an error and exit (va_list version). */
void mcell_internal_errorv_(char const *file, unsigned int line,
char const *func, char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "****************\n");
fprintf(mcell_get_error_file(), "INTERNAL ERROR at %s:%u [%s]: ", file, line,
func);
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
fprintf(mcell_get_error_file(),
"MCell has detected an internal program error.\n");
fprintf(mcell_get_error_file(), "****************\n");
mcell_die();
}
/* Get a copy of a string giving an error message. */
char *mcell_strerror(int err) {
char buffer[2048];
#ifdef STRERROR_R_CHAR_P
char *pbuf = strerror_r(err, buffer, sizeof(buffer));
if (pbuf != NULL)
return CHECKED_STRDUP(pbuf, "error description");
else
return CHECKED_SPRINTF("UNIX error code %d.", err);
#else
if (strerror_r(err, buffer, sizeof(buffer)) == 0)
return CHECKED_STRDUP(buffer, "error description");
else
return CHECKED_SPRINTF("UNIX error code %d.", err);
#endif
}
/* Log an error due to a failed standard library call, and exit. */
void mcell_perror_nodie(int err, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_perrorv_nodie(err, fmt, args);
va_end(args);
}
/* Log an error due to a failed standard library call, and exit (va_list
* version). */
void mcell_perrorv_nodie(int err, char const *fmt, va_list args) {
char buffer[2048];
fprintf(mcell_get_error_file(), "Fatal error: ");
mcell_errorv_raw(fmt, args);
#ifdef STRERROR_R_CHAR_P
fprintf(mcell_get_error_file(), ": %s\n",
strerror_r(err, buffer, sizeof(buffer)));
#else
if (strerror_r(err, buffer, sizeof(buffer)) == 0)
fprintf(mcell_get_error_file(), ": %s\n", buffer);
else
fprintf(mcell_get_error_file(), "\n");
#endif
}
/* Log an error due to a failed standard library call, and exit. */
void mcell_perror(int err, char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_perrorv(err, fmt, args);
va_end(args);
}
/* Log an error due to a failed standard library call, and exit (va_list
* version). */
void mcell_perrorv(int err, char const *fmt, va_list args) {
mcell_perrorv_nodie(err, fmt, args);
mcell_die();
}
/* Log an error due to failed memory allocation, but do not exit. */
void mcell_allocfailed_nodie(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_allocfailedv_nodie(fmt, args);
va_end(args);
}
/* Log an error due to failed memory allocation, but do not exit (va_list
* version). */
void mcell_allocfailedv_nodie(char const *fmt, va_list args) {
fprintf(mcell_get_error_file(), "Fatal error: ");
mcell_errorv_raw(fmt, args);
fprintf(mcell_get_error_file(), "\n");
fprintf(mcell_get_error_file(), "Fatal error: Out of memory\n\n");
mem_dump_stats(mcell_get_error_file());
}
/* Log an error due to failed memory allocation, and exit. */
void mcell_allocfailed(char const *fmt, ...) {
va_list args;
va_start(args, fmt);
mcell_allocfailedv_nodie(fmt, args);
va_end(args);
mcell_die();
}
/* Log an error due to failed memory allocation, and exit (va_list version). */
void mcell_allocfailedv(char const *fmt, va_list args) {
mcell_allocfailedv_nodie(fmt, args);
mcell_die();
}
/* Terminate program execution due to an error. */
void mcell_die(void) { exit(EXIT_FAILURE); }
| C |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.