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
libmcell/generated/gen_molecule.h
.h
6,553
188
/****************************************************************************** * * Copyright (C) 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 API_GEN_MOLECULE_H #define API_GEN_MOLECULE_H #include "api/api_common.h" #include "api/base_introspection_class.h" namespace MCell { namespace API { class Molecule; class GeometryObject; class PythonExportContext; #define MOLECULE_CTOR_NOARGS() \ Molecule( \ ) { \ class_name = "Molecule"; \ id = ID_INVALID; \ type = MoleculeType::UNSET; \ species_id = ID_INVALID; \ pos3d = std::vector<double>(); \ orientation = Orientation::NOT_SET; \ pos2d = std::vector<double>(); \ geometry_object = nullptr; \ wall_index = -1; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Molecule(DefaultCtorArgType) : \ GenMolecule(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenMolecule: public BaseIntrospectionClass { public: GenMolecule() { } GenMolecule(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Molecule> copy_molecule() const; std::shared_ptr<Molecule> deepcopy_molecule(py::dict = py::dict()) const; virtual bool __eq__(const Molecule& other) const; virtual bool eq_nonarray_attributes(const Molecule& other, const bool ignore_name = false) const; bool operator == (const Molecule& other) const { return __eq__(other);} bool operator != (const Molecule& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; // --- attributes --- int id; virtual void set_id(const int new_id_) { if (initialized) { throw RuntimeError("Value 'id' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; id = new_id_; } virtual int get_id() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return id; } MoleculeType type; virtual void set_type(const MoleculeType new_type_) { if (initialized) { throw RuntimeError("Value 'type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; type = new_type_; } virtual MoleculeType get_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return type; } int species_id; virtual void set_species_id(const int new_species_id_) { if (initialized) { throw RuntimeError("Value 'species_id' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; species_id = new_species_id_; } virtual int get_species_id() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return species_id; } std::vector<double> pos3d; virtual void set_pos3d(const std::vector<double> new_pos3d_) { if (initialized) { throw RuntimeError("Value 'pos3d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; pos3d = new_pos3d_; } virtual std::vector<double>& get_pos3d() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return pos3d; } Orientation orientation; virtual void set_orientation(const Orientation new_orientation_) { if (initialized) { throw RuntimeError("Value 'orientation' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; orientation = new_orientation_; } virtual Orientation get_orientation() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return orientation; } std::vector<double> pos2d; virtual void set_pos2d(const std::vector<double> new_pos2d_) { if (initialized) { throw RuntimeError("Value 'pos2d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; pos2d = new_pos2d_; } virtual std::vector<double>& get_pos2d() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return pos2d; } std::shared_ptr<GeometryObject> geometry_object; virtual void set_geometry_object(std::shared_ptr<GeometryObject> new_geometry_object_) { if (initialized) { throw RuntimeError("Value 'geometry_object' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; geometry_object = new_geometry_object_; } virtual std::shared_ptr<GeometryObject> get_geometry_object() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return geometry_object; } int wall_index; virtual void set_wall_index(const int new_wall_index_) { if (initialized) { throw RuntimeError("Value 'wall_index' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_index = new_wall_index_; } virtual int get_wall_index() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_index; } // --- methods --- virtual void remove() = 0; }; // GenMolecule class Molecule; py::class_<Molecule> define_pybinding_Molecule(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_MOLECULE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_instantiation.h
.h
4,550
103
/****************************************************************************** * * Copyright (C) 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 API_GEN_INSTANTIATION_H #define API_GEN_INSTANTIATION_H #include "api/api_common.h" #include "api/base_export_class.h" namespace MCell { namespace API { class Instantiation; class BaseChkptMol; class GeometryObject; class Region; class ReleaseSite; class PythonExportContext; #define INSTANTIATION_CTOR() \ Instantiation( \ const std::vector<std::shared_ptr<ReleaseSite>> release_sites_ = std::vector<std::shared_ptr<ReleaseSite>>(), \ const std::vector<std::shared_ptr<GeometryObject>> geometry_objects_ = std::vector<std::shared_ptr<GeometryObject>>(), \ const std::vector<std::shared_ptr<BaseChkptMol>> checkpointed_molecules_ = std::vector<std::shared_ptr<BaseChkptMol>>() \ ) { \ release_sites = release_sites_; \ geometry_objects = geometry_objects_; \ checkpointed_molecules = checkpointed_molecules_; \ } \ Instantiation(DefaultCtorArgType){ \ } class GenInstantiation: public BaseExportClass { public: GenInstantiation() { } GenInstantiation(DefaultCtorArgType) { } virtual ~GenInstantiation() {} std::shared_ptr<Instantiation> copy_instantiation() const; std::shared_ptr<Instantiation> deepcopy_instantiation(py::dict = py::dict()) const; virtual bool __eq__(const Instantiation& other) const; virtual bool eq_nonarray_attributes(const Instantiation& other, const bool ignore_name = false) const; bool operator == (const Instantiation& other) const { return __eq__(other);} bool operator != (const Instantiation& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_release_sites(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_geometry_objects(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_checkpointed_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<ReleaseSite>> release_sites; virtual void set_release_sites(const std::vector<std::shared_ptr<ReleaseSite>> new_release_sites_) { release_sites = new_release_sites_; } virtual std::vector<std::shared_ptr<ReleaseSite>>& get_release_sites() { return release_sites; } std::vector<std::shared_ptr<GeometryObject>> geometry_objects; virtual void set_geometry_objects(const std::vector<std::shared_ptr<GeometryObject>> new_geometry_objects_) { geometry_objects = new_geometry_objects_; } virtual std::vector<std::shared_ptr<GeometryObject>>& get_geometry_objects() { return geometry_objects; } std::vector<std::shared_ptr<BaseChkptMol>> checkpointed_molecules; virtual void set_checkpointed_molecules(const std::vector<std::shared_ptr<BaseChkptMol>> new_checkpointed_molecules_) { checkpointed_molecules = new_checkpointed_molecules_; } virtual std::vector<std::shared_ptr<BaseChkptMol>>& get_checkpointed_molecules() { return checkpointed_molecules; } // --- methods --- virtual void add_release_site(std::shared_ptr<ReleaseSite> s) = 0; virtual std::shared_ptr<ReleaseSite> find_release_site(const std::string& name) = 0; virtual void add_geometry_object(std::shared_ptr<GeometryObject> o) = 0; virtual std::shared_ptr<GeometryObject> find_geometry_object(const std::string& name) = 0; virtual std::shared_ptr<GeometryObject> find_volume_compartment_object(const std::string& name) = 0; virtual std::shared_ptr<GeometryObject> find_surface_compartment_object(const std::string& name) = 0; virtual void load_bngl_compartments_and_seed_species(const std::string& file_name, std::shared_ptr<Region> default_release_region = nullptr, const std::map<std::string, double>& parameter_overrides = std::map<std::string, double>()) = 0; }; // GenInstantiation class Instantiation; py::class_<Instantiation> define_pybinding_Instantiation(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_INSTANTIATION_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_count_term.cpp
.cpp
13,921
347
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_count_term.h" #include "api/count_term.h" #include "api/complex.h" #include "api/count_term.h" #include "api/reaction_rule.h" #include "api/region.h" namespace MCell { namespace API { void GenCountTerm::check_semantics() const { } void GenCountTerm::set_initialized() { if (is_set(species_pattern)) { species_pattern->set_initialized(); } if (is_set(molecules_pattern)) { molecules_pattern->set_initialized(); } if (is_set(reaction_rule)) { reaction_rule->set_initialized(); } if (is_set(region)) { region->set_initialized(); } if (is_set(left_node)) { left_node->set_initialized(); } if (is_set(right_node)) { right_node->set_initialized(); } initialized = true; } void GenCountTerm::set_all_attributes_as_default_or_unset() { class_name = "CountTerm"; species_pattern = nullptr; molecules_pattern = nullptr; reaction_rule = nullptr; region = nullptr; node_type = ExprNodeType::LEAF; left_node = nullptr; right_node = nullptr; initial_reactions_count = 0; } std::shared_ptr<CountTerm> GenCountTerm::copy_count_term() const { std::shared_ptr<CountTerm> res = std::make_shared<CountTerm>(DefaultCtorArgType()); res->class_name = class_name; res->species_pattern = species_pattern; res->molecules_pattern = molecules_pattern; res->reaction_rule = reaction_rule; res->region = region; res->node_type = node_type; res->left_node = left_node; res->right_node = right_node; res->initial_reactions_count = initial_reactions_count; return res; } std::shared_ptr<CountTerm> GenCountTerm::deepcopy_count_term(py::dict) const { std::shared_ptr<CountTerm> res = std::make_shared<CountTerm>(DefaultCtorArgType()); res->class_name = class_name; res->species_pattern = is_set(species_pattern) ? species_pattern->deepcopy_complex() : nullptr; res->molecules_pattern = is_set(molecules_pattern) ? molecules_pattern->deepcopy_complex() : nullptr; res->reaction_rule = is_set(reaction_rule) ? reaction_rule->deepcopy_reaction_rule() : nullptr; res->region = is_set(region) ? region->deepcopy_region() : nullptr; res->node_type = node_type; res->left_node = is_set(left_node) ? left_node->deepcopy_count_term() : nullptr; res->right_node = is_set(right_node) ? right_node->deepcopy_count_term() : nullptr; res->initial_reactions_count = initial_reactions_count; return res; } bool GenCountTerm::__eq__(const CountTerm& other) const { return ( (is_set(species_pattern)) ? (is_set(other.species_pattern) ? (species_pattern->__eq__(*other.species_pattern)) : false ) : (is_set(other.species_pattern) ? false : true ) ) && ( (is_set(molecules_pattern)) ? (is_set(other.molecules_pattern) ? (molecules_pattern->__eq__(*other.molecules_pattern)) : false ) : (is_set(other.molecules_pattern) ? false : true ) ) && ( (is_set(reaction_rule)) ? (is_set(other.reaction_rule) ? (reaction_rule->__eq__(*other.reaction_rule)) : false ) : (is_set(other.reaction_rule) ? false : true ) ) && ( (is_set(region)) ? (is_set(other.region) ? (region->__eq__(*other.region)) : false ) : (is_set(other.region) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) && initial_reactions_count == other.initial_reactions_count; } bool GenCountTerm::eq_nonarray_attributes(const CountTerm& other, const bool ignore_name) const { return ( (is_set(species_pattern)) ? (is_set(other.species_pattern) ? (species_pattern->__eq__(*other.species_pattern)) : false ) : (is_set(other.species_pattern) ? false : true ) ) && ( (is_set(molecules_pattern)) ? (is_set(other.molecules_pattern) ? (molecules_pattern->__eq__(*other.molecules_pattern)) : false ) : (is_set(other.molecules_pattern) ? false : true ) ) && ( (is_set(reaction_rule)) ? (is_set(other.reaction_rule) ? (reaction_rule->__eq__(*other.reaction_rule)) : false ) : (is_set(other.reaction_rule) ? false : true ) ) && ( (is_set(region)) ? (is_set(other.region) ? (region->__eq__(*other.region)) : false ) : (is_set(other.region) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) && initial_reactions_count == other.initial_reactions_count; } std::string GenCountTerm::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "species_pattern=" << "(" << ((species_pattern != nullptr) ? species_pattern->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "molecules_pattern=" << "(" << ((molecules_pattern != nullptr) ? molecules_pattern->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "reaction_rule=" << "(" << ((reaction_rule != nullptr) ? reaction_rule->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "region=" << "(" << ((region != nullptr) ? region->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "node_type=" << node_type << ", " << "\n" << ind + " " << "left_node=" << "(" << ((left_node != nullptr) ? left_node->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "right_node=" << "(" << ((right_node != nullptr) ? right_node->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "initial_reactions_count=" << initial_reactions_count; return ss.str(); } py::class_<CountTerm> define_pybinding_CountTerm(py::module& m) { return py::class_<CountTerm, std::shared_ptr<CountTerm>>(m, "CountTerm", "A count observable can be defined as an expression composed of addition\nor subtraction individual count terms. This class represents one count term\nin this expression.\n \n") .def( py::init< std::shared_ptr<Complex>, std::shared_ptr<Complex>, std::shared_ptr<ReactionRule>, std::shared_ptr<Region>, const ExprNodeType, std::shared_ptr<CountTerm>, std::shared_ptr<CountTerm>, const uint64_t >(), py::arg("species_pattern") = nullptr, py::arg("molecules_pattern") = nullptr, py::arg("reaction_rule") = nullptr, py::arg("region") = nullptr, py::arg("node_type") = ExprNodeType::LEAF, py::arg("left_node") = nullptr, py::arg("right_node") = nullptr, py::arg("initial_reactions_count") = 0 ) .def("check_semantics", &CountTerm::check_semantics) .def("__copy__", &CountTerm::copy_count_term) .def("__deepcopy__", &CountTerm::deepcopy_count_term, py::arg("memo")) .def("__str__", &CountTerm::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &CountTerm::__eq__, py::arg("other")) .def("__add__", &CountTerm::__add__, py::arg("op2"), "Create a new CountTerm that represents addition of two count terms.\nUsually used through operator '+' such as in ct1 + ct2. \n\n- op2\n") .def("__sub__", &CountTerm::__sub__, py::arg("op2"), "Create a new CountTerm that represents subtraction of two count terms.\nUsually used through operator '-' such as in ct1 - ct2. \n\n- op2\n") .def("dump", &CountTerm::dump) .def_property("species_pattern", &CountTerm::get_species_pattern, &CountTerm::set_species_pattern, "Count the number of molecules that match the given complex instance pattern.\nThis corresponds to the BNGL 'Species' specifier in the BNGL seed species section.\nCounts each molecule exactly once. \nIf the pattern has a compartment set, this specifies the counted region.\nExactly one of species_pattern, molecules_pattern, and reaction_rule must be set. \n") .def_property("molecules_pattern", &CountTerm::get_molecules_pattern, &CountTerm::set_molecules_pattern, "Count the number of matches of the given pattern on molecules.\nThis corresponds to the BNGL 'Molecules' specifier in the BNGL seed species section.\nThe observable will increment the count every time the pattern matches the molecule.\nFor instance, pattern A will match a complex A(a!1).B(a!1,a!2).A(b!2) twice. \nWhen the pattern is symmetric, e.g. as in A(a!1).A(a!1) then a \nmolecule A(b.a!1).A(a!1,b!2).B(a!2) will be counted twice because the \npattern may match in two different ways. \nIf the pattern has a compartment set, the compartment is used to filter out the molecules. \nExactly one of species_pattern, molecules_pattern, and reaction_rule must be set.\n") .def_property("reaction_rule", &CountTerm::get_reaction_rule, &CountTerm::set_reaction_rule, "Count the number of applications of this specific reactions that occurred since the\nstart of the simulation.\nExactly one of species_pattern, molecules_pattern, and reaction_rule must be set.\n \n") .def_property("region", &CountTerm::get_region, &CountTerm::set_region, "Only a GeometryObject or SurfaceRegion can be passed as the region argument, \ncompound regions (created with +, -, *) are not supproted yet. \nCan be combined with a compartment specified in the species_pattern or molecules_pattern.\nIf compartment in species_pattern or molecules_pattern is not specified and \nregion is left unset, counting is done in the whole world.\n") .def_property("node_type", &CountTerm::get_node_type, &CountTerm::set_node_type, "Internal, used to specify what type of count expression node this object represents.") .def_property("left_node", &CountTerm::get_left_node, &CountTerm::set_left_node, "Internal, when node_type is not Leaf, this is the left operand.") .def_property("right_node", &CountTerm::get_right_node, &CountTerm::set_right_node, "Internal, when node_type is not Leaf, this is the right operand.") .def_property("initial_reactions_count", &CountTerm::get_initial_reactions_count, &CountTerm::set_initial_reactions_count, "Used for checkpointing, allows to set initial count of reactions that occurred.\nIgnored when molecules are counted.\n") ; } std::string GenCountTerm::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "count_term_" + std::to_string(ctx.postinc_counter("count_term")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.CountTerm(" << nl; if (is_set(species_pattern)) { ss << ind << "species_pattern = " << species_pattern->export_to_python(out, ctx) << "," << nl; } if (is_set(molecules_pattern)) { ss << ind << "molecules_pattern = " << molecules_pattern->export_to_python(out, ctx) << "," << nl; } if (is_set(reaction_rule)) { ss << ind << "reaction_rule = " << reaction_rule->export_to_python(out, ctx) << "," << nl; } if (is_set(region)) { ss << ind << "region = " << region->export_to_python(out, ctx) << "," << nl; } if (node_type != ExprNodeType::LEAF) { ss << ind << "node_type = " << node_type << "," << nl; } if (is_set(left_node)) { ss << ind << "left_node = " << left_node->export_to_python(out, ctx) << "," << nl; } if (is_set(right_node)) { ss << ind << "right_node = " << right_node->export_to_python(out, ctx) << "," << nl; } if (initial_reactions_count != 0) { ss << ind << "initial_reactions_count = " << initial_reactions_count << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_run_utils.h
.h
836
34
/****************************************************************************** * * Copyright (C) 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 API_GEN_RUN_UTILS_H #define API_GEN_RUN_UTILS_H #include "api/api_common.h" namespace MCell { namespace API { class PythonExportContext; namespace run_utils { std::string get_last_checkpoint_dir(const int seed); std::vector<std::string> remove_cwd(const std::vector<std::string> paths); } // namespace run_utils void define_pybinding_run_utils(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_RUN_UTILS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_observables.cpp
.cpp
8,079
179
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_observables.h" #include "api/observables.h" #include "api/count.h" #include "api/viz_output.h" namespace MCell { namespace API { std::shared_ptr<Observables> GenObservables::copy_observables() const { std::shared_ptr<Observables> res = std::make_shared<Observables>(DefaultCtorArgType()); res->viz_outputs = viz_outputs; res->counts = counts; return res; } std::shared_ptr<Observables> GenObservables::deepcopy_observables(py::dict) const { std::shared_ptr<Observables> res = std::make_shared<Observables>(DefaultCtorArgType()); for (const auto& item: viz_outputs) { res->viz_outputs.push_back((is_set(item)) ? item->deepcopy_viz_output() : nullptr); } for (const auto& item: counts) { res->counts.push_back((is_set(item)) ? item->deepcopy_count() : nullptr); } return res; } bool GenObservables::__eq__(const Observables& other) const { return vec_ptr_eq(viz_outputs, other.viz_outputs) && vec_ptr_eq(counts, other.counts); } bool GenObservables::eq_nonarray_attributes(const Observables& other, const bool ignore_name) const { return true /*viz_outputs*/ && true /*counts*/; } std::string GenObservables::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "Observables" << ": " << "\n" << ind + " " << "viz_outputs=" << vec_ptr_to_str(viz_outputs, all_details, ind + " ") << ", " << "\n" << ind + " " << "counts=" << vec_ptr_to_str(counts, all_details, ind + " "); return ss.str(); } py::class_<Observables> define_pybinding_Observables(py::module& m) { return py::class_<Observables, std::shared_ptr<Observables>>(m, "Observables", "Container used to hold observables-related model data. \nObservables are the measured values of the system. \nThis class also includes information on visualization of simulation.\n") .def( py::init< const std::vector<std::shared_ptr<VizOutput>>, const std::vector<std::shared_ptr<Count>> >(), py::arg("viz_outputs") = std::vector<std::shared_ptr<VizOutput>>(), py::arg("counts") = std::vector<std::shared_ptr<Count>>() ) .def("__copy__", &Observables::copy_observables) .def("__deepcopy__", &Observables::deepcopy_observables, py::arg("memo")) .def("__str__", &Observables::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Observables::__eq__, py::arg("other")) .def("add_viz_output", &Observables::add_viz_output, py::arg("viz_output"), "Adds a reference to the viz_output object to the list of visualization output specifications.\n- viz_output\n") .def("add_count", &Observables::add_count, py::arg("count"), "Adds a reference to the count object to the list of count specifications.\n- count\n") .def("find_count", &Observables::find_count, py::arg("name"), "Finds a count object by its name, returns None if no such count is present.\n- name\n") .def("load_bngl_observables", &Observables::load_bngl_observables, py::arg("file_name"), py::arg("observables_path_or_file") = STR_UNSET, py::arg("parameter_overrides") = std::map<std::string, double>(), py::arg("observables_output_format") = CountOutputFormat::AUTOMATIC_FROM_EXTENSION, "Loads section observables from a BNGL file and creates Count objects according to it.\nAll elementary molecule types used in the seed species section must be defined in subsystem.\n\n- file_name: Path to the BNGL file.\n\n- observables_path_or_file: Directory prefix or file name where observable values will be stored.\nIf a directory such as './react_data/seed_' + str(SEED).zfill(5) + '/' or an empty \nstring/unset is used, each observable gets its own file and the output file format for created Count \nobjects is CountOutputFormat.DAT.\nWhen not set, this path is used: './react_data/seed_' + str(model.config.seed).zfill(5) + '/'.\nIf a file has a .gdat extension such as \n'./react_data/seed_' + str(SEED).zfill(5) + '/counts.gdat', all observable are stored in this \nfile and the output file format for created Count objects is CountOutputFormat.GDAT.\nMust not be empty when observables_output_format is explicitly set to CountOutputFormat.GDAT.\n\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n- observables_output_format: Selection of output format. Default setting uses automatic detection\nbased on contents of the 'observables_path_or_file' attribute.\n \n\n\n") .def("dump", &Observables::dump) .def_property("viz_outputs", &Observables::get_viz_outputs, &Observables::set_viz_outputs, py::return_value_policy::reference, "List of visualization outputs to be included in the model.\nThere is usually just one VizOutput object. \n") .def_property("counts", &Observables::get_counts, &Observables::set_counts, py::return_value_policy::reference, "List of counts to be included in the model.\n") ; } std::string GenObservables::export_to_python(std::ostream& out, PythonExportContext& ctx) { std::string exported_name = "observables"; bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Observables(" << nl; if (viz_outputs != std::vector<std::shared_ptr<VizOutput>>() && !skip_vectors_export()) { ss << ind << "viz_outputs = " << export_vec_viz_outputs(out, ctx, exported_name) << "," << nl; } if (counts != std::vector<std::shared_ptr<Count>>() && !skip_vectors_export()) { ss << ind << "counts = " << export_vec_counts(out, ctx, exported_name) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenObservables::export_vec_viz_outputs(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_viz_outputs"; } else { exported_name = "viz_outputs"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < viz_outputs.size(); i++) { const auto& item = viz_outputs[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenObservables::export_vec_counts(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_counts"; } else { exported_name = "counts"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < counts.size(); i++) { const auto& item = counts[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_molecule_release_info.h
.h
3,700
103
/****************************************************************************** * * Copyright (C) 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 API_GEN_MOLECULE_RELEASE_INFO_H #define API_GEN_MOLECULE_RELEASE_INFO_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class MoleculeReleaseInfo; class Complex; class PythonExportContext; #define MOLECULE_RELEASE_INFO_CTOR() \ MoleculeReleaseInfo( \ std::shared_ptr<Complex> complex_, \ const std::vector<double> location_ \ ) { \ class_name = "MoleculeReleaseInfo"; \ complex = complex_; \ location = location_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ MoleculeReleaseInfo(DefaultCtorArgType) : \ GenMoleculeReleaseInfo(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenMoleculeReleaseInfo: public BaseDataClass { public: GenMoleculeReleaseInfo() { } GenMoleculeReleaseInfo(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<MoleculeReleaseInfo> copy_molecule_release_info() const; std::shared_ptr<MoleculeReleaseInfo> deepcopy_molecule_release_info(py::dict = py::dict()) const; virtual bool __eq__(const MoleculeReleaseInfo& other) const; virtual bool eq_nonarray_attributes(const MoleculeReleaseInfo& other, const bool ignore_name = false) const; bool operator == (const MoleculeReleaseInfo& other) const { return __eq__(other);} bool operator != (const MoleculeReleaseInfo& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_location(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::shared_ptr<Complex> complex; virtual void set_complex(std::shared_ptr<Complex> new_complex_) { if (initialized) { throw RuntimeError("Value 'complex' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; complex = new_complex_; } virtual std::shared_ptr<Complex> get_complex() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return complex; } std::vector<double> location; virtual void set_location(const std::vector<double> new_location_) { if (initialized) { throw RuntimeError("Value 'location' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; location = new_location_; } virtual std::vector<double>& get_location() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return location; } // --- methods --- }; // GenMoleculeReleaseInfo class MoleculeReleaseInfo; py::class_<MoleculeReleaseInfo> define_pybinding_MoleculeReleaseInfo(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_MOLECULE_RELEASE_INFO_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_surface_property.h
.h
4,312
118
/****************************************************************************** * * Copyright (C) 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 API_GEN_SURFACE_PROPERTY_H #define API_GEN_SURFACE_PROPERTY_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class SurfaceProperty; class Complex; class PythonExportContext; #define SURFACE_PROPERTY_CTOR() \ SurfaceProperty( \ const SurfacePropertyType type_ = SurfacePropertyType::UNSET, \ std::shared_ptr<Complex> affected_complex_pattern_ = nullptr, \ const double concentration_ = FLT_UNSET \ ) { \ class_name = "SurfaceProperty"; \ type = type_; \ affected_complex_pattern = affected_complex_pattern_; \ concentration = concentration_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ SurfaceProperty(DefaultCtorArgType) : \ GenSurfaceProperty(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenSurfaceProperty: public BaseDataClass { public: GenSurfaceProperty() { } GenSurfaceProperty(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<SurfaceProperty> copy_surface_property() const; std::shared_ptr<SurfaceProperty> deepcopy_surface_property(py::dict = py::dict()) const; virtual bool __eq__(const SurfaceProperty& other) const; virtual bool eq_nonarray_attributes(const SurfaceProperty& other, const bool ignore_name = false) const; bool operator == (const SurfaceProperty& other) const { return __eq__(other);} bool operator != (const SurfaceProperty& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- SurfacePropertyType type; virtual void set_type(const SurfacePropertyType new_type_) { if (initialized) { throw RuntimeError("Value 'type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; type = new_type_; } virtual SurfacePropertyType get_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return type; } std::shared_ptr<Complex> affected_complex_pattern; virtual void set_affected_complex_pattern(std::shared_ptr<Complex> new_affected_complex_pattern_) { if (initialized) { throw RuntimeError("Value 'affected_complex_pattern' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; affected_complex_pattern = new_affected_complex_pattern_; } virtual std::shared_ptr<Complex> get_affected_complex_pattern() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return affected_complex_pattern; } double concentration; virtual void set_concentration(const double new_concentration_) { if (initialized) { throw RuntimeError("Value 'concentration' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; concentration = new_concentration_; } virtual double get_concentration() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return concentration; } // --- methods --- }; // GenSurfaceProperty class SurfaceProperty; py::class_<SurfaceProperty> define_pybinding_SurfaceProperty(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_SURFACE_PROPERTY_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_molecule_release_info.cpp
.cpp
6,397
175
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_molecule_release_info.h" #include "api/molecule_release_info.h" #include "api/complex.h" namespace MCell { namespace API { void GenMoleculeReleaseInfo::check_semantics() const { if (!is_set(complex)) { throw ValueError("Parameter 'complex' must be set."); } if (!is_set(location)) { throw ValueError("Parameter 'location' must be set and the value must not be an empty list."); } } void GenMoleculeReleaseInfo::set_initialized() { if (is_set(complex)) { complex->set_initialized(); } initialized = true; } void GenMoleculeReleaseInfo::set_all_attributes_as_default_or_unset() { class_name = "MoleculeReleaseInfo"; complex = nullptr; location = std::vector<double>(); } std::shared_ptr<MoleculeReleaseInfo> GenMoleculeReleaseInfo::copy_molecule_release_info() const { std::shared_ptr<MoleculeReleaseInfo> res = std::make_shared<MoleculeReleaseInfo>(DefaultCtorArgType()); res->class_name = class_name; res->complex = complex; res->location = location; return res; } std::shared_ptr<MoleculeReleaseInfo> GenMoleculeReleaseInfo::deepcopy_molecule_release_info(py::dict) const { std::shared_ptr<MoleculeReleaseInfo> res = std::make_shared<MoleculeReleaseInfo>(DefaultCtorArgType()); res->class_name = class_name; res->complex = is_set(complex) ? complex->deepcopy_complex() : nullptr; res->location = location; return res; } bool GenMoleculeReleaseInfo::__eq__(const MoleculeReleaseInfo& other) const { return ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && location == other.location; } bool GenMoleculeReleaseInfo::eq_nonarray_attributes(const MoleculeReleaseInfo& other, const bool ignore_name) const { return ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && true /*location*/; } std::string GenMoleculeReleaseInfo::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "complex=" << "(" << ((complex != nullptr) ? complex->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "location=" << vec_nonptr_to_str(location, all_details, ind + " "); return ss.str(); } py::class_<MoleculeReleaseInfo> define_pybinding_MoleculeReleaseInfo(py::module& m) { return py::class_<MoleculeReleaseInfo, std::shared_ptr<MoleculeReleaseInfo>>(m, "MoleculeReleaseInfo", "Defines a pair (molecule, location). Used in ReleaseSite when its shape is Shape.LIST.\n") .def( py::init< std::shared_ptr<Complex>, const std::vector<double> >(), py::arg("complex"), py::arg("location") ) .def("check_semantics", &MoleculeReleaseInfo::check_semantics) .def("__copy__", &MoleculeReleaseInfo::copy_molecule_release_info) .def("__deepcopy__", &MoleculeReleaseInfo::deepcopy_molecule_release_info, py::arg("memo")) .def("__str__", &MoleculeReleaseInfo::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &MoleculeReleaseInfo::__eq__, py::arg("other")) .def("dump", &MoleculeReleaseInfo::dump) .def_property("complex", &MoleculeReleaseInfo::get_complex, &MoleculeReleaseInfo::set_complex, "Complex instance defining the molecule that will be released.\nOrientation of the complex instance is used to define orientation of the released molecule,\nwhen Orientation.DEFAULT is set, volume molecules are released with Orientation.NONE and\nsurface molecules are released with Orientation.UP.\nCompartment must not be set because this specific release definition states the location. \n") .def_property("location", &MoleculeReleaseInfo::get_location, &MoleculeReleaseInfo::set_location, py::return_value_policy::reference, "3D position where the molecule will be released. \nIf a molecule has a 2D diffusion constant, it will be\nplaced on the surface closest to the coordinate given. \nArgument must have exactly three floating point values [x, y, z].\n \n") ; } std::string GenMoleculeReleaseInfo::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "molecule_release_info_" + std::to_string(ctx.postinc_counter("molecule_release_info")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.MoleculeReleaseInfo(" << nl; ss << ind << "complex = " << complex->export_to_python(out, ctx) << "," << nl; ss << ind << "location = " << export_vec_location(out, ctx, exported_name) << "," << nl; ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenMoleculeReleaseInfo::export_vec_location(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < location.size(); i++) { const auto& item = location[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << f_to_str(item) << ", "; } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_instantiation.cpp
.cpp
10,925
227
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_instantiation.h" #include "api/instantiation.h" #include "api/base_chkpt_mol.h" #include "api/geometry_object.h" #include "api/region.h" #include "api/release_site.h" namespace MCell { namespace API { std::shared_ptr<Instantiation> GenInstantiation::copy_instantiation() const { std::shared_ptr<Instantiation> res = std::make_shared<Instantiation>(DefaultCtorArgType()); res->release_sites = release_sites; res->geometry_objects = geometry_objects; res->checkpointed_molecules = checkpointed_molecules; return res; } std::shared_ptr<Instantiation> GenInstantiation::deepcopy_instantiation(py::dict) const { std::shared_ptr<Instantiation> res = std::make_shared<Instantiation>(DefaultCtorArgType()); for (const auto& item: release_sites) { res->release_sites.push_back((is_set(item)) ? item->deepcopy_release_site() : nullptr); } for (const auto& item: geometry_objects) { res->geometry_objects.push_back((is_set(item)) ? item->deepcopy_geometry_object() : nullptr); } for (const auto& item: checkpointed_molecules) { res->checkpointed_molecules.push_back((is_set(item)) ? item->deepcopy_base_chkpt_mol() : nullptr); } return res; } bool GenInstantiation::__eq__(const Instantiation& other) const { return vec_ptr_eq(release_sites, other.release_sites) && vec_ptr_eq(geometry_objects, other.geometry_objects) && vec_ptr_eq(checkpointed_molecules, other.checkpointed_molecules); } bool GenInstantiation::eq_nonarray_attributes(const Instantiation& other, const bool ignore_name) const { return true /*release_sites*/ && true /*geometry_objects*/ && true /*checkpointed_molecules*/; } std::string GenInstantiation::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "Instantiation" << ": " << "\n" << ind + " " << "release_sites=" << vec_ptr_to_str(release_sites, all_details, ind + " ") << ", " << "\n" << ind + " " << "geometry_objects=" << vec_ptr_to_str(geometry_objects, all_details, ind + " ") << ", " << "\n" << ind + " " << "checkpointed_molecules=" << vec_ptr_to_str(checkpointed_molecules, all_details, ind + " "); return ss.str(); } py::class_<Instantiation> define_pybinding_Instantiation(py::module& m) { return py::class_<Instantiation, std::shared_ptr<Instantiation>>(m, "Instantiation", "Container used to hold instantiation-related model data. \nInstantiation is usually specific for each model, defines \nthe geometry and initial setup of molecule releases.\n") .def( py::init< const std::vector<std::shared_ptr<ReleaseSite>>, const std::vector<std::shared_ptr<GeometryObject>>, const std::vector<std::shared_ptr<BaseChkptMol>> >(), py::arg("release_sites") = std::vector<std::shared_ptr<ReleaseSite>>(), py::arg("geometry_objects") = std::vector<std::shared_ptr<GeometryObject>>(), py::arg("checkpointed_molecules") = std::vector<std::shared_ptr<BaseChkptMol>>() ) .def("__copy__", &Instantiation::copy_instantiation) .def("__deepcopy__", &Instantiation::deepcopy_instantiation, py::arg("memo")) .def("__str__", &Instantiation::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Instantiation::__eq__, py::arg("other")) .def("add_release_site", &Instantiation::add_release_site, py::arg("s"), "Adds a reference to the release site s to the list of release sites.\n- s\n") .def("find_release_site", &Instantiation::find_release_site, py::arg("name"), "Finds a release site by its name, returns None if no such release site is present.\n- name\n") .def("add_geometry_object", &Instantiation::add_geometry_object, py::arg("o"), "Adds a reference to the geometry object o to the list of geometry objects.\n- o\n") .def("find_geometry_object", &Instantiation::find_geometry_object, py::arg("name"), "Finds a geometry object by its name, returns None if no such geometry object is present.\n- name\n") .def("find_volume_compartment_object", &Instantiation::find_volume_compartment_object, py::arg("name"), "Finds a geometry object by its name, the geometry object must be a BNGL compartment.\nReturns None if no such geometry object is present.\n\n- name\n") .def("find_surface_compartment_object", &Instantiation::find_surface_compartment_object, py::arg("name"), "Finds a geometry object that is a BNGL compartment and its surface name is name.\nReturns None if no such geometry object is present.\n\n- name\n") .def("load_bngl_compartments_and_seed_species", &Instantiation::load_bngl_compartments_and_seed_species, py::arg("file_name"), py::arg("default_release_region") = nullptr, py::arg("parameter_overrides") = std::map<std::string, double>(), "First loads section compartments and for each 3D compartment that does not \nalready exist as a geometry object in this Instantiation object, creates a \nbox with compartment's volume and also sets its 2D (membrane) compartment name.\nWhen multiple identical geometry objects are added to the final Model object, \nonly one copy is left so one can merge multiple Instantiation objects that created \ncompartments assuming that their volume is the same. \nThen loads section seed species from a BNGL file and creates release sites according to it.\nAll elementary molecule types used in the seed species section must be already defined in subsystem.\nIf an item in the BNGL seed species section does not have its compartment set,\nthe argument default_region must be set and the molecules are then released into or onto the \ndefault_region. \n\n- file_name: Path to the BNGL file.\n\n- default_release_region: Used as region for releases for seed species that have no compartments specified.\n\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n") .def("dump", &Instantiation::dump) .def_property("release_sites", &Instantiation::get_release_sites, &Instantiation::set_release_sites, py::return_value_policy::reference, "List of release sites to be included in the model. \n") .def_property("geometry_objects", &Instantiation::get_geometry_objects, &Instantiation::set_geometry_objects, py::return_value_policy::reference, "List of geometry objects to be included in the model. \n") .def_property("checkpointed_molecules", &Instantiation::get_checkpointed_molecules, &Instantiation::set_checkpointed_molecules, py::return_value_policy::reference, "Used when resuming simulation from a checkpoint.\n") ; } std::string GenInstantiation::export_to_python(std::ostream& out, PythonExportContext& ctx) { std::string exported_name = "instantiation"; bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Instantiation(" << nl; if (release_sites != std::vector<std::shared_ptr<ReleaseSite>>() && !skip_vectors_export()) { ss << ind << "release_sites = " << export_vec_release_sites(out, ctx, exported_name) << "," << nl; } if (geometry_objects != std::vector<std::shared_ptr<GeometryObject>>() && !skip_vectors_export()) { ss << ind << "geometry_objects = " << export_vec_geometry_objects(out, ctx, exported_name) << "," << nl; } if (checkpointed_molecules != std::vector<std::shared_ptr<BaseChkptMol>>() && !skip_vectors_export()) { ss << ind << "checkpointed_molecules = " << export_vec_checkpointed_molecules(out, ctx, exported_name) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenInstantiation::export_vec_release_sites(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_release_sites"; } else { exported_name = "release_sites"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < release_sites.size(); i++) { const auto& item = release_sites[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenInstantiation::export_vec_geometry_objects(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_geometry_objects"; } else { exported_name = "geometry_objects"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < geometry_objects.size(); i++) { const auto& item = geometry_objects[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenInstantiation::export_vec_checkpointed_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_checkpointed_molecules"; } else { exported_name = "checkpointed_molecules"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < checkpointed_molecules.size(); i++) { const auto& item = checkpointed_molecules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_geometry_utils.cpp
.cpp
2,190
33
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_geometry_utils.h" #include "api/geometry_object.h" #include "api/model.h" namespace MCell { namespace API { void define_pybinding_geometry_utils(py::module& m) { m.def_submodule("geometry_utils") .def("create_box", &geometry_utils::create_box, py::arg("name"), py::arg("edge_dimension") = FLT_UNSET, py::arg("xyz_dimensions") = std::vector<double>(), "Creates a GeometryObject in the shape of a cube whose center is at (0, 0, 0).\n- name: Name of the created geometry object.\n\n- edge_dimension: Specifies length of each edge of the box in um. \nNone of x/y/z dimensions can be set.\n\n\n- xyz_dimensions: Specifies x/y/z sizes of the box in um. Parameter edge_dimension must not be set.\n\n") .def("create_icosphere", &geometry_utils::create_icosphere, py::arg("name"), py::arg("radius"), py::arg("subdivisions"), "Creates a GeometryObject in the shape of an icosphere whose center is at (0, 0, 0).\n- name: Name of the created geometry object.\n\n- radius: Specifies radius of the sphere.\n\n- subdivisions: Number of subdivisions from the initial icosphere. \nThe higher this value will be the smoother the icosphere will be.\nAllowed range is between 1 and 8.\n\n\n") .def("validate_volumetric_mesh", &geometry_utils::validate_volumetric_mesh, py::arg("model"), py::arg("geometry_object"), "Checks that the mesh was correctly analyzed, that it has volume and \nall edges have neighboring walls.\nMust be called after model initialization. \nThrows exception with detained message if validation did not pass. \n\n- model: Model object after initialization.\n\n- geometry_object: Geometry object to be checked.\n\n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_component.cpp
.cpp
5,744
169
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_component.h" #include "api/component.h" #include "api/component_type.h" namespace MCell { namespace API { void GenComponent::check_semantics() const { if (!is_set(component_type)) { throw ValueError("Parameter 'component_type' must be set."); } } void GenComponent::set_initialized() { if (is_set(component_type)) { component_type->set_initialized(); } initialized = true; } void GenComponent::set_all_attributes_as_default_or_unset() { class_name = "Component"; component_type = nullptr; state = "STATE_UNSET"; bond = BOND_UNBOUND; } std::shared_ptr<Component> GenComponent::copy_component() const { std::shared_ptr<Component> res = std::make_shared<Component>(DefaultCtorArgType()); res->class_name = class_name; res->component_type = component_type; res->state = state; res->bond = bond; return res; } std::shared_ptr<Component> GenComponent::deepcopy_component(py::dict) const { std::shared_ptr<Component> res = std::make_shared<Component>(DefaultCtorArgType()); res->class_name = class_name; res->component_type = is_set(component_type) ? component_type->deepcopy_component_type() : nullptr; res->state = state; res->bond = bond; return res; } bool GenComponent::__eq__(const Component& other) const { return ( (is_set(component_type)) ? (is_set(other.component_type) ? (component_type->__eq__(*other.component_type)) : false ) : (is_set(other.component_type) ? false : true ) ) && state == other.state && bond == other.bond; } bool GenComponent::eq_nonarray_attributes(const Component& other, const bool ignore_name) const { return ( (is_set(component_type)) ? (is_set(other.component_type) ? (component_type->__eq__(*other.component_type)) : false ) : (is_set(other.component_type) ? false : true ) ) && state == other.state && bond == other.bond; } std::string GenComponent::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "component_type=" << "(" << ((component_type != nullptr) ? component_type->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "state=" << state << ", " << "bond=" << bond; return ss.str(); } py::class_<Component> define_pybinding_Component(py::module& m) { return py::class_<Component, std::shared_ptr<Component>>(m, "Component", "Instance of a component type belonging to a molecule instance.\nA component instance must have its state set if there is at least one allowed state.\nIt is also used to connect molecule instance in a complex instance through bonds.\n") .def( py::init< std::shared_ptr<ComponentType>, const std::string&, const int >(), py::arg("component_type"), py::arg("state") = "STATE_UNSET", py::arg("bond") = BOND_UNBOUND ) .def("check_semantics", &Component::check_semantics) .def("__copy__", &Component::copy_component) .def("__deepcopy__", &Component::deepcopy_component, py::arg("memo")) .def("__str__", &Component::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Component::__eq__, py::arg("other")) .def("to_bngl_str", &Component::to_bngl_str, "Creates a string that corresponds to this component's BNGL representation.") .def("dump", &Component::dump) .def_property("component_type", &Component::get_component_type, &Component::set_component_type, "Reference to a component type.") .def_property("state", &Component::get_state, &Component::set_state, "Specific state value of this component instance.") .def_property("bond", &Component::get_bond, &Component::set_bond, "Specific bond for this component instance.\nIt is either a numberical value such as in A(c!1),\nor one of special values BOND_UNBOUND in A(c), \nBOND_BOUND in A(c!+) or BOND_ANY in A(c!?).\n \n") ; } std::string GenComponent::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "component_" + std::to_string(ctx.postinc_counter("component")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Component(" << nl; ss << ind << "component_type = " << component_type->export_to_python(out, ctx) << "," << nl; if (state != "STATE_UNSET") { ss << ind << "state = " << "'" << state << "'" << "," << nl; } if (bond != BOND_UNBOUND) { ss << ind << "bond = " << bond << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_config.h
.h
18,852
439
/****************************************************************************** * * Copyright (C) 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 API_GEN_CONFIG_H #define API_GEN_CONFIG_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Config; class RngState; class PythonExportContext; #define CONFIG_CTOR() \ Config( \ const int seed_ = 1, \ const double time_step_ = 1e-6, \ const bool use_bng_units_ = false, \ const double surface_grid_density_ = 10000, \ const double interaction_radius_ = FLT_UNSET, \ const double intermembrane_interaction_radius_ = FLT_UNSET, \ const double vacancy_search_distance_ = 10, \ const bool center_molecules_on_grid_ = false, \ const double partition_dimension_ = 10, \ const std::vector<double> initial_partition_origin_ = std::vector<double>(), \ const double subpartition_dimension_ = 0.5, \ const double total_iterations_ = 1000000, \ const bool check_overlapped_walls_ = true, \ const int reaction_class_cleanup_periodicity_ = 500, \ const int species_cleanup_periodicity_ = 10000, \ const int molecules_order_random_shuffle_periodicity_ = 10000, \ const bool sort_molecules_ = false, \ const int memory_limit_gb_ = -1, \ const uint64_t initial_iteration_ = 0, \ const double initial_time_ = 0, \ std::shared_ptr<RngState> initial_rng_state_ = nullptr, \ const bool append_to_count_output_data_ = false, \ const bool continue_after_sigalrm_ = false \ ) { \ class_name = "Config"; \ seed = seed_; \ time_step = time_step_; \ use_bng_units = use_bng_units_; \ surface_grid_density = surface_grid_density_; \ interaction_radius = interaction_radius_; \ intermembrane_interaction_radius = intermembrane_interaction_radius_; \ vacancy_search_distance = vacancy_search_distance_; \ center_molecules_on_grid = center_molecules_on_grid_; \ partition_dimension = partition_dimension_; \ initial_partition_origin = initial_partition_origin_; \ subpartition_dimension = subpartition_dimension_; \ total_iterations = total_iterations_; \ check_overlapped_walls = check_overlapped_walls_; \ reaction_class_cleanup_periodicity = reaction_class_cleanup_periodicity_; \ species_cleanup_periodicity = species_cleanup_periodicity_; \ molecules_order_random_shuffle_periodicity = molecules_order_random_shuffle_periodicity_; \ sort_molecules = sort_molecules_; \ memory_limit_gb = memory_limit_gb_; \ initial_iteration = initial_iteration_; \ initial_time = initial_time_; \ initial_rng_state = initial_rng_state_; \ append_to_count_output_data = append_to_count_output_data_; \ continue_after_sigalrm = continue_after_sigalrm_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Config(DefaultCtorArgType) : \ GenConfig(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenConfig: public BaseDataClass { public: GenConfig() { } GenConfig(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Config> copy_config() const; std::shared_ptr<Config> deepcopy_config(py::dict = py::dict()) const; virtual bool __eq__(const Config& other) const; virtual bool eq_nonarray_attributes(const Config& other, const bool ignore_name = false) const; bool operator == (const Config& other) const { return __eq__(other);} bool operator != (const Config& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_initial_partition_origin(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- int seed; virtual void set_seed(const int new_seed_) { if (initialized) { throw RuntimeError("Value 'seed' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; seed = new_seed_; } virtual int get_seed() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return seed; } double time_step; virtual void set_time_step(const double new_time_step_) { if (initialized) { throw RuntimeError("Value 'time_step' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; time_step = new_time_step_; } virtual double get_time_step() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return time_step; } bool use_bng_units; virtual void set_use_bng_units(const bool new_use_bng_units_) { if (initialized) { throw RuntimeError("Value 'use_bng_units' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; use_bng_units = new_use_bng_units_; } virtual bool get_use_bng_units() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return use_bng_units; } double surface_grid_density; virtual void set_surface_grid_density(const double new_surface_grid_density_) { if (initialized) { throw RuntimeError("Value 'surface_grid_density' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; surface_grid_density = new_surface_grid_density_; } virtual double get_surface_grid_density() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return surface_grid_density; } double interaction_radius; virtual void set_interaction_radius(const double new_interaction_radius_) { if (initialized) { throw RuntimeError("Value 'interaction_radius' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; interaction_radius = new_interaction_radius_; } virtual double get_interaction_radius() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return interaction_radius; } double intermembrane_interaction_radius; virtual void set_intermembrane_interaction_radius(const double new_intermembrane_interaction_radius_) { if (initialized) { throw RuntimeError("Value 'intermembrane_interaction_radius' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; intermembrane_interaction_radius = new_intermembrane_interaction_radius_; } virtual double get_intermembrane_interaction_radius() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return intermembrane_interaction_radius; } double vacancy_search_distance; virtual void set_vacancy_search_distance(const double new_vacancy_search_distance_) { if (initialized) { throw RuntimeError("Value 'vacancy_search_distance' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; vacancy_search_distance = new_vacancy_search_distance_; } virtual double get_vacancy_search_distance() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return vacancy_search_distance; } bool center_molecules_on_grid; virtual void set_center_molecules_on_grid(const bool new_center_molecules_on_grid_) { if (initialized) { throw RuntimeError("Value 'center_molecules_on_grid' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; center_molecules_on_grid = new_center_molecules_on_grid_; } virtual bool get_center_molecules_on_grid() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return center_molecules_on_grid; } double partition_dimension; virtual void set_partition_dimension(const double new_partition_dimension_) { if (initialized) { throw RuntimeError("Value 'partition_dimension' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; partition_dimension = new_partition_dimension_; } virtual double get_partition_dimension() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return partition_dimension; } std::vector<double> initial_partition_origin; virtual void set_initial_partition_origin(const std::vector<double> new_initial_partition_origin_) { if (initialized) { throw RuntimeError("Value 'initial_partition_origin' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_partition_origin = new_initial_partition_origin_; } virtual std::vector<double>& get_initial_partition_origin() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_partition_origin; } double subpartition_dimension; virtual void set_subpartition_dimension(const double new_subpartition_dimension_) { if (initialized) { throw RuntimeError("Value 'subpartition_dimension' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; subpartition_dimension = new_subpartition_dimension_; } virtual double get_subpartition_dimension() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return subpartition_dimension; } double total_iterations; virtual void set_total_iterations(const double new_total_iterations_) { if (initialized) { throw RuntimeError("Value 'total_iterations' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; total_iterations = new_total_iterations_; } virtual double get_total_iterations() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return total_iterations; } bool check_overlapped_walls; virtual void set_check_overlapped_walls(const bool new_check_overlapped_walls_) { if (initialized) { throw RuntimeError("Value 'check_overlapped_walls' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; check_overlapped_walls = new_check_overlapped_walls_; } virtual bool get_check_overlapped_walls() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return check_overlapped_walls; } int reaction_class_cleanup_periodicity; virtual void set_reaction_class_cleanup_periodicity(const int new_reaction_class_cleanup_periodicity_) { if (initialized) { throw RuntimeError("Value 'reaction_class_cleanup_periodicity' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; reaction_class_cleanup_periodicity = new_reaction_class_cleanup_periodicity_; } virtual int get_reaction_class_cleanup_periodicity() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return reaction_class_cleanup_periodicity; } int species_cleanup_periodicity; virtual void set_species_cleanup_periodicity(const int new_species_cleanup_periodicity_) { if (initialized) { throw RuntimeError("Value 'species_cleanup_periodicity' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; species_cleanup_periodicity = new_species_cleanup_periodicity_; } virtual int get_species_cleanup_periodicity() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return species_cleanup_periodicity; } int molecules_order_random_shuffle_periodicity; virtual void set_molecules_order_random_shuffle_periodicity(const int new_molecules_order_random_shuffle_periodicity_) { if (initialized) { throw RuntimeError("Value 'molecules_order_random_shuffle_periodicity' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; molecules_order_random_shuffle_periodicity = new_molecules_order_random_shuffle_periodicity_; } virtual int get_molecules_order_random_shuffle_periodicity() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return molecules_order_random_shuffle_periodicity; } bool sort_molecules; virtual void set_sort_molecules(const bool new_sort_molecules_) { if (initialized) { throw RuntimeError("Value 'sort_molecules' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; sort_molecules = new_sort_molecules_; } virtual bool get_sort_molecules() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return sort_molecules; } int memory_limit_gb; virtual void set_memory_limit_gb(const int new_memory_limit_gb_) { if (initialized) { throw RuntimeError("Value 'memory_limit_gb' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; memory_limit_gb = new_memory_limit_gb_; } virtual int get_memory_limit_gb() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return memory_limit_gb; } uint64_t initial_iteration; virtual void set_initial_iteration(const uint64_t new_initial_iteration_) { if (initialized) { throw RuntimeError("Value 'initial_iteration' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_iteration = new_initial_iteration_; } virtual uint64_t get_initial_iteration() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_iteration; } double initial_time; virtual void set_initial_time(const double new_initial_time_) { if (initialized) { throw RuntimeError("Value 'initial_time' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_time = new_initial_time_; } virtual double get_initial_time() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_time; } std::shared_ptr<RngState> initial_rng_state; virtual void set_initial_rng_state(std::shared_ptr<RngState> new_initial_rng_state_) { if (initialized) { throw RuntimeError("Value 'initial_rng_state' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_rng_state = new_initial_rng_state_; } virtual std::shared_ptr<RngState> get_initial_rng_state() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_rng_state; } bool append_to_count_output_data; virtual void set_append_to_count_output_data(const bool new_append_to_count_output_data_) { if (initialized) { throw RuntimeError("Value 'append_to_count_output_data' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; append_to_count_output_data = new_append_to_count_output_data_; } virtual bool get_append_to_count_output_data() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return append_to_count_output_data; } bool continue_after_sigalrm; virtual void set_continue_after_sigalrm(const bool new_continue_after_sigalrm_) { if (initialized) { throw RuntimeError("Value 'continue_after_sigalrm' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; continue_after_sigalrm = new_continue_after_sigalrm_; } virtual bool get_continue_after_sigalrm() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return continue_after_sigalrm; } // --- methods --- }; // GenConfig class Config; py::class_<Config> define_pybinding_Config(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_CONFIG_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_bngl_utils.cpp
.cpp
1,173
29
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_bngl_utils.h" namespace MCell { namespace API { void define_pybinding_bngl_utils(py::module& m) { m.def_submodule("bngl_utils") .def("load_bngl_parameters", &bngl_utils::load_bngl_parameters, py::arg("file_name"), py::arg("parameter_overrides") = std::map<std::string, double>(), "Load parameters section from a BNGL file and return it as a dictionary name->value.\n- file_name: Path to the BNGL file to be loaded.\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_data_utils.cpp
.cpp
1,011
29
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_data_utils.h" namespace MCell { namespace API { void define_pybinding_data_utils(py::module& m) { m.def_submodule("data_utils") .def("load_dat_file", &data_utils::load_dat_file, py::arg("file_name"), "Loads a two-column file where the first column is usually time and the second is a \nfloating point value. Returns a two-column list. \nCan be used to load a file with variable rate constants. \n\n- file_name: Path to the .dat file to be loaded.\n\n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_surface_region.h
.h
6,158
152
/****************************************************************************** * * Copyright (C) 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 API_GEN_SURFACE_REGION_H #define API_GEN_SURFACE_REGION_H #include "api/api_common.h" #include "api/region.h" namespace MCell { namespace API { class SurfaceRegion; class Color; class InitialSurfaceRelease; class Region; class SurfaceClass; class PythonExportContext; #define SURFACE_REGION_CTOR() \ SurfaceRegion( \ const std::string& name_, \ const std::vector<int> wall_indices_, \ std::shared_ptr<SurfaceClass> surface_class_ = nullptr, \ const std::vector<std::shared_ptr<InitialSurfaceRelease>> initial_surface_releases_ = std::vector<std::shared_ptr<InitialSurfaceRelease>>(), \ std::shared_ptr<Color> initial_color_ = nullptr, \ const RegionNodeType node_type_ = RegionNodeType::UNSET, \ std::shared_ptr<Region> left_node_ = nullptr, \ std::shared_ptr<Region> right_node_ = nullptr \ ) : GenSurfaceRegion(node_type_,left_node_,right_node_) { \ class_name = "SurfaceRegion"; \ name = name_; \ wall_indices = wall_indices_; \ surface_class = surface_class_; \ initial_surface_releases = initial_surface_releases_; \ initial_color = initial_color_; \ node_type = node_type_; \ left_node = left_node_; \ right_node = right_node_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ SurfaceRegion(DefaultCtorArgType) : \ GenSurfaceRegion(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenSurfaceRegion: public Region { public: GenSurfaceRegion( const RegionNodeType node_type_ = RegionNodeType::UNSET, std::shared_ptr<Region> left_node_ = nullptr, std::shared_ptr<Region> right_node_ = nullptr ) : Region(node_type_,left_node_,right_node_) { } GenSurfaceRegion(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<SurfaceRegion> copy_surface_region() const; std::shared_ptr<SurfaceRegion> deepcopy_surface_region(py::dict = py::dict()) const; virtual bool __eq__(const SurfaceRegion& other) const; virtual bool eq_nonarray_attributes(const SurfaceRegion& other, const bool ignore_name = false) const; bool operator == (const SurfaceRegion& other) const { return __eq__(other);} bool operator != (const SurfaceRegion& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_wall_indices(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_initial_surface_releases(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<int> wall_indices; virtual void set_wall_indices(const std::vector<int> new_wall_indices_) { if (initialized) { throw RuntimeError("Value 'wall_indices' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_indices = new_wall_indices_; } virtual std::vector<int>& get_wall_indices() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_indices; } std::shared_ptr<SurfaceClass> surface_class; virtual void set_surface_class(std::shared_ptr<SurfaceClass> new_surface_class_) { if (initialized) { throw RuntimeError("Value 'surface_class' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; surface_class = new_surface_class_; } virtual std::shared_ptr<SurfaceClass> get_surface_class() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return surface_class; } std::vector<std::shared_ptr<InitialSurfaceRelease>> initial_surface_releases; virtual void set_initial_surface_releases(const std::vector<std::shared_ptr<InitialSurfaceRelease>> new_initial_surface_releases_) { if (initialized) { throw RuntimeError("Value 'initial_surface_releases' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_surface_releases = new_initial_surface_releases_; } virtual std::vector<std::shared_ptr<InitialSurfaceRelease>>& get_initial_surface_releases() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_surface_releases; } std::shared_ptr<Color> initial_color; virtual void set_initial_color(std::shared_ptr<Color> new_initial_color_) { if (initialized) { throw RuntimeError("Value 'initial_color' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_color = new_initial_color_; } virtual std::shared_ptr<Color> get_initial_color() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_color; } // --- methods --- }; // GenSurfaceRegion class SurfaceRegion; py::class_<SurfaceRegion> define_pybinding_SurfaceRegion(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_SURFACE_REGION_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_reaction_info.h
.h
3,426
122
/****************************************************************************** * * Copyright (C) 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 API_GEN_REACTION_INFO_H #define API_GEN_REACTION_INFO_H #include "api/api_common.h" namespace MCell { namespace API { class ReactionInfo; class GeometryObject; class ReactionRule; class PythonExportContext; class GenReactionInfo { public: GenReactionInfo() { } GenReactionInfo(DefaultCtorArgType) { } virtual ~GenReactionInfo() {} std::shared_ptr<ReactionInfo> copy_reaction_info() const; std::shared_ptr<ReactionInfo> deepcopy_reaction_info(py::dict = py::dict()) const; virtual bool __eq__(const ReactionInfo& other) const; virtual bool eq_nonarray_attributes(const ReactionInfo& other, const bool ignore_name = false) const; bool operator == (const ReactionInfo& other) const { return __eq__(other);} bool operator != (const ReactionInfo& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; // --- attributes --- ReactionType type; virtual void set_type(const ReactionType new_type_) { type = new_type_; } virtual ReactionType get_type() const { return type; } std::vector<int> reactant_ids; virtual void set_reactant_ids(const std::vector<int> new_reactant_ids_) { reactant_ids = new_reactant_ids_; } virtual std::vector<int>& get_reactant_ids() { return reactant_ids; } std::vector<int> product_ids; virtual void set_product_ids(const std::vector<int> new_product_ids_) { product_ids = new_product_ids_; } virtual std::vector<int>& get_product_ids() { return product_ids; } std::shared_ptr<ReactionRule> reaction_rule; virtual void set_reaction_rule(std::shared_ptr<ReactionRule> new_reaction_rule_) { reaction_rule = new_reaction_rule_; } virtual std::shared_ptr<ReactionRule> get_reaction_rule() const { return reaction_rule; } double time; virtual void set_time(const double new_time_) { time = new_time_; } virtual double get_time() const { return time; } std::vector<double> pos3d; virtual void set_pos3d(const std::vector<double> new_pos3d_) { pos3d = new_pos3d_; } virtual std::vector<double>& get_pos3d() { return pos3d; } std::shared_ptr<GeometryObject> geometry_object; virtual void set_geometry_object(std::shared_ptr<GeometryObject> new_geometry_object_) { geometry_object = new_geometry_object_; } virtual std::shared_ptr<GeometryObject> get_geometry_object() const { return geometry_object; } int wall_index; virtual void set_wall_index(const int new_wall_index_) { wall_index = new_wall_index_; } virtual int get_wall_index() const { return wall_index; } std::vector<double> pos2d; virtual void set_pos2d(const std::vector<double> new_pos2d_) { pos2d = new_pos2d_; } virtual std::vector<double>& get_pos2d() { return pos2d; } // --- methods --- }; // GenReactionInfo class ReactionInfo; py::class_<ReactionInfo> define_pybinding_ReactionInfo(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_REACTION_INFO_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_warnings.h
.h
3,671
101
/****************************************************************************** * * Copyright (C) 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 API_GEN_WARNINGS_H #define API_GEN_WARNINGS_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Warnings; class PythonExportContext; #define WARNINGS_CTOR() \ Warnings( \ const WarningLevel high_reaction_probability_ = WarningLevel::IGNORE, \ const WarningLevel molecule_placement_failure_ = WarningLevel::ERROR \ ) { \ class_name = "Warnings"; \ high_reaction_probability = high_reaction_probability_; \ molecule_placement_failure = molecule_placement_failure_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Warnings(DefaultCtorArgType) : \ GenWarnings(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenWarnings: public BaseDataClass { public: GenWarnings() { } GenWarnings(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Warnings> copy_warnings() const; std::shared_ptr<Warnings> deepcopy_warnings(py::dict = py::dict()) const; virtual bool __eq__(const Warnings& other) const; virtual bool eq_nonarray_attributes(const Warnings& other, const bool ignore_name = false) const; bool operator == (const Warnings& other) const { return __eq__(other);} bool operator != (const Warnings& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- WarningLevel high_reaction_probability; virtual void set_high_reaction_probability(const WarningLevel new_high_reaction_probability_) { if (initialized) { throw RuntimeError("Value 'high_reaction_probability' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; high_reaction_probability = new_high_reaction_probability_; } virtual WarningLevel get_high_reaction_probability() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return high_reaction_probability; } WarningLevel molecule_placement_failure; virtual void set_molecule_placement_failure(const WarningLevel new_molecule_placement_failure_) { if (initialized) { throw RuntimeError("Value 'molecule_placement_failure' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; molecule_placement_failure = new_molecule_placement_failure_; } virtual WarningLevel get_molecule_placement_failure() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return molecule_placement_failure; } // --- methods --- }; // GenWarnings class Warnings; py::class_<Warnings> define_pybinding_Warnings(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_WARNINGS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_reaction_rule.h
.h
7,557
188
/****************************************************************************** * * Copyright (C) 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 API_GEN_REACTION_RULE_H #define API_GEN_REACTION_RULE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ReactionRule; class Complex; class PythonExportContext; #define REACTION_RULE_CTOR() \ ReactionRule( \ const std::string& name_ = STR_UNSET, \ const std::vector<std::shared_ptr<Complex>> reactants_ = std::vector<std::shared_ptr<Complex>>(), \ const std::vector<std::shared_ptr<Complex>> products_ = std::vector<std::shared_ptr<Complex>>(), \ const double fwd_rate_ = FLT_UNSET, \ const std::string& rev_name_ = STR_UNSET, \ const double rev_rate_ = FLT_UNSET, \ const std::vector<std::vector<double>> variable_rate_ = std::vector<std::vector<double>>(), \ const bool is_intermembrane_surface_reaction_ = false \ ) { \ class_name = "ReactionRule"; \ name = name_; \ reactants = reactants_; \ products = products_; \ fwd_rate = fwd_rate_; \ rev_name = rev_name_; \ rev_rate = rev_rate_; \ variable_rate = variable_rate_; \ is_intermembrane_surface_reaction = is_intermembrane_surface_reaction_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ReactionRule(DefaultCtorArgType) : \ GenReactionRule(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenReactionRule: public BaseDataClass { public: GenReactionRule() { } GenReactionRule(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ReactionRule> copy_reaction_rule() const; std::shared_ptr<ReactionRule> deepcopy_reaction_rule(py::dict = py::dict()) const; virtual bool __eq__(const ReactionRule& other) const; virtual bool eq_nonarray_attributes(const ReactionRule& other, const bool ignore_name = false) const; bool operator == (const ReactionRule& other) const { return __eq__(other);} bool operator != (const ReactionRule& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_reactants(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_products(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_variable_rate(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<Complex>> reactants; virtual void set_reactants(const std::vector<std::shared_ptr<Complex>> new_reactants_) { if (initialized) { throw RuntimeError("Value 'reactants' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; reactants = new_reactants_; } virtual std::vector<std::shared_ptr<Complex>>& get_reactants() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return reactants; } std::vector<std::shared_ptr<Complex>> products; virtual void set_products(const std::vector<std::shared_ptr<Complex>> new_products_) { if (initialized) { throw RuntimeError("Value 'products' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; products = new_products_; } virtual std::vector<std::shared_ptr<Complex>>& get_products() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return products; } double fwd_rate; virtual void set_fwd_rate(const double new_fwd_rate_) { if (initialized) { throw RuntimeError("Value 'fwd_rate' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; fwd_rate = new_fwd_rate_; } virtual double get_fwd_rate() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return fwd_rate; } std::string rev_name; virtual void set_rev_name(const std::string& new_rev_name_) { if (initialized) { throw RuntimeError("Value 'rev_name' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rev_name = new_rev_name_; } virtual const std::string& get_rev_name() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rev_name; } double rev_rate; virtual void set_rev_rate(const double new_rev_rate_) { if (initialized) { throw RuntimeError("Value 'rev_rate' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rev_rate = new_rev_rate_; } virtual double get_rev_rate() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rev_rate; } std::vector<std::vector<double>> variable_rate; virtual void set_variable_rate(const std::vector<std::vector<double>> new_variable_rate_) { if (initialized) { throw RuntimeError("Value 'variable_rate' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; variable_rate = new_variable_rate_; } virtual std::vector<std::vector<double>>& get_variable_rate() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return variable_rate; } bool is_intermembrane_surface_reaction; virtual void set_is_intermembrane_surface_reaction(const bool new_is_intermembrane_surface_reaction_) { if (initialized) { throw RuntimeError("Value 'is_intermembrane_surface_reaction' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; is_intermembrane_surface_reaction = new_is_intermembrane_surface_reaction_; } virtual bool get_is_intermembrane_surface_reaction() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return is_intermembrane_surface_reaction; } // --- methods --- virtual std::string to_bngl_str() const = 0; }; // GenReactionRule class ReactionRule; py::class_<ReactionRule> define_pybinding_ReactionRule(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_REACTION_RULE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_surface_region.cpp
.cpp
12,804
340
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_surface_region.h" #include "api/surface_region.h" #include "api/color.h" #include "api/initial_surface_release.h" #include "api/region.h" #include "api/surface_class.h" namespace MCell { namespace API { void GenSurfaceRegion::check_semantics() const { if (!is_set(name)) { throw ValueError("Parameter 'name' must be set."); } if (!is_set(wall_indices)) { throw ValueError("Parameter 'wall_indices' must be set and the value must not be an empty list."); } } void GenSurfaceRegion::set_initialized() { if (is_set(surface_class)) { surface_class->set_initialized(); } vec_set_initialized(initial_surface_releases); if (is_set(initial_color)) { initial_color->set_initialized(); } if (is_set(left_node)) { left_node->set_initialized(); } if (is_set(right_node)) { right_node->set_initialized(); } initialized = true; } void GenSurfaceRegion::set_all_attributes_as_default_or_unset() { class_name = "SurfaceRegion"; name = STR_UNSET; wall_indices = std::vector<int>(); surface_class = nullptr; initial_surface_releases = std::vector<std::shared_ptr<InitialSurfaceRelease>>(); initial_color = nullptr; node_type = RegionNodeType::UNSET; left_node = nullptr; right_node = nullptr; } std::shared_ptr<SurfaceRegion> GenSurfaceRegion::copy_surface_region() const { std::shared_ptr<SurfaceRegion> res = std::make_shared<SurfaceRegion>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->wall_indices = wall_indices; res->surface_class = surface_class; res->initial_surface_releases = initial_surface_releases; res->initial_color = initial_color; res->node_type = node_type; res->left_node = left_node; res->right_node = right_node; return res; } std::shared_ptr<SurfaceRegion> GenSurfaceRegion::deepcopy_surface_region(py::dict) const { std::shared_ptr<SurfaceRegion> res = std::make_shared<SurfaceRegion>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->wall_indices = wall_indices; res->surface_class = is_set(surface_class) ? surface_class->deepcopy_surface_class() : nullptr; for (const auto& item: initial_surface_releases) { res->initial_surface_releases.push_back((is_set(item)) ? item->deepcopy_initial_surface_release() : nullptr); } res->initial_color = is_set(initial_color) ? initial_color->deepcopy_color() : nullptr; res->node_type = node_type; res->left_node = is_set(left_node) ? left_node->deepcopy_region() : nullptr; res->right_node = is_set(right_node) ? right_node->deepcopy_region() : nullptr; return res; } bool GenSurfaceRegion::__eq__(const SurfaceRegion& other) const { return name == other.name && wall_indices == other.wall_indices && ( (is_set(surface_class)) ? (is_set(other.surface_class) ? (surface_class->__eq__(*other.surface_class)) : false ) : (is_set(other.surface_class) ? false : true ) ) && vec_ptr_eq(initial_surface_releases, other.initial_surface_releases) && ( (is_set(initial_color)) ? (is_set(other.initial_color) ? (initial_color->__eq__(*other.initial_color)) : false ) : (is_set(other.initial_color) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } bool GenSurfaceRegion::eq_nonarray_attributes(const SurfaceRegion& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*wall_indices*/ && ( (is_set(surface_class)) ? (is_set(other.surface_class) ? (surface_class->__eq__(*other.surface_class)) : false ) : (is_set(other.surface_class) ? false : true ) ) && true /*initial_surface_releases*/ && ( (is_set(initial_color)) ? (is_set(other.initial_color) ? (initial_color->__eq__(*other.initial_color)) : false ) : (is_set(other.initial_color) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } std::string GenSurfaceRegion::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "wall_indices=" << vec_nonptr_to_str(wall_indices, all_details, ind + " ") << ", " << "\n" << ind + " " << "surface_class=" << "(" << ((surface_class != nullptr) ? surface_class->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "initial_surface_releases=" << vec_ptr_to_str(initial_surface_releases, all_details, ind + " ") << ", " << "\n" << ind + " " << "initial_color=" << "(" << ((initial_color != nullptr) ? initial_color->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "node_type=" << node_type << ", " << "\n" << ind + " " << "left_node=" << "(" << ((left_node != nullptr) ? left_node->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "right_node=" << "(" << ((right_node != nullptr) ? right_node->to_str(all_details, ind + " ") : "null" ) << ")"; return ss.str(); } py::class_<SurfaceRegion> define_pybinding_SurfaceRegion(py::module& m) { return py::class_<SurfaceRegion, Region, std::shared_ptr<SurfaceRegion>>(m, "SurfaceRegion", "Defines a region on the object. The extent of a region is given by the wall_indices list. \nMolecules can be added and surface properties can be set with the optional regional surface commands. \nYou can have an arbitrary number of regions on an object, and they may overlap if\nyou wish. Molecules added to overlapping regions accumulate. Triangles belonging to \nmultiple regions inherit all parent regions’ surface properties. Users\nhave to make sure that in case of overlapped regions their surface properties\nare compatible. \n") .def( py::init< const std::string&, const std::vector<int>, std::shared_ptr<SurfaceClass>, const std::vector<std::shared_ptr<InitialSurfaceRelease>>, std::shared_ptr<Color>, const RegionNodeType, std::shared_ptr<Region>, std::shared_ptr<Region> >(), py::arg("name"), py::arg("wall_indices"), py::arg("surface_class") = nullptr, py::arg("initial_surface_releases") = std::vector<std::shared_ptr<InitialSurfaceRelease>>(), py::arg("initial_color") = nullptr, py::arg("node_type") = RegionNodeType::UNSET, py::arg("left_node") = nullptr, py::arg("right_node") = nullptr ) .def("check_semantics", &SurfaceRegion::check_semantics) .def("__copy__", &SurfaceRegion::copy_surface_region) .def("__deepcopy__", &SurfaceRegion::deepcopy_surface_region, py::arg("memo")) .def("__str__", &SurfaceRegion::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &SurfaceRegion::__eq__, py::arg("other")) .def("dump", &SurfaceRegion::dump) .def_property("name", &SurfaceRegion::get_name, &SurfaceRegion::set_name, "Name of this region.") .def_property("wall_indices", &SurfaceRegion::get_wall_indices, &SurfaceRegion::set_wall_indices, py::return_value_policy::reference, "Surface region must be a part of a GeometryObject, items in this list are indices to \nits wall_list array.\n") .def_property("surface_class", &SurfaceRegion::get_surface_class, &SurfaceRegion::set_surface_class, "Optional surface class assigned to this surface region.\nIf not set, it is inherited from the parent geometry object's surface_class.\n") .def_property("initial_surface_releases", &SurfaceRegion::get_initial_surface_releases, &SurfaceRegion::set_initial_surface_releases, py::return_value_policy::reference, "Each item of this list defines either density or number of molecules to be released on this surface \nregions when simulation starts.\n") .def_property("initial_color", &SurfaceRegion::get_initial_color, &SurfaceRegion::set_initial_color, "Initial color for this specific surface region. If not set, color of the parent's GeometryObject is used.") ; } std::string GenSurfaceRegion::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("surface_region") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("surface_region"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.SurfaceRegion(" << nl; if (node_type != RegionNodeType::UNSET) { ss << ind << "node_type = " << node_type << "," << nl; } if (is_set(left_node)) { ss << ind << "left_node = " << left_node->export_to_python(out, ctx) << "," << nl; } if (is_set(right_node)) { ss << ind << "right_node = " << right_node->export_to_python(out, ctx) << "," << nl; } ss << ind << "name = " << "'" << name << "'" << "," << nl; ss << ind << "wall_indices = " << export_vec_wall_indices(out, ctx, exported_name) << "," << nl; if (is_set(surface_class)) { ss << ind << "surface_class = " << surface_class->export_to_python(out, ctx) << "," << nl; } if (initial_surface_releases != std::vector<std::shared_ptr<InitialSurfaceRelease>>() && !skip_vectors_export()) { ss << ind << "initial_surface_releases = " << export_vec_initial_surface_releases(out, ctx, exported_name) << "," << nl; } if (is_set(initial_color)) { ss << ind << "initial_color = " << initial_color->export_to_python(out, ctx) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenSurfaceRegion::export_vec_wall_indices(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < wall_indices.size(); i++) { const auto& item = wall_indices[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << item << ", "; } ss << "]"; return ss.str(); } std::string GenSurfaceRegion::export_vec_initial_surface_releases(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < initial_surface_releases.size(); i++) { const auto& item = initial_surface_releases[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_rng_state.h
.h
6,207
183
/****************************************************************************** * * Copyright (C) 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 API_GEN_RNG_STATE_H #define API_GEN_RNG_STATE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class RngState; class PythonExportContext; #define RNG_STATE_CTOR() \ RngState( \ const uint64_t randcnt_, \ const uint64_t aa_, \ const uint64_t bb_, \ const uint64_t cc_, \ const std::vector<uint64_t> randslr_, \ const std::vector<uint64_t> mm_, \ const uint64_t rngblocks_ \ ) { \ class_name = "RngState"; \ randcnt = randcnt_; \ aa = aa_; \ bb = bb_; \ cc = cc_; \ randslr = randslr_; \ mm = mm_; \ rngblocks = rngblocks_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ RngState(DefaultCtorArgType) : \ GenRngState(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenRngState: public BaseDataClass { public: GenRngState() { } GenRngState(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<RngState> copy_rng_state() const; std::shared_ptr<RngState> deepcopy_rng_state(py::dict = py::dict()) const; virtual bool __eq__(const RngState& other) const; virtual bool eq_nonarray_attributes(const RngState& other, const bool ignore_name = false) const; bool operator == (const RngState& other) const { return __eq__(other);} bool operator != (const RngState& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_randslr(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_mm(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- uint64_t randcnt; virtual void set_randcnt(const uint64_t new_randcnt_) { if (initialized) { throw RuntimeError("Value 'randcnt' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; randcnt = new_randcnt_; } virtual uint64_t get_randcnt() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return randcnt; } uint64_t aa; virtual void set_aa(const uint64_t new_aa_) { if (initialized) { throw RuntimeError("Value 'aa' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; aa = new_aa_; } virtual uint64_t get_aa() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return aa; } uint64_t bb; virtual void set_bb(const uint64_t new_bb_) { if (initialized) { throw RuntimeError("Value 'bb' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; bb = new_bb_; } virtual uint64_t get_bb() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return bb; } uint64_t cc; virtual void set_cc(const uint64_t new_cc_) { if (initialized) { throw RuntimeError("Value 'cc' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; cc = new_cc_; } virtual uint64_t get_cc() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return cc; } std::vector<uint64_t> randslr; virtual void set_randslr(const std::vector<uint64_t> new_randslr_) { if (initialized) { throw RuntimeError("Value 'randslr' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; randslr = new_randslr_; } virtual std::vector<uint64_t>& get_randslr() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return randslr; } std::vector<uint64_t> mm; virtual void set_mm(const std::vector<uint64_t> new_mm_) { if (initialized) { throw RuntimeError("Value 'mm' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; mm = new_mm_; } virtual std::vector<uint64_t>& get_mm() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return mm; } uint64_t rngblocks; virtual void set_rngblocks(const uint64_t new_rngblocks_) { if (initialized) { throw RuntimeError("Value 'rngblocks' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rngblocks = new_rngblocks_; } virtual uint64_t get_rngblocks() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rngblocks; } // --- methods --- }; // GenRngState class RngState; py::class_<RngState> define_pybinding_RngState(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_RNG_STATE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_constants.cpp
.cpp
12,187
129
/****************************************************************************** * * Copyright (C) 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 "api/api_common.h" #include "api/species.h" namespace MCell { namespace API { void define_pybinding_constants(py::module& m) { m.attr("STATE_UNSET") = py::str(STATE_UNSET); m.attr("STATE_UNSET_INT") = py::int_(STATE_UNSET_INT); m.attr("BOND_UNBOUND") = py::int_(BOND_UNBOUND); m.attr("BOND_BOUND") = py::int_(BOND_BOUND); m.attr("BOND_ANY") = py::int_(BOND_ANY); m.attr("PARTITION_EDGE_EXTRA_MARGIN_UM") = py::float_(PARTITION_EDGE_EXTRA_MARGIN_UM); m.attr("DEFAULT_COUNT_BUFFER_SIZE") = py::int_(DEFAULT_COUNT_BUFFER_SIZE); m.attr("ALL_MOLECULES") = py::str(ALL_MOLECULES); m.attr("ALL_VOLUME_MOLECULES") = py::str(ALL_VOLUME_MOLECULES); m.attr("ALL_SURFACE_MOLECULES") = py::str(ALL_SURFACE_MOLECULES); m.attr("DEFAULT_CHECKPOINTS_DIR") = py::str(DEFAULT_CHECKPOINTS_DIR); m.attr("DEFAULT_SEED_DIR_PREFIX") = py::str(DEFAULT_SEED_DIR_PREFIX); m.attr("DEFAULT_SEED_DIR_DIGITS") = py::int_(DEFAULT_SEED_DIR_DIGITS); m.attr("DEFAULT_ITERATION_DIR_PREFIX") = py::str(DEFAULT_ITERATION_DIR_PREFIX); m.attr("AllMolecules") = py::object(py::cast(AllMolecules)); m.attr("AllVolumeMolecules") = py::object(py::cast(AllVolumeMolecules)); m.attr("AllSurfaceMolecules") = py::object(py::cast(AllSurfaceMolecules)); m.attr("ID_INVALID") = py::int_(ID_INVALID); m.attr("NUMBER_OF_TRAINS_UNLIMITED") = py::int_(NUMBER_OF_TRAINS_UNLIMITED); m.attr("TIME_INFINITY") = py::float_(TIME_INFINITY); m.attr("INT_UNSET") = py::int_(INT_UNSET); m.attr("FLT_UNSET") = py::float_(FLT_UNSET); m.attr("RNG_SIZE") = py::int_(RNG_SIZE); } void define_pybinding_enums(py::module& m) { py::enum_<Orientation>(m, "Orientation", py::arithmetic(), "Orientation of a Complex.\n- DOWN\n\n- NONE\n\n- UP\n\n- NOT_SET\n\n- ANY\n\n- DEFAULT: Value DEFAULT means NONE for volume complexes and UP for surface complexes.\n") .value("DOWN", Orientation::DOWN) .value("NONE", Orientation::NONE) .value("UP", Orientation::UP) .value("NOT_SET", Orientation::NOT_SET) .value("ANY", Orientation::ANY) .value("DEFAULT", Orientation::DEFAULT) .export_values(); py::enum_<Notification>(m, "Notification", py::arithmetic(), "- NONE\n\n- BRIEF\n\n- FULL\n\n") .value("NONE", Notification::NONE) .value("BRIEF", Notification::BRIEF) .value("FULL", Notification::FULL) .export_values(); py::enum_<WarningLevel>(m, "WarningLevel", py::arithmetic(), "- IGNORE: Do something sensible and continue silently.\n- WARNING: Do something sensible but emit a warning message.\n- ERROR: Treat the warning as an error and stop.\n") .value("IGNORE", WarningLevel::IGNORE) .value("WARNING", WarningLevel::WARNING) .value("ERROR", WarningLevel::ERROR) .export_values(); py::enum_<VizMode>(m, "VizMode", py::arithmetic(), "- ASCII: Readable molecule visualization output.\n- CELLBLENDER_V1: Binary molecule visualization output used by MCell3, format v1.\nAllows only limited length of species name (256 chars) and \ndoes not contain molecule IDs. \n\n- CELLBLENDER: Binary molecule visualization output, format v2.\n") .value("ASCII", VizMode::ASCII) .value("CELLBLENDER_V1", VizMode::CELLBLENDER_V1) .value("CELLBLENDER", VizMode::CELLBLENDER) .export_values(); py::enum_<Shape>(m, "Shape", py::arithmetic(), "- UNSET\n\n- SPHERICAL\n\n- REGION_EXPR\n\n- LIST\n\n- COMPARTMENT\n\n") .value("UNSET", Shape::UNSET) .value("SPHERICAL", Shape::SPHERICAL) .value("REGION_EXPR", Shape::REGION_EXPR) .value("LIST", Shape::LIST) .value("COMPARTMENT", Shape::COMPARTMENT) .export_values(); py::enum_<SurfacePropertyType>(m, "SurfacePropertyType", py::arithmetic(), "- UNSET\n\n- REACTIVE: This surface class does not do anything by itself, but it can be used as a reactant in \nreaction rules. \n\n- REFLECTIVE: If used as a surface property for a volume molecule it is reflected by any surface with\nthis surface class. This is the default behavior for volume molecules.\nIf used for a surface molecule it is reflected by the border of the\nsurface with this surface class. \nSetting orientation in affected_complex_pattern allows selective reflection of volume \nmolecules from only the front or back of a surface or selective reflection of surface \nmolecules with only a certain orientation from the surface’s border. \nUsing m.ALL_MOLECULES as affected_complex_pattern has the effect that all \nvolume molecules are reflected by surfaces with this surface class and all surface molecules \nare reflected by the border of the surfaces with this surface class. \nUsing m.ALL_VOLUME_MOLECULES as affected_complex_pattern has the effect that all\nvolume molecules are reflected by surfaces with this surface class. \nUsing m.ALL_SURFACE_MOLECULES as affected_complex_pattern has the effect that all\nsurface molecules are reflected by the border of the surface with this surface class.\n\n- TRANSPARENT: If used as a surface property for a volume molecule it passes through all surfaces with\nthis surface class. \nIf used for a surface molecule it passes through the border of the surface with this surface \nclass. This is the default behavior for surface molecules.\nSetting orientation in affected_complex_pattern allows selective transparency of volume \nmolecules from only the front or back of a surface or selective transparency for surface \nmolecules with only a certain orientation from the surface’s border. \nTo make a surface with this surface class transparent to all volume molecules,\nuse m.ALL_VOLUME_MOLECULES for affected_complex_pattern. \nTo make a border of the surface with this surface class transparent to all surface molecules,\nuse m.ALL_SURFACE_MOLECULES for the affected_complex_pattern. \nUsing m.ALL_MOLECULES for affected_complex_pattern has the effect that surfaces with this surface class \nare transparent to all volume molecules and borders of the surfaces with this surface class are \ntransparent to all surface molecules. \n \n\n- ABSORPTIVE: If affected_complex_pattern refers to a volume molecule it is destroyed if it touches surfaces with this surface class. \nIf affected_complex_pattern refers to a surface molecule it is destroyed if it touches the border of the surface with \nthis surface class, i.e., it is allowed to release surface molecules on absorptive surfaces, they get destroyed only\nwhen they touch the border of this surface. \nTick marks on name allow destruction from only one side of the surface for volume molecules or selective destruction \nfor surface molecules on the surfaces’s border based on their orientation. \nTo make a surface with this surface class absorptive to all volume molecules, m.ALL_VOLUME_MOLECULES \ncan be used for affected_complex_pattern. \nTo make a border of the surface with this surface class absorptive to all surface molecules,\nm.ALL_SURFACE_MOLECULES can be used for name. \nUsing m.ALL_MOLECULES as affected_complex_pattern has the effect that surfaces with this surface\nclass are absorptive for all volume molecules and borders of the surfaces with this surface class \nare absorptive for all surface molecules.\n\n- CONCENTRATION_CLAMP: Clamps concentration at a surface by periodically releasing molecules that correspond\nto the wall being a transparent boundary to the area with given concentration, \nand by absorbing all molecules that hit this surface. \nThe molecules matching affected_complex_pattern are destroyed if they touch the surface (as if they\nhad passed through), and new molecules are created at the surface, as if molecules had passed through \nfrom the other side at a concentration value (units = M). \nOrientation marks may be used; in this case, the other side of the surface is reflective. \nNote that this command is only used to set the effective concentration of a volume molecule at a surface; \nit is not valid to specify a surface molecule. \n\n- FLUX_CLAMP: Clamps flux at a surface by periodically releasing molecules that correspond\nto the wall being a transparent boundary to the area with given concentration. \nThe clamped surface reflects these molecules. \n\n") .value("UNSET", SurfacePropertyType::UNSET) .value("REACTIVE", SurfacePropertyType::REACTIVE) .value("REFLECTIVE", SurfacePropertyType::REFLECTIVE) .value("TRANSPARENT", SurfacePropertyType::TRANSPARENT) .value("ABSORPTIVE", SurfacePropertyType::ABSORPTIVE) .value("CONCENTRATION_CLAMP", SurfacePropertyType::CONCENTRATION_CLAMP) .value("FLUX_CLAMP", SurfacePropertyType::FLUX_CLAMP) .export_values(); py::enum_<ExprNodeType>(m, "ExprNodeType", py::arithmetic(), "Used internally to represent expression trees.\n- UNSET\n\n- LEAF\n\n- ADD\n\n- SUB\n\n") .value("UNSET", ExprNodeType::UNSET) .value("LEAF", ExprNodeType::LEAF) .value("ADD", ExprNodeType::ADD) .value("SUB", ExprNodeType::SUB) .export_values(); py::enum_<RegionNodeType>(m, "RegionNodeType", py::arithmetic(), "Used internally to represent region trees.\n- UNSET\n\n- LEAF_GEOMETRY_OBJECT\n\n- LEAF_SURFACE_REGION\n\n- UNION\n\n- DIFFERENCE\n\n- INTERSECT\n\n") .value("UNSET", RegionNodeType::UNSET) .value("LEAF_GEOMETRY_OBJECT", RegionNodeType::LEAF_GEOMETRY_OBJECT) .value("LEAF_SURFACE_REGION", RegionNodeType::LEAF_SURFACE_REGION) .value("UNION", RegionNodeType::UNION) .value("DIFFERENCE", RegionNodeType::DIFFERENCE) .value("INTERSECT", RegionNodeType::INTERSECT) .export_values(); py::enum_<ReactionType>(m, "ReactionType", py::arithmetic(), "Used in reaction callbacks.\n- UNSET\n\n- UNIMOL_VOLUME\n\n- UNIMOL_SURFACE\n\n- VOLUME_VOLUME\n\n- VOLUME_SURFACE\n\n- SURFACE_SURFACE\n\n") .value("UNSET", ReactionType::UNSET) .value("UNIMOL_VOLUME", ReactionType::UNIMOL_VOLUME) .value("UNIMOL_SURFACE", ReactionType::UNIMOL_SURFACE) .value("VOLUME_VOLUME", ReactionType::VOLUME_VOLUME) .value("VOLUME_SURFACE", ReactionType::VOLUME_SURFACE) .value("SURFACE_SURFACE", ReactionType::SURFACE_SURFACE) .export_values(); py::enum_<MoleculeType>(m, "MoleculeType", py::arithmetic(), "Used in molecule introspection and internally in checkpointing.\n- UNSET\n\n- VOLUME\n\n- SURFACE\n\n") .value("UNSET", MoleculeType::UNSET) .value("VOLUME", MoleculeType::VOLUME) .value("SURFACE", MoleculeType::SURFACE) .export_values(); py::enum_<BNGSimulationMethod>(m, "BNGSimulationMethod", py::arithmetic(), "Specifies simulation method in exported BNGL, used in Model.export_to_bngl.\n- NONE\n\n- ODE\n\n- SSA\n\n- PLA\n\n- NF\n\n") .value("NONE", BNGSimulationMethod::NONE) .value("ODE", BNGSimulationMethod::ODE) .value("SSA", BNGSimulationMethod::SSA) .value("PLA", BNGSimulationMethod::PLA) .value("NF", BNGSimulationMethod::NF) .export_values(); py::enum_<CountOutputFormat>(m, "CountOutputFormat", py::arithmetic(), "- UNSET: Invalid value.\n- AUTOMATIC_FROM_EXTENSION: Output format is determined fom extension - .dat selects DAT file format \nand .gdat selects GDAT file format. \n\n- DAT: A two-column file with columns time and observable value is created. \nEach count must have its own unique file name.\n\n- GDAT: A multi-column file with time and observable values is created.\nThe first line of the file is a header that starts with a comment \ncharacter followed by time and then by the observable names. \nThe order of observables is given by the order in which they were added \nto the model.\nCan specify the same output file name for multiple observables. \n\n \n") .value("UNSET", CountOutputFormat::UNSET) .value("AUTOMATIC_FROM_EXTENSION", CountOutputFormat::AUTOMATIC_FROM_EXTENSION) .value("DAT", CountOutputFormat::DAT) .value("GDAT", CountOutputFormat::GDAT) .export_values(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_molecule.cpp
.cpp
6,636
159
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_molecule.h" #include "api/molecule.h" #include "api/geometry_object.h" namespace MCell { namespace API { void GenMolecule::check_semantics() const { } void GenMolecule::set_initialized() { if (is_set(geometry_object)) { geometry_object->set_initialized(); } initialized = true; } void GenMolecule::set_all_attributes_as_default_or_unset() { class_name = "Molecule"; id = ID_INVALID; type = MoleculeType::UNSET; species_id = ID_INVALID; pos3d = std::vector<double>(); orientation = Orientation::NOT_SET; pos2d = std::vector<double>(); geometry_object = nullptr; wall_index = -1; } std::shared_ptr<Molecule> GenMolecule::copy_molecule() const { std::shared_ptr<Molecule> res = std::make_shared<Molecule>(DefaultCtorArgType()); res->class_name = class_name; res->id = id; res->type = type; res->species_id = species_id; res->pos3d = pos3d; res->orientation = orientation; res->pos2d = pos2d; res->geometry_object = geometry_object; res->wall_index = wall_index; return res; } std::shared_ptr<Molecule> GenMolecule::deepcopy_molecule(py::dict) const { std::shared_ptr<Molecule> res = std::make_shared<Molecule>(DefaultCtorArgType()); res->class_name = class_name; res->id = id; res->type = type; res->species_id = species_id; res->pos3d = pos3d; res->orientation = orientation; res->pos2d = pos2d; res->geometry_object = is_set(geometry_object) ? geometry_object->deepcopy_geometry_object() : nullptr; res->wall_index = wall_index; return res; } bool GenMolecule::__eq__(const Molecule& other) const { return id == other.id && type == other.type && species_id == other.species_id && pos3d == other.pos3d && orientation == other.orientation && pos2d == other.pos2d && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index; } bool GenMolecule::eq_nonarray_attributes(const Molecule& other, const bool ignore_name) const { return id == other.id && type == other.type && species_id == other.species_id && true /*pos3d*/ && orientation == other.orientation && true /*pos2d*/ && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index; } std::string GenMolecule::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "id=" << id << ", " << "type=" << type << ", " << "species_id=" << species_id << ", " << "pos3d=" << vec_nonptr_to_str(pos3d, all_details, ind + " ") << ", " << "orientation=" << orientation << ", " << "pos2d=" << vec_nonptr_to_str(pos2d, all_details, ind + " ") << ", " << "\n" << ind + " " << "geometry_object=" << "(" << ((geometry_object != nullptr) ? geometry_object->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall_index=" << wall_index; return ss.str(); } py::class_<Molecule> define_pybinding_Molecule(py::module& m) { return py::class_<Molecule, std::shared_ptr<Molecule>>(m, "Molecule", "Representation of a molecule obtained from Model \nduring simulation obtained through Model.get_molecule.\nChanges through changing attributes of this object are not allowed except \nfor complete removal of this molecule. \n") .def( py::init< >() ) .def("check_semantics", &Molecule::check_semantics) .def("__copy__", &Molecule::copy_molecule) .def("__deepcopy__", &Molecule::deepcopy_molecule, py::arg("memo")) .def("__str__", &Molecule::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Molecule::__eq__, py::arg("other")) .def("remove", &Molecule::remove, "Removes this molecule from simulation. Any subsequent modifications\nof this molecule won't have any effect.\n") .def("dump", &Molecule::dump) .def_property("id", &Molecule::get_id, &Molecule::set_id, "Unique id of this molecule. MCell assigns this unique id to each created \nmolecule. All reactions change ID of molecules even in reactions such as \nA@CP -> A@EC.\n") .def_property("type", &Molecule::get_type, &Molecule::set_type, "Type of this molecule, either volume or surface. \n") .def_property("species_id", &Molecule::get_species_id, &Molecule::set_species_id, "Species id of this molecule.\nThe species_id value is only temporary. Species ids are created and removed as needed\nautomatically and if this species is removed, this particular species_id value \nwon't be valid. This can happen when a following iteration is simulated.\n") .def_property("pos3d", &Molecule::get_pos3d, &Molecule::set_pos3d, py::return_value_policy::reference, "Contains position of a molecule in 3D space. \n") .def_property("orientation", &Molecule::get_orientation, &Molecule::set_orientation, "Contains orientation for surface molecule. Volume molecules \nhave always orientation set to Orientation.NONE.\n") .def_property("pos2d", &Molecule::get_pos2d, &Molecule::set_pos2d, py::return_value_policy::reference, "Set only for surface molecules. Position on a wall in UV coordinates \nrelative to the triangle of the wall.\n \n") .def_property("geometry_object", &Molecule::get_geometry_object, &Molecule::set_geometry_object, "Set only for surface molecules.\nIs set to a reference to the geometry object on whose surface is the molecule located.\n") .def_property("wall_index", &Molecule::get_wall_index, &Molecule::set_wall_index, "Set only for surface molecules.\nIndex of wall belonging to the geometry_object where is the \nmolecule located. \n \n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_count_term.h
.h
7,843
202
/****************************************************************************** * * Copyright (C) 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 API_GEN_COUNT_TERM_H #define API_GEN_COUNT_TERM_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Complex; class CountTerm; class ReactionRule; class Region; class PythonExportContext; #define COUNT_TERM_CTOR() \ CountTerm( \ std::shared_ptr<Complex> species_pattern_ = nullptr, \ std::shared_ptr<Complex> molecules_pattern_ = nullptr, \ std::shared_ptr<ReactionRule> reaction_rule_ = nullptr, \ std::shared_ptr<Region> region_ = nullptr, \ const ExprNodeType node_type_ = ExprNodeType::LEAF, \ std::shared_ptr<CountTerm> left_node_ = nullptr, \ std::shared_ptr<CountTerm> right_node_ = nullptr, \ const uint64_t initial_reactions_count_ = 0 \ ) { \ class_name = "CountTerm"; \ species_pattern = species_pattern_; \ molecules_pattern = molecules_pattern_; \ reaction_rule = reaction_rule_; \ region = region_; \ node_type = node_type_; \ left_node = left_node_; \ right_node = right_node_; \ initial_reactions_count = initial_reactions_count_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ CountTerm(DefaultCtorArgType) : \ GenCountTerm(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenCountTerm: public BaseDataClass { public: GenCountTerm() { } GenCountTerm(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<CountTerm> copy_count_term() const; std::shared_ptr<CountTerm> deepcopy_count_term(py::dict = py::dict()) const; virtual bool __eq__(const CountTerm& other) const; virtual bool eq_nonarray_attributes(const CountTerm& other, const bool ignore_name = false) const; bool operator == (const CountTerm& other) const { return __eq__(other);} bool operator != (const CountTerm& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- std::shared_ptr<Complex> species_pattern; virtual void set_species_pattern(std::shared_ptr<Complex> new_species_pattern_) { if (initialized) { throw RuntimeError("Value 'species_pattern' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; species_pattern = new_species_pattern_; } virtual std::shared_ptr<Complex> get_species_pattern() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return species_pattern; } std::shared_ptr<Complex> molecules_pattern; virtual void set_molecules_pattern(std::shared_ptr<Complex> new_molecules_pattern_) { if (initialized) { throw RuntimeError("Value 'molecules_pattern' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; molecules_pattern = new_molecules_pattern_; } virtual std::shared_ptr<Complex> get_molecules_pattern() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return molecules_pattern; } std::shared_ptr<ReactionRule> reaction_rule; virtual void set_reaction_rule(std::shared_ptr<ReactionRule> new_reaction_rule_) { if (initialized) { throw RuntimeError("Value 'reaction_rule' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; reaction_rule = new_reaction_rule_; } virtual std::shared_ptr<ReactionRule> get_reaction_rule() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return reaction_rule; } std::shared_ptr<Region> region; virtual void set_region(std::shared_ptr<Region> new_region_) { if (initialized) { throw RuntimeError("Value 'region' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; region = new_region_; } virtual std::shared_ptr<Region> get_region() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return region; } ExprNodeType node_type; virtual void set_node_type(const ExprNodeType new_node_type_) { if (initialized) { throw RuntimeError("Value 'node_type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; node_type = new_node_type_; } virtual ExprNodeType get_node_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return node_type; } std::shared_ptr<CountTerm> left_node; virtual void set_left_node(std::shared_ptr<CountTerm> new_left_node_) { if (initialized) { throw RuntimeError("Value 'left_node' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; left_node = new_left_node_; } virtual std::shared_ptr<CountTerm> get_left_node() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return left_node; } std::shared_ptr<CountTerm> right_node; virtual void set_right_node(std::shared_ptr<CountTerm> new_right_node_) { if (initialized) { throw RuntimeError("Value 'right_node' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; right_node = new_right_node_; } virtual std::shared_ptr<CountTerm> get_right_node() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return right_node; } uint64_t initial_reactions_count; virtual void set_initial_reactions_count(const uint64_t new_initial_reactions_count_) { if (initialized) { throw RuntimeError("Value 'initial_reactions_count' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_reactions_count = new_initial_reactions_count_; } virtual uint64_t get_initial_reactions_count() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_reactions_count; } // --- methods --- virtual std::shared_ptr<CountTerm> __add__(std::shared_ptr<CountTerm> op2) = 0; virtual std::shared_ptr<CountTerm> __sub__(std::shared_ptr<CountTerm> op2) = 0; }; // GenCountTerm class CountTerm; py::class_<CountTerm> define_pybinding_CountTerm(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COUNT_TERM_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_bngl_utils.h
.h
888
33
/****************************************************************************** * * Copyright (C) 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 API_GEN_BNGL_UTILS_H #define API_GEN_BNGL_UTILS_H #include "api/api_common.h" namespace MCell { namespace API { class PythonExportContext; namespace bngl_utils { std::map<std::string, double> load_bngl_parameters(const std::string& file_name, const std::map<std::string, double>& parameter_overrides = std::map<std::string, double>()); } // namespace bngl_utils void define_pybinding_bngl_utils(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_BNGL_UTILS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_complex.cpp
.cpp
8,882
183
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_complex.h" #include "api/complex.h" #include "api/elementary_molecule.h" #include "api/species.h" namespace MCell { namespace API { void GenComplex::check_semantics() const { } void GenComplex::set_initialized() { vec_set_initialized(elementary_molecules); initialized = true; } void GenComplex::set_all_attributes_as_default_or_unset() { class_name = "Complex"; name = STR_UNSET; elementary_molecules = std::vector<std::shared_ptr<ElementaryMolecule>>(); orientation = Orientation::DEFAULT; compartment_name = STR_UNSET; } std::shared_ptr<Complex> GenComplex::copy_complex() const { std::shared_ptr<Complex> res = std::make_shared<Complex>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->elementary_molecules = elementary_molecules; res->orientation = orientation; res->compartment_name = compartment_name; return res; } std::shared_ptr<Complex> GenComplex::deepcopy_complex(py::dict) const { std::shared_ptr<Complex> res = std::make_shared<Complex>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; for (const auto& item: elementary_molecules) { res->elementary_molecules.push_back((is_set(item)) ? item->deepcopy_elementary_molecule() : nullptr); } res->orientation = orientation; res->compartment_name = compartment_name; return res; } bool GenComplex::__eq__(const Complex& other) const { return name == other.name && vec_ptr_eq(elementary_molecules, other.elementary_molecules) && orientation == other.orientation && compartment_name == other.compartment_name; } bool GenComplex::eq_nonarray_attributes(const Complex& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*elementary_molecules*/ && orientation == other.orientation && compartment_name == other.compartment_name; } std::string GenComplex::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "\n" << ind + " " << "elementary_molecules=" << vec_ptr_to_str(elementary_molecules, all_details, ind + " ") << ", " << "\n" << ind + " " << "orientation=" << orientation << ", " << "compartment_name=" << compartment_name; return ss.str(); } py::class_<Complex> define_pybinding_Complex(py::module& m) { return py::class_<Complex, std::shared_ptr<Complex>>(m, "Complex", "This class represents a complex molecule composed of molecule instances.\nIt is either defined using a BNGL string or using a list of elementary molecule instances.\nOn top of that, orientation may be defined.\nThis class is most often by calling its constructor as m.Complex(bngl_string) in cases where a \nfully qualified instance (such as for molecule releases) or a pattern (in observable counts) is needed. \nComparison operator __eq__ first converts complexes to their canonical representation and \nthen does comparison so for instance m.Complex('A(b!1).B(a!1)') == m.Complex('B(a!2).A(b!2)').\n") .def( py::init< const std::string&, const std::vector<std::shared_ptr<ElementaryMolecule>>, const Orientation, const std::string& >(), py::arg("name") = STR_UNSET, py::arg("elementary_molecules") = std::vector<std::shared_ptr<ElementaryMolecule>>(), py::arg("orientation") = Orientation::DEFAULT, py::arg("compartment_name") = STR_UNSET ) .def("check_semantics", &Complex::check_semantics) .def("__copy__", &Complex::copy_complex) .def("__deepcopy__", &Complex::deepcopy_complex, py::arg("memo")) .def("__str__", &Complex::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Complex::__eq__, py::arg("other")) .def("to_bngl_str", &Complex::to_bngl_str, "Creates a string that corresponds to its BNGL representation including compartments.") .def("as_species", &Complex::as_species, "Returns a Species object based on this Complex. All species-specific \nattributes are set to their default values and 'name' is set to value returned by \n'to_bngl_str()'.\n") .def("dump", &Complex::dump) .def_property("name", &Complex::get_name, &Complex::set_name, "When set, this complex instance is initialized from a BNGL string passed as this argument, \nthe string is parsed and elementary_molecules and compartment are initialized.\nOnly one of name or elementary_molecules can be set. \n") .def_property("elementary_molecules", &Complex::get_elementary_molecules, &Complex::set_elementary_molecules, py::return_value_policy::reference, "Individual molecule instances contained in the complex.\nOnly one of name or elementary_molecules can be set.\n") .def_property("orientation", &Complex::get_orientation, &Complex::set_orientation, "Specifies orientation of a molecule. \nWhen Orientation.DEFAULT if kept then during model initialization is\n'orientation' set to Orientation.NONE for volume complexes and to \nOrientation.UP for surface complexes.\nIgnored by derived class Species.\n") .def_property("compartment_name", &Complex::get_compartment_name, &Complex::set_compartment_name, "Specifies compartment name of this Complex.\nOnly one of 'orientation' and 'compartment_name' can be set. \nCorresponds to BNGL specification of a compartment for the whole complex '@COMP:'.\nIf a 2D/surface compartment is specified, the complex must be a surface complex and \norientation is set to Orientation.UP.\nIf a 3D/volume compartment is specified, the complex must be a volume complex and\norientation is set to Orientation.NONE.\nSets compartment to all elementary molecules whose compartment is unset. Does not override \nspecific compartments of elementary molecules that were already set.\nIf this is a volume complex (all elementary molecules have their diffusion_constant_3d set), \nall compartments of elementary molecules must be the same volume compartment.\nIf this is a surface complex (at least one elementary molecule has its their diffusion_constant_2d \nset), all compartments of surface elementary molecules must be the same, and\nall compartments of volume elementary molecules must be from the two neighboring \nvolume compartments.\n") ; } std::string GenComplex::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("complex") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("complex"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Complex(" << nl; if (name != STR_UNSET) { ss << ind << "name = " << "'" << name << "'" << "," << nl; } if (elementary_molecules != std::vector<std::shared_ptr<ElementaryMolecule>>() && !skip_vectors_export()) { ss << ind << "elementary_molecules = " << export_vec_elementary_molecules(out, ctx, exported_name) << "," << nl; } if (orientation != Orientation::DEFAULT) { ss << ind << "orientation = " << orientation << "," << nl; } if (compartment_name != STR_UNSET) { ss << ind << "compartment_name = " << "'" << compartment_name << "'" << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenComplex::export_vec_elementary_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < elementary_molecules.size(); i++) { const auto& item = elementary_molecules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_geometry_object.h
.h
9,590
220
/****************************************************************************** * * Copyright (C) 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 API_GEN_GEOMETRY_OBJECT_H #define API_GEN_GEOMETRY_OBJECT_H #include "api/api_common.h" #include "api/region.h" namespace MCell { namespace API { class GeometryObject; class Color; class InitialSurfaceRelease; class Region; class SurfaceClass; class SurfaceRegion; class PythonExportContext; #define GEOMETRY_OBJECT_CTOR() \ GeometryObject( \ const std::string& name_, \ const std::vector<std::vector<double>> vertex_list_, \ const std::vector<std::vector<int>> wall_list_, \ const bool is_bngl_compartment_ = false, \ const std::string& surface_compartment_name_ = STR_UNSET, \ const std::vector<std::shared_ptr<SurfaceRegion>> surface_regions_ = std::vector<std::shared_ptr<SurfaceRegion>>(), \ std::shared_ptr<SurfaceClass> surface_class_ = nullptr, \ const std::vector<std::shared_ptr<InitialSurfaceRelease>> initial_surface_releases_ = std::vector<std::shared_ptr<InitialSurfaceRelease>>(), \ std::shared_ptr<Color> initial_color_ = nullptr, \ const RegionNodeType node_type_ = RegionNodeType::UNSET, \ std::shared_ptr<Region> left_node_ = nullptr, \ std::shared_ptr<Region> right_node_ = nullptr \ ) : GenGeometryObject(node_type_,left_node_,right_node_) { \ class_name = "GeometryObject"; \ name = name_; \ vertex_list = vertex_list_; \ wall_list = wall_list_; \ is_bngl_compartment = is_bngl_compartment_; \ surface_compartment_name = surface_compartment_name_; \ surface_regions = surface_regions_; \ surface_class = surface_class_; \ initial_surface_releases = initial_surface_releases_; \ initial_color = initial_color_; \ node_type = node_type_; \ left_node = left_node_; \ right_node = right_node_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ GeometryObject(DefaultCtorArgType) : \ GenGeometryObject(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenGeometryObject: public Region { public: GenGeometryObject( const RegionNodeType node_type_ = RegionNodeType::UNSET, std::shared_ptr<Region> left_node_ = nullptr, std::shared_ptr<Region> right_node_ = nullptr ) : Region(node_type_,left_node_,right_node_) { } GenGeometryObject(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<GeometryObject> copy_geometry_object() const; std::shared_ptr<GeometryObject> deepcopy_geometry_object(py::dict = py::dict()) const; virtual bool __eq__(const GeometryObject& other) const; virtual bool eq_nonarray_attributes(const GeometryObject& other, const bool ignore_name = false) const; bool operator == (const GeometryObject& other) const { return __eq__(other);} bool operator != (const GeometryObject& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_vertex_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_wall_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_surface_regions(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_initial_surface_releases(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::vector<double>> vertex_list; virtual void set_vertex_list(const std::vector<std::vector<double>> new_vertex_list_) { if (initialized) { throw RuntimeError("Value 'vertex_list' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; vertex_list = new_vertex_list_; } virtual std::vector<std::vector<double>>& get_vertex_list() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return vertex_list; } std::vector<std::vector<int>> wall_list; virtual void set_wall_list(const std::vector<std::vector<int>> new_wall_list_) { if (initialized) { throw RuntimeError("Value 'wall_list' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_list = new_wall_list_; } virtual std::vector<std::vector<int>>& get_wall_list() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_list; } bool is_bngl_compartment; virtual void set_is_bngl_compartment(const bool new_is_bngl_compartment_) { if (initialized) { throw RuntimeError("Value 'is_bngl_compartment' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; is_bngl_compartment = new_is_bngl_compartment_; } virtual bool get_is_bngl_compartment() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return is_bngl_compartment; } std::string surface_compartment_name; virtual void set_surface_compartment_name(const std::string& new_surface_compartment_name_) { if (initialized) { throw RuntimeError("Value 'surface_compartment_name' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; surface_compartment_name = new_surface_compartment_name_; } virtual const std::string& get_surface_compartment_name() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return surface_compartment_name; } std::vector<std::shared_ptr<SurfaceRegion>> surface_regions; virtual void set_surface_regions(const std::vector<std::shared_ptr<SurfaceRegion>> new_surface_regions_) { if (initialized) { throw RuntimeError("Value 'surface_regions' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; surface_regions = new_surface_regions_; } virtual std::vector<std::shared_ptr<SurfaceRegion>>& get_surface_regions() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return surface_regions; } std::shared_ptr<SurfaceClass> surface_class; virtual void set_surface_class(std::shared_ptr<SurfaceClass> new_surface_class_) { if (initialized) { throw RuntimeError("Value 'surface_class' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; surface_class = new_surface_class_; } virtual std::shared_ptr<SurfaceClass> get_surface_class() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return surface_class; } std::vector<std::shared_ptr<InitialSurfaceRelease>> initial_surface_releases; virtual void set_initial_surface_releases(const std::vector<std::shared_ptr<InitialSurfaceRelease>> new_initial_surface_releases_) { if (initialized) { throw RuntimeError("Value 'initial_surface_releases' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_surface_releases = new_initial_surface_releases_; } virtual std::vector<std::shared_ptr<InitialSurfaceRelease>>& get_initial_surface_releases() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_surface_releases; } std::shared_ptr<Color> initial_color; virtual void set_initial_color(std::shared_ptr<Color> new_initial_color_) { if (initialized) { throw RuntimeError("Value 'initial_color' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; initial_color = new_initial_color_; } virtual std::shared_ptr<Color> get_initial_color() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return initial_color; } // --- methods --- virtual void translate(const std::vector<double> move) = 0; }; // GenGeometryObject class GeometryObject; py::class_<GeometryObject> define_pybinding_GeometryObject(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_GEOMETRY_OBJECT_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_config.cpp
.cpp
24,863
425
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_config.h" #include "api/api_config.h" #include "api/rng_state.h" namespace MCell { namespace API { void GenConfig::check_semantics() const { } void GenConfig::set_initialized() { if (is_set(initial_rng_state)) { initial_rng_state->set_initialized(); } initialized = true; } void GenConfig::set_all_attributes_as_default_or_unset() { class_name = "Config"; seed = 1; time_step = 1e-6; use_bng_units = false; surface_grid_density = 10000; interaction_radius = FLT_UNSET; intermembrane_interaction_radius = FLT_UNSET; vacancy_search_distance = 10; center_molecules_on_grid = false; partition_dimension = 10; initial_partition_origin = std::vector<double>(); subpartition_dimension = 0.5; total_iterations = 1000000; check_overlapped_walls = true; reaction_class_cleanup_periodicity = 500; species_cleanup_periodicity = 10000; molecules_order_random_shuffle_periodicity = 10000; sort_molecules = false; memory_limit_gb = -1; initial_iteration = 0; initial_time = 0; initial_rng_state = nullptr; append_to_count_output_data = false; continue_after_sigalrm = false; } std::shared_ptr<Config> GenConfig::copy_config() const { std::shared_ptr<Config> res = std::make_shared<Config>(DefaultCtorArgType()); res->class_name = class_name; res->seed = seed; res->time_step = time_step; res->use_bng_units = use_bng_units; res->surface_grid_density = surface_grid_density; res->interaction_radius = interaction_radius; res->intermembrane_interaction_radius = intermembrane_interaction_radius; res->vacancy_search_distance = vacancy_search_distance; res->center_molecules_on_grid = center_molecules_on_grid; res->partition_dimension = partition_dimension; res->initial_partition_origin = initial_partition_origin; res->subpartition_dimension = subpartition_dimension; res->total_iterations = total_iterations; res->check_overlapped_walls = check_overlapped_walls; res->reaction_class_cleanup_periodicity = reaction_class_cleanup_periodicity; res->species_cleanup_periodicity = species_cleanup_periodicity; res->molecules_order_random_shuffle_periodicity = molecules_order_random_shuffle_periodicity; res->sort_molecules = sort_molecules; res->memory_limit_gb = memory_limit_gb; res->initial_iteration = initial_iteration; res->initial_time = initial_time; res->initial_rng_state = initial_rng_state; res->append_to_count_output_data = append_to_count_output_data; res->continue_after_sigalrm = continue_after_sigalrm; return res; } std::shared_ptr<Config> GenConfig::deepcopy_config(py::dict) const { std::shared_ptr<Config> res = std::make_shared<Config>(DefaultCtorArgType()); res->class_name = class_name; res->seed = seed; res->time_step = time_step; res->use_bng_units = use_bng_units; res->surface_grid_density = surface_grid_density; res->interaction_radius = interaction_radius; res->intermembrane_interaction_radius = intermembrane_interaction_radius; res->vacancy_search_distance = vacancy_search_distance; res->center_molecules_on_grid = center_molecules_on_grid; res->partition_dimension = partition_dimension; res->initial_partition_origin = initial_partition_origin; res->subpartition_dimension = subpartition_dimension; res->total_iterations = total_iterations; res->check_overlapped_walls = check_overlapped_walls; res->reaction_class_cleanup_periodicity = reaction_class_cleanup_periodicity; res->species_cleanup_periodicity = species_cleanup_periodicity; res->molecules_order_random_shuffle_periodicity = molecules_order_random_shuffle_periodicity; res->sort_molecules = sort_molecules; res->memory_limit_gb = memory_limit_gb; res->initial_iteration = initial_iteration; res->initial_time = initial_time; res->initial_rng_state = is_set(initial_rng_state) ? initial_rng_state->deepcopy_rng_state() : nullptr; res->append_to_count_output_data = append_to_count_output_data; res->continue_after_sigalrm = continue_after_sigalrm; return res; } bool GenConfig::__eq__(const Config& other) const { return seed == other.seed && time_step == other.time_step && use_bng_units == other.use_bng_units && surface_grid_density == other.surface_grid_density && interaction_radius == other.interaction_radius && intermembrane_interaction_radius == other.intermembrane_interaction_radius && vacancy_search_distance == other.vacancy_search_distance && center_molecules_on_grid == other.center_molecules_on_grid && partition_dimension == other.partition_dimension && initial_partition_origin == other.initial_partition_origin && subpartition_dimension == other.subpartition_dimension && total_iterations == other.total_iterations && check_overlapped_walls == other.check_overlapped_walls && reaction_class_cleanup_periodicity == other.reaction_class_cleanup_periodicity && species_cleanup_periodicity == other.species_cleanup_periodicity && molecules_order_random_shuffle_periodicity == other.molecules_order_random_shuffle_periodicity && sort_molecules == other.sort_molecules && memory_limit_gb == other.memory_limit_gb && initial_iteration == other.initial_iteration && initial_time == other.initial_time && ( (is_set(initial_rng_state)) ? (is_set(other.initial_rng_state) ? (initial_rng_state->__eq__(*other.initial_rng_state)) : false ) : (is_set(other.initial_rng_state) ? false : true ) ) && append_to_count_output_data == other.append_to_count_output_data && continue_after_sigalrm == other.continue_after_sigalrm; } bool GenConfig::eq_nonarray_attributes(const Config& other, const bool ignore_name) const { return seed == other.seed && time_step == other.time_step && use_bng_units == other.use_bng_units && surface_grid_density == other.surface_grid_density && interaction_radius == other.interaction_radius && intermembrane_interaction_radius == other.intermembrane_interaction_radius && vacancy_search_distance == other.vacancy_search_distance && center_molecules_on_grid == other.center_molecules_on_grid && partition_dimension == other.partition_dimension && true /*initial_partition_origin*/ && subpartition_dimension == other.subpartition_dimension && total_iterations == other.total_iterations && check_overlapped_walls == other.check_overlapped_walls && reaction_class_cleanup_periodicity == other.reaction_class_cleanup_periodicity && species_cleanup_periodicity == other.species_cleanup_periodicity && molecules_order_random_shuffle_periodicity == other.molecules_order_random_shuffle_periodicity && sort_molecules == other.sort_molecules && memory_limit_gb == other.memory_limit_gb && initial_iteration == other.initial_iteration && initial_time == other.initial_time && ( (is_set(initial_rng_state)) ? (is_set(other.initial_rng_state) ? (initial_rng_state->__eq__(*other.initial_rng_state)) : false ) : (is_set(other.initial_rng_state) ? false : true ) ) && append_to_count_output_data == other.append_to_count_output_data && continue_after_sigalrm == other.continue_after_sigalrm; } std::string GenConfig::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "seed=" << seed << ", " << "time_step=" << time_step << ", " << "use_bng_units=" << use_bng_units << ", " << "surface_grid_density=" << surface_grid_density << ", " << "interaction_radius=" << interaction_radius << ", " << "intermembrane_interaction_radius=" << intermembrane_interaction_radius << ", " << "vacancy_search_distance=" << vacancy_search_distance << ", " << "center_molecules_on_grid=" << center_molecules_on_grid << ", " << "partition_dimension=" << partition_dimension << ", " << "initial_partition_origin=" << vec_nonptr_to_str(initial_partition_origin, all_details, ind + " ") << ", " << "subpartition_dimension=" << subpartition_dimension << ", " << "total_iterations=" << total_iterations << ", " << "check_overlapped_walls=" << check_overlapped_walls << ", " << "reaction_class_cleanup_periodicity=" << reaction_class_cleanup_periodicity << ", " << "species_cleanup_periodicity=" << species_cleanup_periodicity << ", " << "molecules_order_random_shuffle_periodicity=" << molecules_order_random_shuffle_periodicity << ", " << "sort_molecules=" << sort_molecules << ", " << "memory_limit_gb=" << memory_limit_gb << ", " << "initial_iteration=" << initial_iteration << ", " << "initial_time=" << initial_time << ", " << "\n" << ind + " " << "initial_rng_state=" << "(" << ((initial_rng_state != nullptr) ? initial_rng_state->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "append_to_count_output_data=" << append_to_count_output_data << ", " << "continue_after_sigalrm=" << continue_after_sigalrm; return ss.str(); } py::class_<Config> define_pybinding_Config(py::module& m) { return py::class_<Config, std::shared_ptr<Config>>(m, "Config", "Class holds simulation configuration.") .def( py::init< const int, const double, const bool, const double, const double, const double, const double, const bool, const double, const std::vector<double>, const double, const double, const bool, const int, const int, const int, const bool, const int, const uint64_t, const double, std::shared_ptr<RngState>, const bool, const bool >(), py::arg("seed") = 1, py::arg("time_step") = 1e-6, py::arg("use_bng_units") = false, py::arg("surface_grid_density") = 10000, py::arg("interaction_radius") = FLT_UNSET, py::arg("intermembrane_interaction_radius") = FLT_UNSET, py::arg("vacancy_search_distance") = 10, py::arg("center_molecules_on_grid") = false, py::arg("partition_dimension") = 10, py::arg("initial_partition_origin") = std::vector<double>(), py::arg("subpartition_dimension") = 0.5, py::arg("total_iterations") = 1000000, py::arg("check_overlapped_walls") = true, py::arg("reaction_class_cleanup_periodicity") = 500, py::arg("species_cleanup_periodicity") = 10000, py::arg("molecules_order_random_shuffle_periodicity") = 10000, py::arg("sort_molecules") = false, py::arg("memory_limit_gb") = -1, py::arg("initial_iteration") = 0, py::arg("initial_time") = 0, py::arg("initial_rng_state") = nullptr, py::arg("append_to_count_output_data") = false, py::arg("continue_after_sigalrm") = false ) .def("check_semantics", &Config::check_semantics) .def("__copy__", &Config::copy_config) .def("__deepcopy__", &Config::deepcopy_config, py::arg("memo")) .def("__str__", &Config::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Config::__eq__, py::arg("other")) .def("dump", &Config::dump) .def_property("seed", &Config::get_seed, &Config::set_seed, "Random generator seed value.") .def_property("time_step", &Config::get_time_step, &Config::set_time_step, "Set the simulation time step to time_step seconds. 1e-6 (1us) is a common value. \nOne can set the time steps taken by individual molecules, but this \ntime step is still used as a default.\n") .def_property("use_bng_units", &Config::get_use_bng_units, &Config::set_use_bng_units, "When False (default), MCell uses traditional MCell units for bimolecular reaction rates are:\n * [M^-1*s^-1] for bimolecular reactions between either two volume molecules, a volume molecule \n and a surface (molecule), \n * [um^2*N^-1*s^-1] bimolecular reactions between two surface molecules on the same surface.\nWhen True, BioNetGen units for bimolecular reaction rates are:\n * [um^3*N^-1*s^-1] for any bimolecular reactions. Surface-surface reaction rate conversion assumes 10nm membrane thickness\nBioNetGen units are compatible with BioNetGen's ODE, SSA, and PLA solvers given that seed species \nis copy number (N), these units are not compatible with NFSim. \nNo other units are affected by this setting.\n") .def_property("surface_grid_density", &Config::get_surface_grid_density, &Config::set_surface_grid_density, "Tile all surfaces so that they can hold molecules at N different positions per square micron.") .def_property("interaction_radius", &Config::get_interaction_radius, &Config::set_interaction_radius, "Diffusing volume molecules will interact with each other when\nthey get within N microns of each other. The default is\n1/sqrt(PI * Sigma_s) where Sigma_s is the surface grid density \n(default or user-specified).\n") .def_property("intermembrane_interaction_radius", &Config::get_intermembrane_interaction_radius, &Config::set_intermembrane_interaction_radius, "Diffusing surface molecules will interact with surface molecules on other\nwalls when they get within N microns of each other. The default is\n1/sqrt(PI * Sigma_s) where Sigma_s is the surface grid density \n(default or user-specified). \nWhen unset, the default value is computed as: \n1.0 / sqrt_f(MY_PI * surface_grid_density).\n") .def_property("vacancy_search_distance", &Config::get_vacancy_search_distance, &Config::set_vacancy_search_distance, "Rather internal, there is usually no need to change this value.\nUsed in dynamic geometry (see Model.apply_vertex_moves()). \nWhen a wall moves or its dimensions change, this is the maximum search distance \nuse when looking onto which tiles place the molecules on this wall. \nIf no empty tile is found within this distance, simulation fails. \n \n") .def_property("center_molecules_on_grid", &Config::get_center_molecules_on_grid, &Config::set_center_molecules_on_grid, "If set to True, then all molecules on a surface will be\nlocated exactly at the center of their grid element. If False, the\nmolecules will be randomly located when placed, and reactions\nwill take place at the location of the target (or the site of impact\nin the case of 3D molecule/surface reactions). \n") .def_property("partition_dimension", &Config::get_partition_dimension, &Config::set_partition_dimension, "All the simulated 3d space is placed in a partition. The partition is a cube and \nthis partition_dimension specifies the length of its edge in um.\n") .def_property("initial_partition_origin", &Config::get_initial_partition_origin, &Config::set_initial_partition_origin, py::return_value_policy::reference, "Optional placement of the initial partition in um, specifies the left, lower front \npoint. If not set, value -partition_dimension/2 is used for each of the dimensions \nplacing the center of the partition to (0, 0, 0). \n") .def_property("subpartition_dimension", &Config::get_subpartition_dimension, &Config::set_subpartition_dimension, "Subpartition are spatial division of 3D space used to accelerate collision checking.\nIn general, partitions should be chosen to avoid having too many surfaces and molecules\nin one subpartition. \nIf there are few surfaces and/or molecules in a subvolume, it is advantageous to have the \nsubvolume as large as possible. Crossing partition boundaries takes a small amount of time, \nso it is rarely useful to have partitions more finely spaced than the average diffusion distance \nof the faster-moving molecules in the simulation.\n") .def_property("total_iterations", &Config::get_total_iterations, &Config::set_total_iterations, "Required for checkpointing so that the checkpointed model has information on\nthe intended total number of iterations. \nAlso used when generating visualization data files and also for other reporting uses. \nValue is truncated to an integer.\n") .def_property("check_overlapped_walls", &Config::get_check_overlapped_walls, &Config::set_check_overlapped_walls, "Enables check for overlapped walls. Overlapping walls can cause issues during \nsimulation such as a molecule escaping closed geometry when it hits two walls \nthat overlap. \n") .def_property("reaction_class_cleanup_periodicity", &Config::get_reaction_class_cleanup_periodicity, &Config::set_reaction_class_cleanup_periodicity, "Reaction class cleanup removes computed reaction classes for inactive species from memory.\nThis provides faster reaction lookup faster but when the same reaction class is \nneeded again, it must be recomputed.\n") .def_property("species_cleanup_periodicity", &Config::get_species_cleanup_periodicity, &Config::set_species_cleanup_periodicity, "Species cleanup removes inactive species from memory. It removes also all reaction classes \nthat reference it.\nThis provides faster addition of new species lookup faster but when the species is \nneeded again, it must be recomputed.\n") .def_property("molecules_order_random_shuffle_periodicity", &Config::get_molecules_order_random_shuffle_periodicity, &Config::set_molecules_order_random_shuffle_periodicity, "Randomly shuffle the order in which molecules are simulated.\nThis helps to overcome potential biases that may occur when \nmolecules are ordered e.g. by their species when simulation starts. \nThe first shuffling occurs at this iteration, i.e. no shuffle is done at iteration 0.\nSetting this parameter to 0 disables the shuffling. \n") .def_property("sort_molecules", &Config::get_sort_molecules, &Config::set_sort_molecules, "Enables sorting of molecules for diffusion, this may improve cache locality and provide \nslightly better performance. \nProduces different results for the same seed when enabled because molecules are simulated \nin a different order. \n") .def_property("memory_limit_gb", &Config::get_memory_limit_gb, &Config::set_memory_limit_gb, "Sets memory limit in GB for simulation run. \nWhen this limit is hit, all buffers are flushed and simulation is terminated with an error.\n") .def_property("initial_iteration", &Config::get_initial_iteration, &Config::set_initial_iteration, "Initial iteration, used when resuming a checkpoint.") .def_property("initial_time", &Config::get_initial_time, &Config::set_initial_time, "Initial time in us, used when resuming a checkpoint.\nWill be truncated to be a multiple of time step.\n") .def_property("initial_rng_state", &Config::get_initial_rng_state, &Config::set_initial_rng_state, "Used for checkpointing, may contain state of the random number generator to be set \nafter initialization right before the first event is started. \nWhen not set, the set 'seed' value is used to initialize the random number generator. \n") .def_property("append_to_count_output_data", &Config::get_append_to_count_output_data, &Config::set_append_to_count_output_data, "Used for checkpointing, instead of creating new files for Count observables data, \nnew values are appended to the existing files. If such files do not exist, new files are\ncreated.\n") .def_property("continue_after_sigalrm", &Config::get_continue_after_sigalrm, &Config::set_continue_after_sigalrm, "MCell registers a SIGALRM signal handler. When SIGALRM signal is received and \ncontinue_after_sigalrm is False, checkpoint is stored and simulation is terminated. \nWhen continue_after_sigalrm is True, checkpoint is stored and simulation continues.\nSIGALRM is not supported on Windows.\n") ; } std::string GenConfig::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "config_" + std::to_string(ctx.postinc_counter("config")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Config(" << nl; if (seed != 1) { ss << ind << "seed = " << seed << "," << nl; } if (time_step != 1e-6) { ss << ind << "time_step = " << f_to_str(time_step) << "," << nl; } if (use_bng_units != false) { ss << ind << "use_bng_units = " << use_bng_units << "," << nl; } if (surface_grid_density != 10000) { ss << ind << "surface_grid_density = " << f_to_str(surface_grid_density) << "," << nl; } if (interaction_radius != FLT_UNSET) { ss << ind << "interaction_radius = " << f_to_str(interaction_radius) << "," << nl; } if (intermembrane_interaction_radius != FLT_UNSET) { ss << ind << "intermembrane_interaction_radius = " << f_to_str(intermembrane_interaction_radius) << "," << nl; } if (vacancy_search_distance != 10) { ss << ind << "vacancy_search_distance = " << f_to_str(vacancy_search_distance) << "," << nl; } if (center_molecules_on_grid != false) { ss << ind << "center_molecules_on_grid = " << center_molecules_on_grid << "," << nl; } if (partition_dimension != 10) { ss << ind << "partition_dimension = " << f_to_str(partition_dimension) << "," << nl; } if (initial_partition_origin != std::vector<double>() && !skip_vectors_export()) { ss << ind << "initial_partition_origin = " << export_vec_initial_partition_origin(out, ctx, exported_name) << "," << nl; } if (subpartition_dimension != 0.5) { ss << ind << "subpartition_dimension = " << f_to_str(subpartition_dimension) << "," << nl; } if (total_iterations != 1000000) { ss << ind << "total_iterations = " << f_to_str(total_iterations) << "," << nl; } if (check_overlapped_walls != true) { ss << ind << "check_overlapped_walls = " << check_overlapped_walls << "," << nl; } if (reaction_class_cleanup_periodicity != 500) { ss << ind << "reaction_class_cleanup_periodicity = " << reaction_class_cleanup_periodicity << "," << nl; } if (species_cleanup_periodicity != 10000) { ss << ind << "species_cleanup_periodicity = " << species_cleanup_periodicity << "," << nl; } if (molecules_order_random_shuffle_periodicity != 10000) { ss << ind << "molecules_order_random_shuffle_periodicity = " << molecules_order_random_shuffle_periodicity << "," << nl; } if (sort_molecules != false) { ss << ind << "sort_molecules = " << sort_molecules << "," << nl; } if (memory_limit_gb != -1) { ss << ind << "memory_limit_gb = " << memory_limit_gb << "," << nl; } if (initial_iteration != 0) { ss << ind << "initial_iteration = " << initial_iteration << "," << nl; } if (initial_time != 0) { ss << ind << "initial_time = " << f_to_str(initial_time) << "," << nl; } if (is_set(initial_rng_state)) { ss << ind << "initial_rng_state = " << initial_rng_state->export_to_python(out, ctx) << "," << nl; } if (append_to_count_output_data != false) { ss << ind << "append_to_count_output_data = " << append_to_count_output_data << "," << nl; } if (continue_after_sigalrm != false) { ss << ind << "continue_after_sigalrm = " << continue_after_sigalrm << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenConfig::export_vec_initial_partition_origin(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < initial_partition_origin.size(); i++) { const auto& item = initial_partition_origin[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << f_to_str(item) << ", "; } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_run_utils.cpp
.cpp
1,231
30
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_run_utils.h" namespace MCell { namespace API { void define_pybinding_run_utils(py::module& m) { m.def_submodule("run_utils") .def("get_last_checkpoint_dir", &run_utils::get_last_checkpoint_dir, py::arg("seed"), "Searches the directory checkpoints for the last checkpoint for the given \nparameters and returns the directory name if such a directory exists. \nReturns empty string if no checkpoint directory was found.\nCurrently supports only the seed argument.\n\n- seed\n") .def("remove_cwd", &run_utils::remove_cwd, py::arg("paths"), "Removes all directory names items pointing to the current working directory from a list and \nreturns a new list.\n\n- paths\n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_elementary_molecule.cpp
.cpp
7,920
194
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_elementary_molecule.h" #include "api/elementary_molecule.h" #include "api/component.h" #include "api/elementary_molecule_type.h" namespace MCell { namespace API { void GenElementaryMolecule::check_semantics() const { if (!is_set(elementary_molecule_type)) { throw ValueError("Parameter 'elementary_molecule_type' must be set."); } } void GenElementaryMolecule::set_initialized() { if (is_set(elementary_molecule_type)) { elementary_molecule_type->set_initialized(); } vec_set_initialized(components); initialized = true; } void GenElementaryMolecule::set_all_attributes_as_default_or_unset() { class_name = "ElementaryMolecule"; elementary_molecule_type = nullptr; components = std::vector<std::shared_ptr<Component>>(); compartment_name = STR_UNSET; } std::shared_ptr<ElementaryMolecule> GenElementaryMolecule::copy_elementary_molecule() const { std::shared_ptr<ElementaryMolecule> res = std::make_shared<ElementaryMolecule>(DefaultCtorArgType()); res->class_name = class_name; res->elementary_molecule_type = elementary_molecule_type; res->components = components; res->compartment_name = compartment_name; return res; } std::shared_ptr<ElementaryMolecule> GenElementaryMolecule::deepcopy_elementary_molecule(py::dict) const { std::shared_ptr<ElementaryMolecule> res = std::make_shared<ElementaryMolecule>(DefaultCtorArgType()); res->class_name = class_name; res->elementary_molecule_type = is_set(elementary_molecule_type) ? elementary_molecule_type->deepcopy_elementary_molecule_type() : nullptr; for (const auto& item: components) { res->components.push_back((is_set(item)) ? item->deepcopy_component() : nullptr); } res->compartment_name = compartment_name; return res; } bool GenElementaryMolecule::__eq__(const ElementaryMolecule& other) const { return ( (is_set(elementary_molecule_type)) ? (is_set(other.elementary_molecule_type) ? (elementary_molecule_type->__eq__(*other.elementary_molecule_type)) : false ) : (is_set(other.elementary_molecule_type) ? false : true ) ) && vec_ptr_eq(components, other.components) && compartment_name == other.compartment_name; } bool GenElementaryMolecule::eq_nonarray_attributes(const ElementaryMolecule& other, const bool ignore_name) const { return ( (is_set(elementary_molecule_type)) ? (is_set(other.elementary_molecule_type) ? (elementary_molecule_type->__eq__(*other.elementary_molecule_type)) : false ) : (is_set(other.elementary_molecule_type) ? false : true ) ) && true /*components*/ && compartment_name == other.compartment_name; } std::string GenElementaryMolecule::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "elementary_molecule_type=" << "(" << ((elementary_molecule_type != nullptr) ? elementary_molecule_type->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "components=" << vec_ptr_to_str(components, all_details, ind + " ") << ", " << "\n" << ind + " " << "compartment_name=" << compartment_name; return ss.str(); } py::class_<ElementaryMolecule> define_pybinding_ElementaryMolecule(py::module& m) { return py::class_<ElementaryMolecule, std::shared_ptr<ElementaryMolecule>>(m, "ElementaryMolecule", "Instance of an elementary molecule type. A BNGL complex is composed of elementary molecules.") .def( py::init< std::shared_ptr<ElementaryMoleculeType>, const std::vector<std::shared_ptr<Component>>, const std::string& >(), py::arg("elementary_molecule_type"), py::arg("components") = std::vector<std::shared_ptr<Component>>(), py::arg("compartment_name") = STR_UNSET ) .def("check_semantics", &ElementaryMolecule::check_semantics) .def("__copy__", &ElementaryMolecule::copy_elementary_molecule) .def("__deepcopy__", &ElementaryMolecule::deepcopy_elementary_molecule, py::arg("memo")) .def("__str__", &ElementaryMolecule::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ElementaryMolecule::__eq__, py::arg("other")) .def("to_bngl_str", &ElementaryMolecule::to_bngl_str, py::arg("with_compartment") = true, "Creates a string that corresponds to its BNGL representation\n- with_compartment: Include compartment name in the returned BNGL string.\n\n") .def("dump", &ElementaryMolecule::dump) .def_property("elementary_molecule_type", &ElementaryMolecule::get_elementary_molecule_type, &ElementaryMolecule::set_elementary_molecule_type, "Reference to the type of this elementary molecule.") .def_property("components", &ElementaryMolecule::get_components, &ElementaryMolecule::set_components, py::return_value_policy::reference, "List of component instances. Not all components need to be specified \nin case when this elementary molecule is used in a pattern.\n") .def_property("compartment_name", &ElementaryMolecule::get_compartment_name, &ElementaryMolecule::set_compartment_name, "Optional BNGL compartment name for this elemenrary molecule. If a 2D/surface compartment is specified, the elementary moelcule must be of surface type. If a 3D/volume compartment is specified, the elementary moelcule must be of volume type.") ; } std::string GenElementaryMolecule::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "elementary_molecule_" + std::to_string(ctx.postinc_counter("elementary_molecule")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ElementaryMolecule(" << nl; ss << ind << "elementary_molecule_type = " << elementary_molecule_type->export_to_python(out, ctx) << "," << nl; if (components != std::vector<std::shared_ptr<Component>>() && !skip_vectors_export()) { ss << ind << "components = " << export_vec_components(out, ctx, exported_name) << "," << nl; } if (compartment_name != STR_UNSET) { ss << ind << "compartment_name = " << "'" << compartment_name << "'" << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenElementaryMolecule::export_vec_components(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < components.size(); i++) { const auto& item = components[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_viz_output.h
.h
4,969
135
/****************************************************************************** * * Copyright (C) 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 API_GEN_VIZ_OUTPUT_H #define API_GEN_VIZ_OUTPUT_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class VizOutput; class Species; class PythonExportContext; #define VIZ_OUTPUT_CTOR() \ VizOutput( \ const std::string& output_files_prefix_ = STR_UNSET, \ const std::vector<std::shared_ptr<Species>> species_list_ = std::vector<std::shared_ptr<Species>>(), \ const VizMode mode_ = VizMode::ASCII, \ const double every_n_timesteps_ = 1 \ ) { \ class_name = "VizOutput"; \ output_files_prefix = output_files_prefix_; \ species_list = species_list_; \ mode = mode_; \ every_n_timesteps = every_n_timesteps_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ VizOutput(DefaultCtorArgType) : \ GenVizOutput(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenVizOutput: public BaseDataClass { public: GenVizOutput() { } GenVizOutput(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<VizOutput> copy_viz_output() const; std::shared_ptr<VizOutput> deepcopy_viz_output(py::dict = py::dict()) const; virtual bool __eq__(const VizOutput& other) const; virtual bool eq_nonarray_attributes(const VizOutput& other, const bool ignore_name = false) const; bool operator == (const VizOutput& other) const { return __eq__(other);} bool operator != (const VizOutput& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_species_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::string output_files_prefix; virtual void set_output_files_prefix(const std::string& new_output_files_prefix_) { if (initialized) { throw RuntimeError("Value 'output_files_prefix' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; output_files_prefix = new_output_files_prefix_; } virtual const std::string& get_output_files_prefix() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return output_files_prefix; } std::vector<std::shared_ptr<Species>> species_list; virtual void set_species_list(const std::vector<std::shared_ptr<Species>> new_species_list_) { if (initialized) { throw RuntimeError("Value 'species_list' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; species_list = new_species_list_; } virtual std::vector<std::shared_ptr<Species>>& get_species_list() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return species_list; } VizMode mode; virtual void set_mode(const VizMode new_mode_) { if (initialized) { throw RuntimeError("Value 'mode' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; mode = new_mode_; } virtual VizMode get_mode() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return mode; } double every_n_timesteps; virtual void set_every_n_timesteps(const double new_every_n_timesteps_) { if (initialized) { throw RuntimeError("Value 'every_n_timesteps' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; every_n_timesteps = new_every_n_timesteps_; } virtual double get_every_n_timesteps() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return every_n_timesteps; } // --- methods --- }; // GenVizOutput class VizOutput; py::class_<VizOutput> define_pybinding_VizOutput(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_VIZ_OUTPUT_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_chkpt_vol_mol.h
.h
3,502
108
/****************************************************************************** * * Copyright (C) 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 API_GEN_CHKPT_VOL_MOL_H #define API_GEN_CHKPT_VOL_MOL_H #include "api/api_common.h" #include "api/base_chkpt_mol.h" namespace MCell { namespace API { class ChkptVolMol; class Species; class PythonExportContext; #define CHKPT_VOL_MOL_CTOR() \ ChkptVolMol( \ const Vec3& pos_, \ const int id_, \ std::shared_ptr<Species> species_, \ const double diffusion_time_, \ const double birthday_, \ const int flags_, \ const double unimol_rxn_time_ = FLT_UNSET \ ) : GenChkptVolMol(id_,species_,diffusion_time_,birthday_,flags_,unimol_rxn_time_) { \ class_name = "ChkptVolMol"; \ pos = pos_; \ id = id_; \ species = species_; \ diffusion_time = diffusion_time_; \ birthday = birthday_; \ flags = flags_; \ unimol_rxn_time = unimol_rxn_time_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ChkptVolMol(DefaultCtorArgType) : \ GenChkptVolMol(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenChkptVolMol: public BaseChkptMol { public: GenChkptVolMol( const int id_, std::shared_ptr<Species> species_, const double diffusion_time_, const double birthday_, const int flags_, const double unimol_rxn_time_ = FLT_UNSET ) : BaseChkptMol(id_,species_,diffusion_time_,birthday_,flags_,unimol_rxn_time_) { } GenChkptVolMol() : BaseChkptMol(DefaultCtorArgType()) { } GenChkptVolMol(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ChkptVolMol> copy_chkpt_vol_mol() const; std::shared_ptr<ChkptVolMol> deepcopy_chkpt_vol_mol(py::dict = py::dict()) const; virtual bool __eq__(const ChkptVolMol& other) const; virtual bool eq_nonarray_attributes(const ChkptVolMol& other, const bool ignore_name = false) const; bool operator == (const ChkptVolMol& other) const { return __eq__(other);} bool operator != (const ChkptVolMol& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); // --- attributes --- Vec3 pos; virtual void set_pos(const Vec3& new_pos_) { if (initialized) { throw RuntimeError("Value 'pos' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; pos = new_pos_; } virtual const Vec3& get_pos() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return pos; } // --- methods --- }; // GenChkptVolMol class ChkptVolMol; py::class_<ChkptVolMol> define_pybinding_ChkptVolMol(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_CHKPT_VOL_MOL_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_viz_output.cpp
.cpp
6,918
180
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_viz_output.h" #include "api/viz_output.h" #include "api/species.h" namespace MCell { namespace API { void GenVizOutput::check_semantics() const { } void GenVizOutput::set_initialized() { vec_set_initialized(species_list); initialized = true; } void GenVizOutput::set_all_attributes_as_default_or_unset() { class_name = "VizOutput"; output_files_prefix = STR_UNSET; species_list = std::vector<std::shared_ptr<Species>>(); mode = VizMode::ASCII; every_n_timesteps = 1; } std::shared_ptr<VizOutput> GenVizOutput::copy_viz_output() const { std::shared_ptr<VizOutput> res = std::make_shared<VizOutput>(DefaultCtorArgType()); res->class_name = class_name; res->output_files_prefix = output_files_prefix; res->species_list = species_list; res->mode = mode; res->every_n_timesteps = every_n_timesteps; return res; } std::shared_ptr<VizOutput> GenVizOutput::deepcopy_viz_output(py::dict) const { std::shared_ptr<VizOutput> res = std::make_shared<VizOutput>(DefaultCtorArgType()); res->class_name = class_name; res->output_files_prefix = output_files_prefix; for (const auto& item: species_list) { res->species_list.push_back((is_set(item)) ? item->deepcopy_species() : nullptr); } res->mode = mode; res->every_n_timesteps = every_n_timesteps; return res; } bool GenVizOutput::__eq__(const VizOutput& other) const { return output_files_prefix == other.output_files_prefix && vec_ptr_eq(species_list, other.species_list) && mode == other.mode && every_n_timesteps == other.every_n_timesteps; } bool GenVizOutput::eq_nonarray_attributes(const VizOutput& other, const bool ignore_name) const { return output_files_prefix == other.output_files_prefix && true /*species_list*/ && mode == other.mode && every_n_timesteps == other.every_n_timesteps; } std::string GenVizOutput::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "output_files_prefix=" << output_files_prefix << ", " << "\n" << ind + " " << "species_list=" << vec_ptr_to_str(species_list, all_details, ind + " ") << ", " << "\n" << ind + " " << "mode=" << mode << ", " << "every_n_timesteps=" << every_n_timesteps; return ss.str(); } py::class_<VizOutput> define_pybinding_VizOutput(py::module& m) { return py::class_<VizOutput, std::shared_ptr<VizOutput>>(m, "VizOutput", "Defines a visualization output with locations of molecules \nthat can be then loaded by CellBlender.\n") .def( py::init< const std::string&, const std::vector<std::shared_ptr<Species>>, const VizMode, const double >(), py::arg("output_files_prefix") = STR_UNSET, py::arg("species_list") = std::vector<std::shared_ptr<Species>>(), py::arg("mode") = VizMode::ASCII, py::arg("every_n_timesteps") = 1 ) .def("check_semantics", &VizOutput::check_semantics) .def("__copy__", &VizOutput::copy_viz_output) .def("__deepcopy__", &VizOutput::deepcopy_viz_output, py::arg("memo")) .def("__str__", &VizOutput::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &VizOutput::__eq__, py::arg("other")) .def("dump", &VizOutput::dump) .def_property("output_files_prefix", &VizOutput::get_output_files_prefix, &VizOutput::set_output_files_prefix, "Prefix for the viz output files.\nWhen not set, the default prefix value is computed from the simulation seed\nwhen the model is initialized to: \n'./viz_data/seed_' + str(seed).zfill(5) + '/Scene'.\n") .def_property("species_list", &VizOutput::get_species_list, &VizOutput::set_species_list, py::return_value_policy::reference, "Specifies a list of species to be visualized, when empty, all_species will be generated.") .def_property("mode", &VizOutput::get_mode, &VizOutput::set_mode, "Specified the output format of the visualization files. \nVizMode.ASCII is a readable representation, VizMode.CELLBLENDER is a binary representation \nthat cannot be read using a text editor but is faster to generate. \n") .def_property("every_n_timesteps", &VizOutput::get_every_n_timesteps, &VizOutput::set_every_n_timesteps, "Specifies periodicity of visualization output.\nValue is truncated (floored) to an integer.\nValue 0 means that the viz output is ran only once at iteration 0. \n") ; } std::string GenVizOutput::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "viz_output_" + std::to_string(ctx.postinc_counter("viz_output")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.VizOutput(" << nl; if (output_files_prefix != STR_UNSET) { ss << ind << "output_files_prefix = " << "'" << output_files_prefix << "'" << "," << nl; } if (species_list != std::vector<std::shared_ptr<Species>>() && !skip_vectors_export()) { ss << ind << "species_list = " << export_vec_species_list(out, ctx, exported_name) << "," << nl; } if (mode != VizMode::ASCII) { ss << ind << "mode = " << mode << "," << nl; } if (every_n_timesteps != 1) { ss << ind << "every_n_timesteps = " << f_to_str(every_n_timesteps) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenVizOutput::export_vec_species_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < species_list.size(); i++) { const auto& item = species_list[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_wall_wall_hit_info.h
.h
3,281
97
/****************************************************************************** * * Copyright (C) 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 API_GEN_WALL_WALL_HIT_INFO_H #define API_GEN_WALL_WALL_HIT_INFO_H #include "api/api_common.h" #include "api/base_introspection_class.h" namespace MCell { namespace API { class WallWallHitInfo; class Wall; class PythonExportContext; #define WALL_WALL_HIT_INFO_CTOR_NOARGS() \ WallWallHitInfo( \ ) { \ class_name = "WallWallHitInfo"; \ wall1 = nullptr; \ wall2 = nullptr; \ postprocess_in_ctor(); \ check_semantics(); \ } \ WallWallHitInfo(DefaultCtorArgType) : \ GenWallWallHitInfo(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenWallWallHitInfo: public BaseIntrospectionClass { public: GenWallWallHitInfo() { } GenWallWallHitInfo(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<WallWallHitInfo> copy_wall_wall_hit_info() const; std::shared_ptr<WallWallHitInfo> deepcopy_wall_wall_hit_info(py::dict = py::dict()) const; virtual bool __eq__(const WallWallHitInfo& other) const; virtual bool eq_nonarray_attributes(const WallWallHitInfo& other, const bool ignore_name = false) const; bool operator == (const WallWallHitInfo& other) const { return __eq__(other);} bool operator != (const WallWallHitInfo& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; // --- attributes --- std::shared_ptr<Wall> wall1; virtual void set_wall1(std::shared_ptr<Wall> new_wall1_) { if (initialized) { throw RuntimeError("Value 'wall1' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall1 = new_wall1_; } virtual std::shared_ptr<Wall> get_wall1() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall1; } std::shared_ptr<Wall> wall2; virtual void set_wall2(std::shared_ptr<Wall> new_wall2_) { if (initialized) { throw RuntimeError("Value 'wall2' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall2 = new_wall2_; } virtual std::shared_ptr<Wall> get_wall2() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall2; } // --- methods --- }; // GenWallWallHitInfo class WallWallHitInfo; py::class_<WallWallHitInfo> define_pybinding_WallWallHitInfo(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_WALL_WALL_HIT_INFO_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_elementary_molecule.h
.h
4,887
121
/****************************************************************************** * * Copyright (C) 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 API_GEN_ELEMENTARY_MOLECULE_H #define API_GEN_ELEMENTARY_MOLECULE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ElementaryMolecule; class Component; class ElementaryMoleculeType; class PythonExportContext; #define ELEMENTARY_MOLECULE_CTOR() \ ElementaryMolecule( \ std::shared_ptr<ElementaryMoleculeType> elementary_molecule_type_, \ const std::vector<std::shared_ptr<Component>> components_ = std::vector<std::shared_ptr<Component>>(), \ const std::string& compartment_name_ = STR_UNSET \ ) { \ class_name = "ElementaryMolecule"; \ elementary_molecule_type = elementary_molecule_type_; \ components = components_; \ compartment_name = compartment_name_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ElementaryMolecule(DefaultCtorArgType) : \ GenElementaryMolecule(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenElementaryMolecule: public BaseDataClass { public: GenElementaryMolecule() { } GenElementaryMolecule(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ElementaryMolecule> copy_elementary_molecule() const; std::shared_ptr<ElementaryMolecule> deepcopy_elementary_molecule(py::dict = py::dict()) const; virtual bool __eq__(const ElementaryMolecule& other) const; virtual bool eq_nonarray_attributes(const ElementaryMolecule& other, const bool ignore_name = false) const; bool operator == (const ElementaryMolecule& other) const { return __eq__(other);} bool operator != (const ElementaryMolecule& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_components(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::shared_ptr<ElementaryMoleculeType> elementary_molecule_type; virtual void set_elementary_molecule_type(std::shared_ptr<ElementaryMoleculeType> new_elementary_molecule_type_) { if (initialized) { throw RuntimeError("Value 'elementary_molecule_type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; elementary_molecule_type = new_elementary_molecule_type_; } virtual std::shared_ptr<ElementaryMoleculeType> get_elementary_molecule_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return elementary_molecule_type; } std::vector<std::shared_ptr<Component>> components; virtual void set_components(const std::vector<std::shared_ptr<Component>> new_components_) { if (initialized) { throw RuntimeError("Value 'components' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; components = new_components_; } virtual std::vector<std::shared_ptr<Component>>& get_components() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return components; } std::string compartment_name; virtual void set_compartment_name(const std::string& new_compartment_name_) { if (initialized) { throw RuntimeError("Value 'compartment_name' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; compartment_name = new_compartment_name_; } virtual const std::string& get_compartment_name() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return compartment_name; } // --- methods --- virtual std::string to_bngl_str(const bool with_compartment = true) const = 0; }; // GenElementaryMolecule class ElementaryMolecule; py::class_<ElementaryMolecule> define_pybinding_ElementaryMolecule(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_ELEMENTARY_MOLECULE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_rng_state.cpp
.cpp
7,192
234
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_rng_state.h" #include "api/rng_state.h" namespace MCell { namespace API { void GenRngState::check_semantics() const { if (!is_set(randcnt)) { throw ValueError("Parameter 'randcnt' must be set."); } if (!is_set(aa)) { throw ValueError("Parameter 'aa' must be set."); } if (!is_set(bb)) { throw ValueError("Parameter 'bb' must be set."); } if (!is_set(cc)) { throw ValueError("Parameter 'cc' must be set."); } if (!is_set(randslr)) { throw ValueError("Parameter 'randslr' must be set and the value must not be an empty list."); } if (!is_set(mm)) { throw ValueError("Parameter 'mm' must be set and the value must not be an empty list."); } if (!is_set(rngblocks)) { throw ValueError("Parameter 'rngblocks' must be set."); } } void GenRngState::set_initialized() { initialized = true; } void GenRngState::set_all_attributes_as_default_or_unset() { class_name = "RngState"; randcnt = 0; aa = 0; bb = 0; cc = 0; randslr = std::vector<uint64_t>(); mm = std::vector<uint64_t>(); rngblocks = 0; } std::shared_ptr<RngState> GenRngState::copy_rng_state() const { std::shared_ptr<RngState> res = std::make_shared<RngState>(DefaultCtorArgType()); res->class_name = class_name; res->randcnt = randcnt; res->aa = aa; res->bb = bb; res->cc = cc; res->randslr = randslr; res->mm = mm; res->rngblocks = rngblocks; return res; } std::shared_ptr<RngState> GenRngState::deepcopy_rng_state(py::dict) const { std::shared_ptr<RngState> res = std::make_shared<RngState>(DefaultCtorArgType()); res->class_name = class_name; res->randcnt = randcnt; res->aa = aa; res->bb = bb; res->cc = cc; res->randslr = randslr; res->mm = mm; res->rngblocks = rngblocks; return res; } bool GenRngState::__eq__(const RngState& other) const { return randcnt == other.randcnt && aa == other.aa && bb == other.bb && cc == other.cc && randslr == other.randslr && mm == other.mm && rngblocks == other.rngblocks; } bool GenRngState::eq_nonarray_attributes(const RngState& other, const bool ignore_name) const { return randcnt == other.randcnt && aa == other.aa && bb == other.bb && cc == other.cc && true /*randslr*/ && true /*mm*/ && rngblocks == other.rngblocks; } std::string GenRngState::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "randcnt=" << randcnt << ", " << "aa=" << aa << ", " << "bb=" << bb << ", " << "cc=" << cc << ", " << "randslr=" << vec_nonptr_to_str(randslr, all_details, ind + " ") << ", " << "mm=" << vec_nonptr_to_str(mm, all_details, ind + " ") << ", " << "rngblocks=" << rngblocks; return ss.str(); } py::class_<RngState> define_pybinding_RngState(py::module& m) { return py::class_<RngState, std::shared_ptr<RngState>>(m, "RngState", "Internal checkpointing structure holding state of the random number generator.") .def( py::init< const uint64_t, const uint64_t, const uint64_t, const uint64_t, const std::vector<uint64_t>, const std::vector<uint64_t>, const uint64_t >(), py::arg("randcnt"), py::arg("aa"), py::arg("bb"), py::arg("cc"), py::arg("randslr"), py::arg("mm"), py::arg("rngblocks") ) .def("check_semantics", &RngState::check_semantics) .def("__copy__", &RngState::copy_rng_state) .def("__deepcopy__", &RngState::deepcopy_rng_state, py::arg("memo")) .def("__str__", &RngState::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &RngState::__eq__, py::arg("other")) .def("dump", &RngState::dump) .def_property("randcnt", &RngState::get_randcnt, &RngState::set_randcnt) .def_property("aa", &RngState::get_aa, &RngState::set_aa) .def_property("bb", &RngState::get_bb, &RngState::set_bb) .def_property("cc", &RngState::get_cc, &RngState::set_cc) .def_property("randslr", &RngState::get_randslr, &RngState::set_randslr, py::return_value_policy::reference, "Must contain RNG_SIZE items.") .def_property("mm", &RngState::get_mm, &RngState::set_mm, py::return_value_policy::reference, "Must contain RNG_SIZE items.") .def_property("rngblocks", &RngState::get_rngblocks, &RngState::set_rngblocks, "Must contain RNG_SIZE items.") ; } std::string GenRngState::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "rng_state_" + std::to_string(ctx.postinc_counter("rng_state")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.RngState(" << nl; ss << ind << "randcnt = " << randcnt << "," << nl; ss << ind << "aa = " << aa << "," << nl; ss << ind << "bb = " << bb << "," << nl; ss << ind << "cc = " << cc << "," << nl; ss << ind << "randslr = " << export_vec_randslr(out, ctx, exported_name) << "," << nl; ss << ind << "mm = " << export_vec_mm(out, ctx, exported_name) << "," << nl; ss << ind << "rngblocks = " << rngblocks << "," << nl; ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenRngState::export_vec_randslr(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < randslr.size(); i++) { const auto& item = randslr[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << item << ", "; } ss << "]"; return ss.str(); } std::string GenRngState::export_vec_mm(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < mm.size(); i++) { const auto& item = mm[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << item << ", "; } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_region.cpp
.cpp
6,362
193
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_region.h" #include "api/region.h" #include "api/region.h" namespace MCell { namespace API { void GenRegion::check_semantics() const { } void GenRegion::set_initialized() { if (is_set(left_node)) { left_node->set_initialized(); } if (is_set(right_node)) { right_node->set_initialized(); } initialized = true; } void GenRegion::set_all_attributes_as_default_or_unset() { class_name = "Region"; node_type = RegionNodeType::UNSET; left_node = nullptr; right_node = nullptr; } std::shared_ptr<Region> GenRegion::copy_region() const { std::shared_ptr<Region> res = std::make_shared<Region>(DefaultCtorArgType()); res->class_name = class_name; res->node_type = node_type; res->left_node = left_node; res->right_node = right_node; return res; } std::shared_ptr<Region> GenRegion::deepcopy_region(py::dict) const { std::shared_ptr<Region> res = std::make_shared<Region>(DefaultCtorArgType()); res->class_name = class_name; res->node_type = node_type; res->left_node = is_set(left_node) ? left_node->deepcopy_region() : nullptr; res->right_node = is_set(right_node) ? right_node->deepcopy_region() : nullptr; return res; } bool GenRegion::__eq__(const Region& other) const { return node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } bool GenRegion::eq_nonarray_attributes(const Region& other, const bool ignore_name) const { return node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } std::string GenRegion::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "node_type=" << node_type << ", " << "\n" << ind + " " << "left_node=" << "(" << ((left_node != nullptr) ? left_node->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "right_node=" << "(" << ((right_node != nullptr) ? right_node->to_str(all_details, ind + " ") : "null" ) << ")"; return ss.str(); } py::class_<Region> define_pybinding_Region(py::module& m) { return py::class_<Region, std::shared_ptr<Region>>(m, "Region", "Represents region construted from 1 or more multiple, usually unnamed?") .def( py::init< const RegionNodeType, std::shared_ptr<Region>, std::shared_ptr<Region> >(), py::arg("node_type") = RegionNodeType::UNSET, py::arg("left_node") = nullptr, py::arg("right_node") = nullptr ) .def("check_semantics", &Region::check_semantics) .def("__copy__", &Region::copy_region) .def("__deepcopy__", &Region::deepcopy_region, py::arg("memo")) .def("__str__", &Region::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Region::__eq__, py::arg("other")) .def("__add__", &Region::__add__, py::arg("other"), "Computes union of two regions, use with Python operator '+'.\n- other\n") .def("__sub__", &Region::__sub__, py::arg("other"), "Computes difference of two regions, use with Python operator '-'.\n- other\n") .def("__mul__", &Region::__mul__, py::arg("other"), "Computes intersection of two regions, use with Python operator '*'.\n- other\n") .def("dump", &Region::dump) .def_property("node_type", &Region::get_node_type, &Region::set_node_type, "When this values is LeafGeometryObject, then this object is of class GeometryObject,\nwhen LeafSurfaceRegion, then it is of class SurfaceRegion.\n") .def_property("left_node", &Region::get_left_node, &Region::set_left_node, "Internal, do not use. When node_type is not Leaf, this is the left operand") .def_property("right_node", &Region::get_right_node, &Region::set_right_node, "Internal, do not use. When node_type is not Leaf, this is the right operand") ; } std::string GenRegion::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "region_" + std::to_string(ctx.postinc_counter("region")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Region(" << nl; if (node_type != RegionNodeType::UNSET) { ss << ind << "node_type = " << node_type << "," << nl; } if (is_set(left_node)) { ss << ind << "left_node = " << left_node->export_to_python(out, ctx) << "," << nl; } if (is_set(right_node)) { ss << ind << "right_node = " << right_node->export_to_python(out, ctx) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_wall_wall_hit_info.cpp
.cpp
4,383
145
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_wall_wall_hit_info.h" #include "api/wall_wall_hit_info.h" #include "api/wall.h" namespace MCell { namespace API { void GenWallWallHitInfo::check_semantics() const { if (!is_set(wall1)) { throw ValueError("Parameter 'wall1' must be set."); } if (!is_set(wall2)) { throw ValueError("Parameter 'wall2' must be set."); } } void GenWallWallHitInfo::set_initialized() { if (is_set(wall1)) { wall1->set_initialized(); } if (is_set(wall2)) { wall2->set_initialized(); } initialized = true; } void GenWallWallHitInfo::set_all_attributes_as_default_or_unset() { class_name = "WallWallHitInfo"; wall1 = nullptr; wall2 = nullptr; } std::shared_ptr<WallWallHitInfo> GenWallWallHitInfo::copy_wall_wall_hit_info() const { std::shared_ptr<WallWallHitInfo> res = std::make_shared<WallWallHitInfo>(DefaultCtorArgType()); res->class_name = class_name; res->wall1 = wall1; res->wall2 = wall2; return res; } std::shared_ptr<WallWallHitInfo> GenWallWallHitInfo::deepcopy_wall_wall_hit_info(py::dict) const { std::shared_ptr<WallWallHitInfo> res = std::make_shared<WallWallHitInfo>(DefaultCtorArgType()); res->class_name = class_name; res->wall1 = is_set(wall1) ? wall1->deepcopy_wall() : nullptr; res->wall2 = is_set(wall2) ? wall2->deepcopy_wall() : nullptr; return res; } bool GenWallWallHitInfo::__eq__(const WallWallHitInfo& other) const { return ( (is_set(wall1)) ? (is_set(other.wall1) ? (wall1->__eq__(*other.wall1)) : false ) : (is_set(other.wall1) ? false : true ) ) && ( (is_set(wall2)) ? (is_set(other.wall2) ? (wall2->__eq__(*other.wall2)) : false ) : (is_set(other.wall2) ? false : true ) ) ; } bool GenWallWallHitInfo::eq_nonarray_attributes(const WallWallHitInfo& other, const bool ignore_name) const { return ( (is_set(wall1)) ? (is_set(other.wall1) ? (wall1->__eq__(*other.wall1)) : false ) : (is_set(other.wall1) ? false : true ) ) && ( (is_set(wall2)) ? (is_set(other.wall2) ? (wall2->__eq__(*other.wall2)) : false ) : (is_set(other.wall2) ? false : true ) ) ; } std::string GenWallWallHitInfo::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "wall1=" << "(" << ((wall1 != nullptr) ? wall1->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall2=" << "(" << ((wall2 != nullptr) ? wall2->to_str(all_details, ind + " ") : "null" ) << ")"; return ss.str(); } py::class_<WallWallHitInfo> define_pybinding_WallWallHitInfo(py::module& m) { return py::class_<WallWallHitInfo, std::shared_ptr<WallWallHitInfo>>(m, "WallWallHitInfo", "This class is used in the return type of Model.apply_vertex_moves.\nContains pair of walls that collided.\n") .def( py::init< >() ) .def("check_semantics", &WallWallHitInfo::check_semantics) .def("__copy__", &WallWallHitInfo::copy_wall_wall_hit_info) .def("__deepcopy__", &WallWallHitInfo::deepcopy_wall_wall_hit_info, py::arg("memo")) .def("__str__", &WallWallHitInfo::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &WallWallHitInfo::__eq__, py::arg("other")) .def("dump", &WallWallHitInfo::dump) .def_property("wall1", &WallWallHitInfo::get_wall1, &WallWallHitInfo::set_wall1, "First colliding wall.") .def_property("wall2", &WallWallHitInfo::get_wall2, &WallWallHitInfo::set_wall2, "Second colliding wall.") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_release_site.cpp
.cpp
17,205
391
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_release_site.h" #include "api/release_site.h" #include "api/complex.h" #include "api/molecule_release_info.h" #include "api/region.h" #include "api/release_pattern.h" namespace MCell { namespace API { void GenReleaseSite::check_semantics() const { if (!is_set(name)) { throw ValueError("Parameter 'name' must be set."); } } void GenReleaseSite::set_initialized() { if (is_set(complex)) { complex->set_initialized(); } vec_set_initialized(molecule_list); if (is_set(release_pattern)) { release_pattern->set_initialized(); } if (is_set(region)) { region->set_initialized(); } initialized = true; } void GenReleaseSite::set_all_attributes_as_default_or_unset() { class_name = "ReleaseSite"; name = STR_UNSET; complex = nullptr; molecule_list = std::vector<std::shared_ptr<MoleculeReleaseInfo>>(); release_time = 0; release_pattern = nullptr; shape = Shape::UNSET; region = nullptr; location = std::vector<double>(); site_diameter = 0; site_radius = FLT_UNSET; number_to_release = FLT_UNSET; density = FLT_UNSET; concentration = FLT_UNSET; release_probability = 1; } std::shared_ptr<ReleaseSite> GenReleaseSite::copy_release_site() const { std::shared_ptr<ReleaseSite> res = std::make_shared<ReleaseSite>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->complex = complex; res->molecule_list = molecule_list; res->release_time = release_time; res->release_pattern = release_pattern; res->shape = shape; res->region = region; res->location = location; res->site_diameter = site_diameter; res->site_radius = site_radius; res->number_to_release = number_to_release; res->density = density; res->concentration = concentration; res->release_probability = release_probability; return res; } std::shared_ptr<ReleaseSite> GenReleaseSite::deepcopy_release_site(py::dict) const { std::shared_ptr<ReleaseSite> res = std::make_shared<ReleaseSite>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->complex = is_set(complex) ? complex->deepcopy_complex() : nullptr; for (const auto& item: molecule_list) { res->molecule_list.push_back((is_set(item)) ? item->deepcopy_molecule_release_info() : nullptr); } res->release_time = release_time; res->release_pattern = is_set(release_pattern) ? release_pattern->deepcopy_release_pattern() : nullptr; res->shape = shape; res->region = is_set(region) ? region->deepcopy_region() : nullptr; res->location = location; res->site_diameter = site_diameter; res->site_radius = site_radius; res->number_to_release = number_to_release; res->density = density; res->concentration = concentration; res->release_probability = release_probability; return res; } bool GenReleaseSite::__eq__(const ReleaseSite& other) const { return name == other.name && ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && vec_ptr_eq(molecule_list, other.molecule_list) && release_time == other.release_time && ( (is_set(release_pattern)) ? (is_set(other.release_pattern) ? (release_pattern->__eq__(*other.release_pattern)) : false ) : (is_set(other.release_pattern) ? false : true ) ) && shape == other.shape && ( (is_set(region)) ? (is_set(other.region) ? (region->__eq__(*other.region)) : false ) : (is_set(other.region) ? false : true ) ) && location == other.location && site_diameter == other.site_diameter && site_radius == other.site_radius && number_to_release == other.number_to_release && density == other.density && concentration == other.concentration && release_probability == other.release_probability; } bool GenReleaseSite::eq_nonarray_attributes(const ReleaseSite& other, const bool ignore_name) const { return (ignore_name || name == other.name) && ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && true /*molecule_list*/ && release_time == other.release_time && ( (is_set(release_pattern)) ? (is_set(other.release_pattern) ? (release_pattern->__eq__(*other.release_pattern)) : false ) : (is_set(other.release_pattern) ? false : true ) ) && shape == other.shape && ( (is_set(region)) ? (is_set(other.region) ? (region->__eq__(*other.region)) : false ) : (is_set(other.region) ? false : true ) ) && true /*location*/ && site_diameter == other.site_diameter && site_radius == other.site_radius && number_to_release == other.number_to_release && density == other.density && concentration == other.concentration && release_probability == other.release_probability; } std::string GenReleaseSite::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "\n" << ind + " " << "complex=" << "(" << ((complex != nullptr) ? complex->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "molecule_list=" << vec_ptr_to_str(molecule_list, all_details, ind + " ") << ", " << "\n" << ind + " " << "release_time=" << release_time << ", " << "\n" << ind + " " << "release_pattern=" << "(" << ((release_pattern != nullptr) ? release_pattern->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "shape=" << shape << ", " << "\n" << ind + " " << "region=" << "(" << ((region != nullptr) ? region->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "location=" << vec_nonptr_to_str(location, all_details, ind + " ") << ", " << "site_diameter=" << site_diameter << ", " << "site_radius=" << site_radius << ", " << "number_to_release=" << number_to_release << ", " << "density=" << density << ", " << "concentration=" << concentration << ", " << "release_probability=" << release_probability; return ss.str(); } py::class_<ReleaseSite> define_pybinding_ReleaseSite(py::module& m) { return py::class_<ReleaseSite, std::shared_ptr<ReleaseSite>>(m, "ReleaseSite", "Defines a release site that specifies where, when and how should molecules be released. \n") .def( py::init< const std::string&, std::shared_ptr<Complex>, const std::vector<std::shared_ptr<MoleculeReleaseInfo>>, const double, std::shared_ptr<ReleasePattern>, const Shape, std::shared_ptr<Region>, const std::vector<double>, const double, const double, const double, const double, const double, const double >(), py::arg("name"), py::arg("complex") = nullptr, py::arg("molecule_list") = std::vector<std::shared_ptr<MoleculeReleaseInfo>>(), py::arg("release_time") = 0, py::arg("release_pattern") = nullptr, py::arg("shape") = Shape::UNSET, py::arg("region") = nullptr, py::arg("location") = std::vector<double>(), py::arg("site_diameter") = 0, py::arg("site_radius") = FLT_UNSET, py::arg("number_to_release") = FLT_UNSET, py::arg("density") = FLT_UNSET, py::arg("concentration") = FLT_UNSET, py::arg("release_probability") = 1 ) .def("check_semantics", &ReleaseSite::check_semantics) .def("__copy__", &ReleaseSite::copy_release_site) .def("__deepcopy__", &ReleaseSite::deepcopy_release_site, py::arg("memo")) .def("__str__", &ReleaseSite::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ReleaseSite::__eq__, py::arg("other")) .def("dump", &ReleaseSite::dump) .def_property("name", &ReleaseSite::get_name, &ReleaseSite::set_name, "Name of the release site") .def_property("complex", &ReleaseSite::get_complex, &ReleaseSite::set_complex, "Defines the species of the molecule that will be released. Not used for the LIST shape. \nMust be set when molecule_list is empty and unset when molecule_list is not empty.\nOrientation of the complex instance is used to define orientation of the released molecule,\nwhen Orientation.DEFAULT is set, volume molecules are released with Orientation.NONE and\nsurface molecules are released with Orientation.UP.\nWhen compartment is specified and region is not set, this sets shape to Shape.COMPARTMENT and \nthe molecules are released into the compartment.\nWhen this is a release of volume molecules, and both compartment and region are set, \nthis sets shape to Shape.REGION_EXPR and the target region is the intersection \nof the region and the compartment.\n") .def_property("molecule_list", &ReleaseSite::get_molecule_list, &ReleaseSite::set_molecule_list, py::return_value_policy::reference, "Used for LIST shape release mode. \nOnly one of number_to_release, density, concentration or molecule_list can be set.\n") .def_property("release_time", &ReleaseSite::get_release_time, &ReleaseSite::set_release_time, "Specifies time in seconds when the release event is executed.\nIn case when a release pattern is used, this is the time of the first release. \nEquivalent to MDL's RELEASE_PATTERN command DELAY.\n") .def_property("release_pattern", &ReleaseSite::get_release_pattern, &ReleaseSite::set_release_pattern, "Use the release pattern to define schedule of releases. \nThe default is to release the specified number of molecules at the set release_time. \n") .def_property("shape", &ReleaseSite::get_shape, &ReleaseSite::set_shape, "Defines how the molecules shoudl be released. \nSet automatically for these cases to the following values: \nregion is set - Shape.REGION_EXPR,\nregion is not set and complex uses a compartment - Shape.COMPARTMENT,\nmolecule_list is set - Shape.LIST,\nlocation is set - Shape.SPHERICAL.\n") .def_property("region", &ReleaseSite::get_region, &ReleaseSite::set_region, "Defines a volume or surface region where to release molecules. \nSetting it sets shape to Shape.REGION_EXPR. \nWhen this is a release of volume molecules, and both compartment and region are set, \nthis sets shape to Shape.REGION_EXPR and the target region is the intersection \nof the region and the compartment.\n \n") .def_property("location", &ReleaseSite::get_location, &ReleaseSite::set_location, py::return_value_policy::reference, "Defines center of a sphere where to release molecules. \nSetting it sets shape to Shape.SPHERICAL.\n") .def_property("site_diameter", &ReleaseSite::get_site_diameter, &ReleaseSite::set_site_diameter, "For a geometrical release site, this releases molecules uniformly within\na radius r computed as site_diameter/2. \nUsed only when shape is Shape.SPHERICAL.\nMaximum one of site_diameter or site_radius may be set.\n") .def_property("site_radius", &ReleaseSite::get_site_radius, &ReleaseSite::set_site_radius, "For a geometrical release site, this releases molecules uniformly within\na radius site_radius.\nUsed only when shape is Shape.SPHERICAL.\nMaximum one of site_diameter or site_radius may be set.\n") .def_property("number_to_release", &ReleaseSite::get_number_to_release, &ReleaseSite::set_number_to_release, "Sets number of molecules to release. Cannot be set when shape is Shape.LIST. \nOnly one of number_to_release, density, concentration or molecule_list can be set.\nValue is truncated (floored) to an integer.\n") .def_property("density", &ReleaseSite::get_density, &ReleaseSite::set_density, "Unit is molecules per square micron (for surfaces). \nOnly one of number_to_release, density, concentration or molecule_list can be set.\nCannot be set when shape is Shape.LIST.\n") .def_property("concentration", &ReleaseSite::get_concentration, &ReleaseSite::set_concentration, "Unit is molar (moles per liter) for volumes.\nOnly one of number_to_release, density, concentration or molecule_list can be set.\nCannot be set when shape is Shape.LIST.\n") .def_property("release_probability", &ReleaseSite::get_release_probability, &ReleaseSite::set_release_probability, "This release does not occur every time, but rather with probability p. \nEither the whole release occurs or none of it does; the probability does not \napply molecule-by-molecule. release_probability must be in the interval [0, 1].\n") ; } std::string GenReleaseSite::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("release_site") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("release_site"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ReleaseSite(" << nl; ss << ind << "name = " << "'" << name << "'" << "," << nl; if (is_set(complex)) { ss << ind << "complex = " << complex->export_to_python(out, ctx) << "," << nl; } if (molecule_list != std::vector<std::shared_ptr<MoleculeReleaseInfo>>() && !skip_vectors_export()) { ss << ind << "molecule_list = " << export_vec_molecule_list(out, ctx, exported_name) << "," << nl; } if (release_time != 0) { ss << ind << "release_time = " << f_to_str(release_time) << "," << nl; } if (is_set(release_pattern)) { ss << ind << "release_pattern = " << release_pattern->export_to_python(out, ctx) << "," << nl; } if (shape != Shape::UNSET) { ss << ind << "shape = " << shape << "," << nl; } if (is_set(region)) { ss << ind << "region = " << region->export_to_python(out, ctx) << "," << nl; } if (location != std::vector<double>() && !skip_vectors_export()) { ss << ind << "location = " << export_vec_location(out, ctx, exported_name) << "," << nl; } if (site_diameter != 0) { ss << ind << "site_diameter = " << f_to_str(site_diameter) << "," << nl; } if (site_radius != FLT_UNSET) { ss << ind << "site_radius = " << f_to_str(site_radius) << "," << nl; } if (number_to_release != FLT_UNSET) { ss << ind << "number_to_release = " << f_to_str(number_to_release) << "," << nl; } if (density != FLT_UNSET) { ss << ind << "density = " << f_to_str(density) << "," << nl; } if (concentration != FLT_UNSET) { ss << ind << "concentration = " << f_to_str(concentration) << "," << nl; } if (release_probability != 1) { ss << ind << "release_probability = " << f_to_str(release_probability) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenReleaseSite::export_vec_molecule_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < molecule_list.size(); i++) { const auto& item = molecule_list[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } std::string GenReleaseSite::export_vec_location(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < location.size(); i++) { const auto& item = location[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << f_to_str(item) << ", "; } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_vectors_bind.cpp
.cpp
7,658
140
/****************************************************************************** * * Copyright (C) 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 "api/pybind11_stl_include.h" #include "pybind11/include/pybind11/stl_bind.h" #include "pybind11/include/pybind11/numpy.h" namespace py = pybind11; #include "api/base_chkpt_mol.h" #include "api/complex.h" #include "api/component.h" #include "api/component_type.h" #include "api/count.h" #include "api/elementary_molecule.h" #include "api/elementary_molecule_type.h" #include "api/geometry_object.h" #include "api/initial_surface_release.h" #include "api/molecule_release_info.h" #include "api/reaction_rule.h" #include "api/release_site.h" #include "api/species.h" #include "api/surface_class.h" #include "api/surface_property.h" #include "api/surface_region.h" #include "api/viz_output.h" namespace MCell { namespace API { void gen_vectors_bind(py::module& m){ py::bind_vector<std::vector<std::shared_ptr<MCell::API::BaseChkptMol>>>(m,"VectorBaseChkptMol"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::BaseChkptMol>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::BaseChkptMol>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::Complex>>>(m,"VectorComplex"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::Complex>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::Complex>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::Component>>>(m,"VectorComponent"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::Component>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::Component>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::ComponentType>>>(m,"VectorComponentType"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::ComponentType>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::ComponentType>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::Count>>>(m,"VectorCount"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::Count>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::Count>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::ElementaryMolecule>>>(m,"VectorElementaryMolecule"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::ElementaryMolecule>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::ElementaryMolecule>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::ElementaryMoleculeType>>>(m,"VectorElementaryMoleculeType"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::ElementaryMoleculeType>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::ElementaryMoleculeType>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::GeometryObject>>>(m,"VectorGeometryObject"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::GeometryObject>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::GeometryObject>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::InitialSurfaceRelease>>>(m,"VectorInitialSurfaceRelease"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::InitialSurfaceRelease>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::InitialSurfaceRelease>>>(); py::bind_vector<std::vector<std::vector<double>>>(m,"VectorVectorFloat"); py::implicitly_convertible<py::list, std::vector<std::vector<double>>>(); py::implicitly_convertible<py::tuple, std::vector<std::vector<double>>>(); py::bind_vector<std::vector<std::vector<int>>>(m,"VectorVectorInt"); py::implicitly_convertible<py::list, std::vector<std::vector<int>>>(); py::implicitly_convertible<py::tuple, std::vector<std::vector<int>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::MoleculeReleaseInfo>>>(m,"VectorMoleculeReleaseInfo"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::MoleculeReleaseInfo>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::MoleculeReleaseInfo>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::ReactionRule>>>(m,"VectorReactionRule"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::ReactionRule>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::ReactionRule>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::ReleaseSite>>>(m,"VectorReleaseSite"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::ReleaseSite>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::ReleaseSite>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::Species>>>(m,"VectorSpecies"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::Species>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::Species>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::SurfaceClass>>>(m,"VectorSurfaceClass"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::SurfaceClass>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::SurfaceClass>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::SurfaceProperty>>>(m,"VectorSurfaceProperty"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::SurfaceProperty>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::SurfaceProperty>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::SurfaceRegion>>>(m,"VectorSurfaceRegion"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::SurfaceRegion>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::SurfaceRegion>>>(); py::bind_vector<std::vector<std::shared_ptr<MCell::API::VizOutput>>>(m,"VectorVizOutput"); py::implicitly_convertible<py::list, std::vector<std::shared_ptr<MCell::API::VizOutput>>>(); py::implicitly_convertible<py::tuple, std::vector<std::shared_ptr<MCell::API::VizOutput>>>(); py::bind_vector<std::vector<double>>(m,"VectorFloat"); py::implicitly_convertible<py::list, std::vector<double>>(); py::implicitly_convertible<py::tuple, std::vector<double>>(); py::implicitly_convertible<py::array_t<double>, std::vector<double>>(); py::bind_vector<std::vector<int>>(m,"VectorInt"); py::implicitly_convertible<py::list, std::vector<int>>(); py::implicitly_convertible<py::tuple, std::vector<int>>(); py::implicitly_convertible<py::array_t<int>, std::vector<int>>(); py::bind_vector<std::vector<std::string>>(m,"VectorStr"); py::implicitly_convertible<py::list, std::vector<std::string>>(); py::implicitly_convertible<py::tuple, std::vector<std::string>>(); py::bind_vector<std::vector<uint64_t>>(m,"VectorUint64"); py::implicitly_convertible<py::list, std::vector<uint64_t>>(); py::implicitly_convertible<py::tuple, std::vector<uint64_t>>(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_surface_class.cpp
.cpp
8,048
214
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_surface_class.h" #include "api/surface_class.h" #include "api/complex.h" #include "api/surface_property.h" namespace MCell { namespace API { void GenSurfaceClass::check_semantics() const { if (!is_set(name)) { throw ValueError("Parameter 'name' must be set."); } } void GenSurfaceClass::set_initialized() { vec_set_initialized(properties); if (is_set(affected_complex_pattern)) { affected_complex_pattern->set_initialized(); } initialized = true; } void GenSurfaceClass::set_all_attributes_as_default_or_unset() { class_name = "SurfaceClass"; name = STR_UNSET; properties = std::vector<std::shared_ptr<SurfaceProperty>>(); type = SurfacePropertyType::UNSET; affected_complex_pattern = nullptr; concentration = FLT_UNSET; } std::shared_ptr<SurfaceClass> GenSurfaceClass::copy_surface_class() const { std::shared_ptr<SurfaceClass> res = std::make_shared<SurfaceClass>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->properties = properties; res->type = type; res->affected_complex_pattern = affected_complex_pattern; res->concentration = concentration; return res; } std::shared_ptr<SurfaceClass> GenSurfaceClass::deepcopy_surface_class(py::dict) const { std::shared_ptr<SurfaceClass> res = std::make_shared<SurfaceClass>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; for (const auto& item: properties) { res->properties.push_back((is_set(item)) ? item->deepcopy_surface_property() : nullptr); } res->type = type; res->affected_complex_pattern = is_set(affected_complex_pattern) ? affected_complex_pattern->deepcopy_complex() : nullptr; res->concentration = concentration; return res; } bool GenSurfaceClass::__eq__(const SurfaceClass& other) const { return name == other.name && vec_ptr_eq(properties, other.properties) && type == other.type && ( (is_set(affected_complex_pattern)) ? (is_set(other.affected_complex_pattern) ? (affected_complex_pattern->__eq__(*other.affected_complex_pattern)) : false ) : (is_set(other.affected_complex_pattern) ? false : true ) ) && concentration == other.concentration; } bool GenSurfaceClass::eq_nonarray_attributes(const SurfaceClass& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*properties*/ && type == other.type && ( (is_set(affected_complex_pattern)) ? (is_set(other.affected_complex_pattern) ? (affected_complex_pattern->__eq__(*other.affected_complex_pattern)) : false ) : (is_set(other.affected_complex_pattern) ? false : true ) ) && concentration == other.concentration; } std::string GenSurfaceClass::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "\n" << ind + " " << "properties=" << vec_ptr_to_str(properties, all_details, ind + " ") << ", " << "\n" << ind + " " << "type=" << type << ", " << "\n" << ind + " " << "affected_complex_pattern=" << "(" << ((affected_complex_pattern != nullptr) ? affected_complex_pattern->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "concentration=" << concentration; return ss.str(); } py::class_<SurfaceClass> define_pybinding_SurfaceClass(py::module& m) { return py::class_<SurfaceClass, SurfaceProperty, std::shared_ptr<SurfaceClass>>(m, "SurfaceClass", "Defining a surface class allows surfaces to behave like species. For instance, one may wish \nto specify that a surface does not block the diffusion of molecules. Each type of surface is defined\nby name, and each surface name must be unique in the simulation and should not match any molecule names.\nTo define a reaction with a surface class, use constructor call m.Complex(name) as one of the reactants.\n") .def( py::init< const std::string&, const std::vector<std::shared_ptr<SurfaceProperty>>, const SurfacePropertyType, std::shared_ptr<Complex>, const double >(), py::arg("name"), py::arg("properties") = std::vector<std::shared_ptr<SurfaceProperty>>(), py::arg("type") = SurfacePropertyType::UNSET, py::arg("affected_complex_pattern") = nullptr, py::arg("concentration") = FLT_UNSET ) .def("check_semantics", &SurfaceClass::check_semantics) .def("__copy__", &SurfaceClass::copy_surface_class) .def("__deepcopy__", &SurfaceClass::deepcopy_surface_class, py::arg("memo")) .def("__str__", &SurfaceClass::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &SurfaceClass::__eq__, py::arg("other")) .def("dump", &SurfaceClass::dump) .def_property("name", &SurfaceClass::get_name, &SurfaceClass::set_name, "Name of the surface class.") .def_property("properties", &SurfaceClass::get_properties, &SurfaceClass::set_properties, py::return_value_policy::reference, "A surface class can either have a list of properties or just one property.\nIn the usual case of having one property, one can set the attributes \ntype, affected_species, etc. inherited from SurfaceProperty directly.\n") ; } std::string GenSurfaceClass::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("surface_class") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("surface_class"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.SurfaceClass(" << nl; if (type != SurfacePropertyType::UNSET) { ss << ind << "type = " << type << "," << nl; } if (is_set(affected_complex_pattern)) { ss << ind << "affected_complex_pattern = " << affected_complex_pattern->export_to_python(out, ctx) << "," << nl; } if (concentration != FLT_UNSET) { ss << ind << "concentration = " << f_to_str(concentration) << "," << nl; } ss << ind << "name = " << "'" << name << "'" << "," << nl; if (properties != std::vector<std::shared_ptr<SurfaceProperty>>() && !skip_vectors_export()) { ss << ind << "properties = " << export_vec_properties(out, ctx, exported_name) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenSurfaceClass::export_vec_properties(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < properties.size(); i++) { const auto& item = properties[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_warnings.cpp
.cpp
4,852
131
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_warnings.h" #include "api/warnings.h" namespace MCell { namespace API { void GenWarnings::check_semantics() const { } void GenWarnings::set_initialized() { initialized = true; } void GenWarnings::set_all_attributes_as_default_or_unset() { class_name = "Warnings"; high_reaction_probability = WarningLevel::IGNORE; molecule_placement_failure = WarningLevel::ERROR; } std::shared_ptr<Warnings> GenWarnings::copy_warnings() const { std::shared_ptr<Warnings> res = std::make_shared<Warnings>(DefaultCtorArgType()); res->class_name = class_name; res->high_reaction_probability = high_reaction_probability; res->molecule_placement_failure = molecule_placement_failure; return res; } std::shared_ptr<Warnings> GenWarnings::deepcopy_warnings(py::dict) const { std::shared_ptr<Warnings> res = std::make_shared<Warnings>(DefaultCtorArgType()); res->class_name = class_name; res->high_reaction_probability = high_reaction_probability; res->molecule_placement_failure = molecule_placement_failure; return res; } bool GenWarnings::__eq__(const Warnings& other) const { return high_reaction_probability == other.high_reaction_probability && molecule_placement_failure == other.molecule_placement_failure; } bool GenWarnings::eq_nonarray_attributes(const Warnings& other, const bool ignore_name) const { return high_reaction_probability == other.high_reaction_probability && molecule_placement_failure == other.molecule_placement_failure; } std::string GenWarnings::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "high_reaction_probability=" << high_reaction_probability << ", " << "molecule_placement_failure=" << molecule_placement_failure; return ss.str(); } py::class_<Warnings> define_pybinding_Warnings(py::module& m) { return py::class_<Warnings, std::shared_ptr<Warnings>>(m, "Warnings", "This class contains warnings settings. For now it contains only one configurable \nwarning.\n") .def( py::init< const WarningLevel, const WarningLevel >(), py::arg("high_reaction_probability") = WarningLevel::IGNORE, py::arg("molecule_placement_failure") = WarningLevel::ERROR ) .def("check_semantics", &Warnings::check_semantics) .def("__copy__", &Warnings::copy_warnings) .def("__deepcopy__", &Warnings::deepcopy_warnings, py::arg("memo")) .def("__str__", &Warnings::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Warnings::__eq__, py::arg("other")) .def("dump", &Warnings::dump) .def_property("high_reaction_probability", &Warnings::get_high_reaction_probability, &Warnings::set_high_reaction_probability, "Print a warning when a bimolecular reaction probability is over 0.5 but less or equal than 1.\nWarning when probability is greater than 1 is always printed.\nCannot be set to WarningLevel.ERROR.\n") .def_property("molecule_placement_failure", &Warnings::get_molecule_placement_failure, &Warnings::set_molecule_placement_failure, "Print a warning or end with an error when a release of a molecule fails.\n") ; } std::string GenWarnings::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "warnings_" + std::to_string(ctx.postinc_counter("warnings")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Warnings(" << nl; if (high_reaction_probability != WarningLevel::IGNORE) { ss << ind << "high_reaction_probability = " << high_reaction_probability << "," << nl; } if (molecule_placement_failure != WarningLevel::ERROR) { ss << ind << "molecule_placement_failure = " << molecule_placement_failure << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_mol_wall_hit_info.cpp
.cpp
5,381
127
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_mol_wall_hit_info.h" #include "api/mol_wall_hit_info.h" #include "api/geometry_object.h" namespace MCell { namespace API { std::shared_ptr<MolWallHitInfo> GenMolWallHitInfo::copy_mol_wall_hit_info() const { std::shared_ptr<MolWallHitInfo> res = std::make_shared<MolWallHitInfo>(DefaultCtorArgType()); res->molecule_id = molecule_id; res->geometry_object = geometry_object; res->wall_index = wall_index; res->time = time; res->pos3d = pos3d; res->time_before_hit = time_before_hit; res->pos3d_before_hit = pos3d_before_hit; return res; } std::shared_ptr<MolWallHitInfo> GenMolWallHitInfo::deepcopy_mol_wall_hit_info(py::dict) const { std::shared_ptr<MolWallHitInfo> res = std::make_shared<MolWallHitInfo>(DefaultCtorArgType()); res->molecule_id = molecule_id; res->geometry_object = is_set(geometry_object) ? geometry_object->deepcopy_geometry_object() : nullptr; res->wall_index = wall_index; res->time = time; res->pos3d = pos3d; res->time_before_hit = time_before_hit; res->pos3d_before_hit = pos3d_before_hit; return res; } bool GenMolWallHitInfo::__eq__(const MolWallHitInfo& other) const { return molecule_id == other.molecule_id && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && time == other.time && pos3d == other.pos3d && time_before_hit == other.time_before_hit && pos3d_before_hit == other.pos3d_before_hit; } bool GenMolWallHitInfo::eq_nonarray_attributes(const MolWallHitInfo& other, const bool ignore_name) const { return molecule_id == other.molecule_id && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && time == other.time && true /*pos3d*/ && time_before_hit == other.time_before_hit && true /*pos3d_before_hit*/; } std::string GenMolWallHitInfo::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "MolWallHitInfo" << ": " << "molecule_id=" << molecule_id << ", " << "\n" << ind + " " << "geometry_object=" << "(" << ((geometry_object != nullptr) ? geometry_object->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall_index=" << wall_index << ", " << "time=" << time << ", " << "pos3d=" << vec_nonptr_to_str(pos3d, all_details, ind + " ") << ", " << "time_before_hit=" << time_before_hit << ", " << "pos3d_before_hit=" << vec_nonptr_to_str(pos3d_before_hit, all_details, ind + " "); return ss.str(); } py::class_<MolWallHitInfo> define_pybinding_MolWallHitInfo(py::module& m) { return py::class_<MolWallHitInfo, std::shared_ptr<MolWallHitInfo>>(m, "MolWallHitInfo", "Data structure passed to a callback function registered through\nModel.register_mol_wall_hit_callback.\n \n") .def( py::init< >() ) .def("__copy__", &MolWallHitInfo::copy_mol_wall_hit_info) .def("__deepcopy__", &MolWallHitInfo::deepcopy_mol_wall_hit_info, py::arg("memo")) .def("__str__", &MolWallHitInfo::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &MolWallHitInfo::__eq__, py::arg("other")) .def("dump", &MolWallHitInfo::dump) .def_property("molecule_id", &MolWallHitInfo::get_molecule_id, &MolWallHitInfo::set_molecule_id, "Id of molecule that hit the wall.") .def_property("geometry_object", &MolWallHitInfo::get_geometry_object, &MolWallHitInfo::set_geometry_object, "Object that was hit.") .def_property("wall_index", &MolWallHitInfo::get_wall_index, &MolWallHitInfo::set_wall_index, "Index of the wall belonging to the geometry_object.") .def_property("time", &MolWallHitInfo::get_time, &MolWallHitInfo::set_time, "Time of the hit.") .def_property("pos3d", &MolWallHitInfo::get_pos3d, &MolWallHitInfo::set_pos3d, py::return_value_policy::reference, "Position of the hit.") .def_property("time_before_hit", &MolWallHitInfo::get_time_before_hit, &MolWallHitInfo::set_time_before_hit, "The time when the molecule started to diffuse towards the hit wall. \nIt is either the start of the molecule's diffusion or \nwhen the molecule reflected from another wall.\n \n") .def_property("pos3d_before_hit", &MolWallHitInfo::get_pos3d_before_hit, &MolWallHitInfo::set_pos3d_before_hit, py::return_value_policy::reference, "Position of the molecule at time_before_hit.") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_color.cpp
.cpp
5,431
167
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_color.h" #include "api/color.h" namespace MCell { namespace API { void GenColor::check_semantics() const { } void GenColor::set_initialized() { initialized = true; } void GenColor::set_all_attributes_as_default_or_unset() { class_name = "Color"; red = FLT_UNSET; green = FLT_UNSET; blue = FLT_UNSET; alpha = 1; rgba = 0; } std::shared_ptr<Color> GenColor::copy_color() const { std::shared_ptr<Color> res = std::make_shared<Color>(DefaultCtorArgType()); res->class_name = class_name; res->red = red; res->green = green; res->blue = blue; res->alpha = alpha; res->rgba = rgba; return res; } std::shared_ptr<Color> GenColor::deepcopy_color(py::dict) const { std::shared_ptr<Color> res = std::make_shared<Color>(DefaultCtorArgType()); res->class_name = class_name; res->red = red; res->green = green; res->blue = blue; res->alpha = alpha; res->rgba = rgba; return res; } bool GenColor::__eq__(const Color& other) const { return red == other.red && green == other.green && blue == other.blue && alpha == other.alpha && rgba == other.rgba; } bool GenColor::eq_nonarray_attributes(const Color& other, const bool ignore_name) const { return red == other.red && green == other.green && blue == other.blue && alpha == other.alpha && rgba == other.rgba; } std::string GenColor::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "red=" << red << ", " << "green=" << green << ", " << "blue=" << blue << ", " << "alpha=" << alpha << ", " << "rgba=" << rgba; return ss.str(); } py::class_<Color> define_pybinding_Color(py::module& m) { return py::class_<Color, std::shared_ptr<Color>>(m, "Color", "Represents color with alpha component.\nProvides two means to set value, either red, green, blue and alpha, \nor rgba. If both color individual components and rgba are set in initialization,\nthe individual components are used.\n \n") .def( py::init< const double, const double, const double, const double, const uint >(), py::arg("red") = FLT_UNSET, py::arg("green") = FLT_UNSET, py::arg("blue") = FLT_UNSET, py::arg("alpha") = 1, py::arg("rgba") = 0 ) .def("check_semantics", &Color::check_semantics) .def("__copy__", &Color::copy_color) .def("__deepcopy__", &Color::deepcopy_color, py::arg("memo")) .def("__str__", &Color::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Color::__eq__, py::arg("other")) .def("dump", &Color::dump) .def_property("red", &Color::get_red, &Color::set_red, "Red component in range 0-1.") .def_property("green", &Color::get_green, &Color::set_green, "Green component in range 0-1.") .def_property("blue", &Color::get_blue, &Color::set_blue, "Blue component in range 0-1.") .def_property("alpha", &Color::get_alpha, &Color::set_alpha, "Alpha component in range 0-1. 1 means nontransparent.") .def_property("rgba", &Color::get_rgba, &Color::set_rgba, "This attribute provides an alternative way of defining colors by supplying a \n32-bit unsigned integer representation of the color with an aplha channel. \nIn hexadecimal notation the first 2 digits are value for red, second 2 digits are \ngreen, third 2 digits are blue and the last two digits are alpha. \nThe range for each component is thus 0x0-0xFF (0-255). \nExample: 0x0000ffcc represents the same color as rgba(0, 0, 100%, 80%).\nAll values are valid.\n \n") ; } std::string GenColor::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "color_" + std::to_string(ctx.postinc_counter("color")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Color(" << nl; if (red != FLT_UNSET) { ss << ind << "red = " << f_to_str(red) << "," << nl; } if (green != FLT_UNSET) { ss << ind << "green = " << f_to_str(green) << "," << nl; } if (blue != FLT_UNSET) { ss << ind << "blue = " << f_to_str(blue) << "," << nl; } if (alpha != 1) { ss << ind << "alpha = " << f_to_str(alpha) << "," << nl; } if (rgba != 0) { ss << ind << "rgba = " << rgba << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_count.cpp
.cpp
9,749
204
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_count.h" #include "api/count.h" #include "api/count_term.h" namespace MCell { namespace API { void GenCount::check_semantics() const { } void GenCount::set_initialized() { if (is_set(expression)) { expression->set_initialized(); } initialized = true; } void GenCount::set_all_attributes_as_default_or_unset() { class_name = "Count"; name = STR_UNSET; file_name = STR_UNSET; expression = nullptr; multiplier = 1; every_n_timesteps = 1; output_format = CountOutputFormat::AUTOMATIC_FROM_EXTENSION; } std::shared_ptr<Count> GenCount::copy_count() const { std::shared_ptr<Count> res = std::make_shared<Count>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->file_name = file_name; res->expression = expression; res->multiplier = multiplier; res->every_n_timesteps = every_n_timesteps; res->output_format = output_format; return res; } std::shared_ptr<Count> GenCount::deepcopy_count(py::dict) const { std::shared_ptr<Count> res = std::make_shared<Count>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->file_name = file_name; res->expression = is_set(expression) ? expression->deepcopy_count_term() : nullptr; res->multiplier = multiplier; res->every_n_timesteps = every_n_timesteps; res->output_format = output_format; return res; } bool GenCount::__eq__(const Count& other) const { return name == other.name && file_name == other.file_name && ( (is_set(expression)) ? (is_set(other.expression) ? (expression->__eq__(*other.expression)) : false ) : (is_set(other.expression) ? false : true ) ) && multiplier == other.multiplier && every_n_timesteps == other.every_n_timesteps && output_format == other.output_format; } bool GenCount::eq_nonarray_attributes(const Count& other, const bool ignore_name) const { return (ignore_name || name == other.name) && file_name == other.file_name && ( (is_set(expression)) ? (is_set(other.expression) ? (expression->__eq__(*other.expression)) : false ) : (is_set(other.expression) ? false : true ) ) && multiplier == other.multiplier && every_n_timesteps == other.every_n_timesteps && output_format == other.output_format; } std::string GenCount::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "file_name=" << file_name << ", " << "\n" << ind + " " << "expression=" << "(" << ((expression != nullptr) ? expression->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "multiplier=" << multiplier << ", " << "every_n_timesteps=" << every_n_timesteps << ", " << "output_format=" << output_format; return ss.str(); } py::class_<Count> define_pybinding_Count(py::module& m) { return py::class_<Count, std::shared_ptr<Count>>(m, "Count", "Represents a molecule or reaction count observable.\nWhat is counted is defined through a CounTerm tree and a reference to \nthe root of this tree is stored into attribute expression. \nThis tree usually contains just one node. \n \n") .def( py::init< const std::string&, const std::string&, std::shared_ptr<CountTerm>, const double, const double, const CountOutputFormat >(), py::arg("name") = STR_UNSET, py::arg("file_name") = STR_UNSET, py::arg("expression") = nullptr, py::arg("multiplier") = 1, py::arg("every_n_timesteps") = 1, py::arg("output_format") = CountOutputFormat::AUTOMATIC_FROM_EXTENSION ) .def("check_semantics", &Count::check_semantics) .def("__copy__", &Count::copy_count) .def("__deepcopy__", &Count::deepcopy_count, py::arg("memo")) .def("__str__", &Count::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Count::__eq__, py::arg("other")) .def("get_current_value", &Count::get_current_value, "Returns the current value for this count. Can be used to count both molecules and reactions.\nReaction counting starts at the beginning of the simulation.\nThe model must be initialized with this Count present as one of the observables.\n") .def("dump", &Count::dump) .def_property("name", &Count::get_name, &Count::set_name, "Name of a count may be specified when one needs to search for them later. \nWhen the count is created when a BNGL file is loaded, its name is set, for instance\nwhen the following BNGL code is loaded:\n\nbegin observables\n Molecules Acount A\nend observables\n\nthe name is set to Acount.\n") .def_property("file_name", &Count::get_file_name, &Count::set_file_name, "File name where this observable values will be stored.\nFile extension or setting explicit output_format determines the output format.\nA) When not set, the value is set using seed during model initialization as follows: \nfile_name = './react_data/seed_' + str(model.config.seed).zfill(5) + '/' + name + '.dat'\nand the output format is set to CountOutputFormat.DAT in the constructor.\nB) When the file_name is set explicitly by the user and the extension is .dat such as here:\nfile_name = './react_data/seed_' + str(SEED).zfill(5) + '/' + name + '.dat'\nand the output format is set to CountOutputFormat.DAT in the constructor.\nFile names for individual Counts must be different.\nC) When the file_name is set explicitly by the user and the extension is .gdat such as here:\nfile_name = './react_data/seed_' + str(SEED).zfill(5) + '/counts.gdat'\nand the output format is set to CountOutputFormat.GDAT in the constructor.\nThe file name is usually the same for all counts but one can \ncreate multiple gdat files with different observables.\nAll observables that are stored into a single .gdat file must have the same \nperiodicity specified by attribute every_n_timesteps.\nMust be set.\n") .def_property("expression", &Count::get_expression, &Count::set_expression, "The expression must be set to a root of an expression tree composed of CountTerms. \nIn the usual cases, there is just one CountTerm in this expression tree and its \nnode_type is ExprNodeType.LEAF.\nThe count expression tree defines CountTerm objects that are added or subtracted\nfrom each other.\n") .def_property("multiplier", &Count::get_multiplier, &Count::set_multiplier, "In some cases it might be useful to multiply the whole count by a constant to get \nfor instance concentration. The expression tree allows only addition and subtraction \nof count terms so such multiplication can be done through this attribute.\nIt can be also used to divide the resulting count by passing an inverse of the divisor (1/d). \n") .def_property("every_n_timesteps", &Count::get_every_n_timesteps, &Count::set_every_n_timesteps, "Specifies periodicity of this count's output.\nValue is truncated (floored) to an integer.\nIf value is set to 0, this Count is used only on-demand through calls to its\nget_current_value method. \n") .def_property("output_format", &Count::get_output_format, &Count::set_output_format, "Listed as the last attribute because the automatic default value\nis sufficient in most cases. \nSelection of output format. Default setting uses file extension \nfrom attribute file_name. \nWhen set to CountOutputFormat.AUTOMATIC_FROM_EXTENSION, \nthis output_format is set automatically only in the Count's constructor. \n") ; } std::string GenCount::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("count") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("count"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Count(" << nl; if (name != STR_UNSET) { ss << ind << "name = " << "'" << name << "'" << "," << nl; } if (file_name != STR_UNSET) { ss << ind << "file_name = " << "'" << file_name << "'" << "," << nl; } if (is_set(expression)) { ss << ind << "expression = " << expression->export_to_python(out, ctx) << "," << nl; } if (multiplier != 1) { ss << ind << "multiplier = " << f_to_str(multiplier) << "," << nl; } if (every_n_timesteps != 1) { ss << ind << "every_n_timesteps = " << f_to_str(every_n_timesteps) << "," << nl; } if (output_format != CountOutputFormat::AUTOMATIC_FROM_EXTENSION) { ss << ind << "output_format = " << output_format << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_component_type.h
.h
3,286
92
/****************************************************************************** * * Copyright (C) 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 API_GEN_COMPONENT_TYPE_H #define API_GEN_COMPONENT_TYPE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ComponentType; class Component; class PythonExportContext; #define COMPONENT_TYPE_CTOR() \ ComponentType( \ const std::string& name_, \ const std::vector<std::string> states_ = std::vector<std::string>() \ ) { \ class_name = "ComponentType"; \ name = name_; \ states = states_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ComponentType(DefaultCtorArgType) : \ GenComponentType(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenComponentType: public BaseDataClass { public: GenComponentType() { } GenComponentType(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ComponentType> copy_component_type() const; std::shared_ptr<ComponentType> deepcopy_component_type(py::dict = py::dict()) const; virtual bool __eq__(const ComponentType& other) const; virtual bool eq_nonarray_attributes(const ComponentType& other, const bool ignore_name = false) const; bool operator == (const ComponentType& other) const { return __eq__(other);} bool operator != (const ComponentType& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_states(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::string> states; virtual void set_states(const std::vector<std::string> new_states_) { if (initialized) { throw RuntimeError("Value 'states' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; states = new_states_; } virtual std::vector<std::string>& get_states() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return states; } // --- methods --- virtual std::shared_ptr<Component> inst(const std::string& state = "STATE_UNSET", const int bond = BOND_UNBOUND) = 0; virtual std::shared_ptr<Component> inst(const int state = STATE_UNSET_INT, const int bond = BOND_UNBOUND) = 0; virtual std::string to_bngl_str() const = 0; }; // GenComponentType class ComponentType; py::class_<ComponentType> define_pybinding_ComponentType(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COMPONENT_TYPE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_geometry_utils.h
.h
1,179
37
/****************************************************************************** * * Copyright (C) 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 API_GEN_GEOMETRY_UTILS_H #define API_GEN_GEOMETRY_UTILS_H #include "api/api_common.h" namespace MCell { namespace API { class GeometryObject; class Model; class PythonExportContext; namespace geometry_utils { std::shared_ptr<GeometryObject> create_box(const std::string& name, const double edge_dimension = FLT_UNSET, const std::vector<double> xyz_dimensions = std::vector<double>()); std::shared_ptr<GeometryObject> create_icosphere(const std::string& name, const double radius, const int subdivisions); void validate_volumetric_mesh(std::shared_ptr<Model> model, std::shared_ptr<GeometryObject> geometry_object); } // namespace geometry_utils void define_pybinding_geometry_utils(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_GEOMETRY_UTILS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_elementary_molecule_type.h
.h
7,126
173
/****************************************************************************** * * Copyright (C) 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 API_GEN_ELEMENTARY_MOLECULE_TYPE_H #define API_GEN_ELEMENTARY_MOLECULE_TYPE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ElementaryMoleculeType; class Component; class ComponentType; class ElementaryMolecule; class PythonExportContext; #define ELEMENTARY_MOLECULE_TYPE_CTOR() \ ElementaryMoleculeType( \ const std::string& name_, \ const std::vector<std::shared_ptr<ComponentType>> components_ = std::vector<std::shared_ptr<ComponentType>>(), \ const double diffusion_constant_2d_ = FLT_UNSET, \ const double diffusion_constant_3d_ = FLT_UNSET, \ const double custom_time_step_ = FLT_UNSET, \ const double custom_space_step_ = FLT_UNSET, \ const bool target_only_ = false \ ) { \ class_name = "ElementaryMoleculeType"; \ name = name_; \ components = components_; \ diffusion_constant_2d = diffusion_constant_2d_; \ diffusion_constant_3d = diffusion_constant_3d_; \ custom_time_step = custom_time_step_; \ custom_space_step = custom_space_step_; \ target_only = target_only_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ElementaryMoleculeType(DefaultCtorArgType) : \ GenElementaryMoleculeType(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenElementaryMoleculeType: public BaseDataClass { public: GenElementaryMoleculeType() { } GenElementaryMoleculeType(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ElementaryMoleculeType> copy_elementary_molecule_type() const; std::shared_ptr<ElementaryMoleculeType> deepcopy_elementary_molecule_type(py::dict = py::dict()) const; virtual bool __eq__(const ElementaryMoleculeType& other) const; virtual bool eq_nonarray_attributes(const ElementaryMoleculeType& other, const bool ignore_name = false) const; bool operator == (const ElementaryMoleculeType& other) const { return __eq__(other);} bool operator != (const ElementaryMoleculeType& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_components(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<ComponentType>> components; virtual void set_components(const std::vector<std::shared_ptr<ComponentType>> new_components_) { if (initialized) { throw RuntimeError("Value 'components' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; components = new_components_; } virtual std::vector<std::shared_ptr<ComponentType>>& get_components() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return components; } double diffusion_constant_2d; virtual void set_diffusion_constant_2d(const double new_diffusion_constant_2d_) { if (initialized) { throw RuntimeError("Value 'diffusion_constant_2d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; diffusion_constant_2d = new_diffusion_constant_2d_; } virtual double get_diffusion_constant_2d() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return diffusion_constant_2d; } double diffusion_constant_3d; virtual void set_diffusion_constant_3d(const double new_diffusion_constant_3d_) { if (initialized) { throw RuntimeError("Value 'diffusion_constant_3d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; diffusion_constant_3d = new_diffusion_constant_3d_; } virtual double get_diffusion_constant_3d() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return diffusion_constant_3d; } double custom_time_step; virtual void set_custom_time_step(const double new_custom_time_step_) { if (initialized) { throw RuntimeError("Value 'custom_time_step' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; custom_time_step = new_custom_time_step_; } virtual double get_custom_time_step() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return custom_time_step; } double custom_space_step; virtual void set_custom_space_step(const double new_custom_space_step_) { if (initialized) { throw RuntimeError("Value 'custom_space_step' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; custom_space_step = new_custom_space_step_; } virtual double get_custom_space_step() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return custom_space_step; } bool target_only; virtual void set_target_only(const bool new_target_only_) { if (initialized) { throw RuntimeError("Value 'target_only' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; target_only = new_target_only_; } virtual bool get_target_only() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return target_only; } // --- methods --- virtual std::shared_ptr<ElementaryMolecule> inst(const std::vector<std::shared_ptr<Component>> components = std::vector<std::shared_ptr<Component>>(), const std::string& compartment_name = STR_UNSET) = 0; virtual std::string to_bngl_str() const = 0; }; // GenElementaryMoleculeType class ElementaryMoleculeType; py::class_<ElementaryMoleculeType> define_pybinding_ElementaryMoleculeType(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_ELEMENTARY_MOLECULE_TYPE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_observables.h
.h
3,326
87
/****************************************************************************** * * Copyright (C) 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 API_GEN_OBSERVABLES_H #define API_GEN_OBSERVABLES_H #include "api/api_common.h" #include "api/base_export_class.h" namespace MCell { namespace API { class Observables; class Count; class VizOutput; class PythonExportContext; #define OBSERVABLES_CTOR() \ Observables( \ const std::vector<std::shared_ptr<VizOutput>> viz_outputs_ = std::vector<std::shared_ptr<VizOutput>>(), \ const std::vector<std::shared_ptr<Count>> counts_ = std::vector<std::shared_ptr<Count>>() \ ) { \ viz_outputs = viz_outputs_; \ counts = counts_; \ } \ Observables(DefaultCtorArgType){ \ } class GenObservables: public BaseExportClass { public: GenObservables() { } GenObservables(DefaultCtorArgType) { } virtual ~GenObservables() {} std::shared_ptr<Observables> copy_observables() const; std::shared_ptr<Observables> deepcopy_observables(py::dict = py::dict()) const; virtual bool __eq__(const Observables& other) const; virtual bool eq_nonarray_attributes(const Observables& other, const bool ignore_name = false) const; bool operator == (const Observables& other) const { return __eq__(other);} bool operator != (const Observables& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_viz_outputs(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_counts(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<VizOutput>> viz_outputs; virtual void set_viz_outputs(const std::vector<std::shared_ptr<VizOutput>> new_viz_outputs_) { viz_outputs = new_viz_outputs_; } virtual std::vector<std::shared_ptr<VizOutput>>& get_viz_outputs() { return viz_outputs; } std::vector<std::shared_ptr<Count>> counts; virtual void set_counts(const std::vector<std::shared_ptr<Count>> new_counts_) { counts = new_counts_; } virtual std::vector<std::shared_ptr<Count>>& get_counts() { return counts; } // --- methods --- virtual void add_viz_output(std::shared_ptr<VizOutput> viz_output) = 0; virtual void add_count(std::shared_ptr<Count> count) = 0; virtual std::shared_ptr<Count> find_count(const std::string& name) = 0; virtual void load_bngl_observables(const std::string& file_name, const std::string& observables_path_or_file = STR_UNSET, const std::map<std::string, double>& parameter_overrides = std::map<std::string, double>(), const CountOutputFormat observables_output_format = CountOutputFormat::AUTOMATIC_FROM_EXTENSION) = 0; }; // GenObservables class Observables; py::class_<Observables> define_pybinding_Observables(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_OBSERVABLES_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_wall.h
.h
5,454
157
/****************************************************************************** * * Copyright (C) 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 API_GEN_WALL_H #define API_GEN_WALL_H #include "api/api_common.h" #include "api/base_introspection_class.h" namespace MCell { namespace API { class Wall; class GeometryObject; class PythonExportContext; #define WALL_CTOR_NOARGS() \ Wall( \ ) { \ class_name = "Wall"; \ geometry_object = nullptr; \ wall_index = INT_UNSET; \ vertices = std::vector<std::vector<double>>(); \ area = FLT_UNSET; \ unit_normal = std::vector<double>(); \ is_movable = true; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Wall(DefaultCtorArgType) : \ GenWall(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenWall: public BaseIntrospectionClass { public: GenWall() { } GenWall(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Wall> copy_wall() const; std::shared_ptr<Wall> deepcopy_wall(py::dict = py::dict()) const; virtual bool __eq__(const Wall& other) const; virtual bool eq_nonarray_attributes(const Wall& other, const bool ignore_name = false) const; bool operator == (const Wall& other) const { return __eq__(other);} bool operator != (const Wall& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; // --- attributes --- std::shared_ptr<GeometryObject> geometry_object; virtual void set_geometry_object(std::shared_ptr<GeometryObject> new_geometry_object_) { if (initialized) { throw RuntimeError("Value 'geometry_object' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; geometry_object = new_geometry_object_; } virtual std::shared_ptr<GeometryObject> get_geometry_object() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return geometry_object; } int wall_index; virtual void set_wall_index(const int new_wall_index_) { if (initialized) { throw RuntimeError("Value 'wall_index' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_index = new_wall_index_; } virtual int get_wall_index() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_index; } std::vector<std::vector<double>> vertices; virtual void set_vertices(const std::vector<std::vector<double>> new_vertices_) { if (initialized) { throw RuntimeError("Value 'vertices' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; vertices = new_vertices_; } virtual std::vector<std::vector<double>>& get_vertices() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return vertices; } double area; virtual void set_area(const double new_area_) { if (initialized) { throw RuntimeError("Value 'area' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; area = new_area_; } virtual double get_area() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return area; } std::vector<double> unit_normal; virtual void set_unit_normal(const std::vector<double> new_unit_normal_) { if (initialized) { throw RuntimeError("Value 'unit_normal' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; unit_normal = new_unit_normal_; } virtual std::vector<double>& get_unit_normal() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return unit_normal; } bool is_movable; virtual void set_is_movable(const bool new_is_movable_) { if (initialized) { throw RuntimeError("Value 'is_movable' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; is_movable = new_is_movable_; } virtual bool get_is_movable() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return is_movable; } // --- methods --- }; // GenWall class Wall; py::class_<Wall> define_pybinding_Wall(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_WALL_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_initial_surface_release.h
.h
4,261
118
/****************************************************************************** * * Copyright (C) 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 API_GEN_INITIAL_SURFACE_RELEASE_H #define API_GEN_INITIAL_SURFACE_RELEASE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class InitialSurfaceRelease; class Complex; class PythonExportContext; #define INITIAL_SURFACE_RELEASE_CTOR() \ InitialSurfaceRelease( \ std::shared_ptr<Complex> complex_, \ const int number_to_release_ = INT_UNSET, \ const double density_ = FLT_UNSET \ ) { \ class_name = "InitialSurfaceRelease"; \ complex = complex_; \ number_to_release = number_to_release_; \ density = density_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ InitialSurfaceRelease(DefaultCtorArgType) : \ GenInitialSurfaceRelease(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenInitialSurfaceRelease: public BaseDataClass { public: GenInitialSurfaceRelease() { } GenInitialSurfaceRelease(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<InitialSurfaceRelease> copy_initial_surface_release() const; std::shared_ptr<InitialSurfaceRelease> deepcopy_initial_surface_release(py::dict = py::dict()) const; virtual bool __eq__(const InitialSurfaceRelease& other) const; virtual bool eq_nonarray_attributes(const InitialSurfaceRelease& other, const bool ignore_name = false) const; bool operator == (const InitialSurfaceRelease& other) const { return __eq__(other);} bool operator != (const InitialSurfaceRelease& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- std::shared_ptr<Complex> complex; virtual void set_complex(std::shared_ptr<Complex> new_complex_) { if (initialized) { throw RuntimeError("Value 'complex' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; complex = new_complex_; } virtual std::shared_ptr<Complex> get_complex() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return complex; } int number_to_release; virtual void set_number_to_release(const int new_number_to_release_) { if (initialized) { throw RuntimeError("Value 'number_to_release' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; number_to_release = new_number_to_release_; } virtual int get_number_to_release() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return number_to_release; } double density; virtual void set_density(const double new_density_) { if (initialized) { throw RuntimeError("Value 'density' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; density = new_density_; } virtual double get_density() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return density; } // --- methods --- }; // GenInitialSurfaceRelease class InitialSurfaceRelease; py::class_<InitialSurfaceRelease> define_pybinding_InitialSurfaceRelease(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_INITIAL_SURFACE_RELEASE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_geometry_object.cpp
.cpp
17,578
441
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_geometry_object.h" #include "api/geometry_object.h" #include "api/color.h" #include "api/initial_surface_release.h" #include "api/region.h" #include "api/surface_class.h" #include "api/surface_region.h" namespace MCell { namespace API { void GenGeometryObject::check_semantics() const { if (!is_set(name)) { throw ValueError("Parameter 'name' must be set."); } if (!is_set(vertex_list)) { throw ValueError("Parameter 'vertex_list' must be set and the value must not be an empty list."); } if (!is_set(wall_list)) { throw ValueError("Parameter 'wall_list' must be set and the value must not be an empty list."); } } void GenGeometryObject::set_initialized() { vec_set_initialized(surface_regions); if (is_set(surface_class)) { surface_class->set_initialized(); } vec_set_initialized(initial_surface_releases); if (is_set(initial_color)) { initial_color->set_initialized(); } if (is_set(left_node)) { left_node->set_initialized(); } if (is_set(right_node)) { right_node->set_initialized(); } initialized = true; } void GenGeometryObject::set_all_attributes_as_default_or_unset() { class_name = "GeometryObject"; name = STR_UNSET; vertex_list = std::vector<std::vector<double>>(); wall_list = std::vector<std::vector<int>>(); is_bngl_compartment = false; surface_compartment_name = STR_UNSET; surface_regions = std::vector<std::shared_ptr<SurfaceRegion>>(); surface_class = nullptr; initial_surface_releases = std::vector<std::shared_ptr<InitialSurfaceRelease>>(); initial_color = nullptr; node_type = RegionNodeType::UNSET; left_node = nullptr; right_node = nullptr; } std::shared_ptr<GeometryObject> GenGeometryObject::copy_geometry_object() const { std::shared_ptr<GeometryObject> res = std::make_shared<GeometryObject>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->vertex_list = vertex_list; res->wall_list = wall_list; res->is_bngl_compartment = is_bngl_compartment; res->surface_compartment_name = surface_compartment_name; res->surface_regions = surface_regions; res->surface_class = surface_class; res->initial_surface_releases = initial_surface_releases; res->initial_color = initial_color; res->node_type = node_type; res->left_node = left_node; res->right_node = right_node; return res; } std::shared_ptr<GeometryObject> GenGeometryObject::deepcopy_geometry_object(py::dict) const { std::shared_ptr<GeometryObject> res = std::make_shared<GeometryObject>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->vertex_list = vertex_list; res->wall_list = wall_list; res->is_bngl_compartment = is_bngl_compartment; res->surface_compartment_name = surface_compartment_name; for (const auto& item: surface_regions) { res->surface_regions.push_back((is_set(item)) ? item->deepcopy_surface_region() : nullptr); } res->surface_class = is_set(surface_class) ? surface_class->deepcopy_surface_class() : nullptr; for (const auto& item: initial_surface_releases) { res->initial_surface_releases.push_back((is_set(item)) ? item->deepcopy_initial_surface_release() : nullptr); } res->initial_color = is_set(initial_color) ? initial_color->deepcopy_color() : nullptr; res->node_type = node_type; res->left_node = is_set(left_node) ? left_node->deepcopy_region() : nullptr; res->right_node = is_set(right_node) ? right_node->deepcopy_region() : nullptr; return res; } bool GenGeometryObject::__eq__(const GeometryObject& other) const { return name == other.name && vertex_list == other.vertex_list && wall_list == other.wall_list && is_bngl_compartment == other.is_bngl_compartment && surface_compartment_name == other.surface_compartment_name && vec_ptr_eq(surface_regions, other.surface_regions) && ( (is_set(surface_class)) ? (is_set(other.surface_class) ? (surface_class->__eq__(*other.surface_class)) : false ) : (is_set(other.surface_class) ? false : true ) ) && vec_ptr_eq(initial_surface_releases, other.initial_surface_releases) && ( (is_set(initial_color)) ? (is_set(other.initial_color) ? (initial_color->__eq__(*other.initial_color)) : false ) : (is_set(other.initial_color) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } bool GenGeometryObject::eq_nonarray_attributes(const GeometryObject& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*vertex_list*/ && true /*wall_list*/ && is_bngl_compartment == other.is_bngl_compartment && surface_compartment_name == other.surface_compartment_name && true /*surface_regions*/ && ( (is_set(surface_class)) ? (is_set(other.surface_class) ? (surface_class->__eq__(*other.surface_class)) : false ) : (is_set(other.surface_class) ? false : true ) ) && true /*initial_surface_releases*/ && ( (is_set(initial_color)) ? (is_set(other.initial_color) ? (initial_color->__eq__(*other.initial_color)) : false ) : (is_set(other.initial_color) ? false : true ) ) && node_type == other.node_type && ( (is_set(left_node)) ? (is_set(other.left_node) ? (left_node->__eq__(*other.left_node)) : false ) : (is_set(other.left_node) ? false : true ) ) && ( (is_set(right_node)) ? (is_set(other.right_node) ? (right_node->__eq__(*other.right_node)) : false ) : (is_set(other.right_node) ? false : true ) ) ; } std::string GenGeometryObject::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "vertex_list=" << vec_nonptr_to_str(vertex_list, all_details, ind + " ") << ", " << "wall_list=" << vec_nonptr_to_str(wall_list, all_details, ind + " ") << ", " << "is_bngl_compartment=" << is_bngl_compartment << ", " << "surface_compartment_name=" << surface_compartment_name << ", " << "\n" << ind + " " << "surface_regions=" << vec_ptr_to_str(surface_regions, all_details, ind + " ") << ", " << "\n" << ind + " " << "surface_class=" << "(" << ((surface_class != nullptr) ? surface_class->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "initial_surface_releases=" << vec_ptr_to_str(initial_surface_releases, all_details, ind + " ") << ", " << "\n" << ind + " " << "initial_color=" << "(" << ((initial_color != nullptr) ? initial_color->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "node_type=" << node_type << ", " << "\n" << ind + " " << "left_node=" << "(" << ((left_node != nullptr) ? left_node->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "right_node=" << "(" << ((right_node != nullptr) ? right_node->to_str(all_details, ind + " ") : "null" ) << ")"; return ss.str(); } py::class_<GeometryObject> define_pybinding_GeometryObject(py::module& m) { return py::class_<GeometryObject, Region, std::shared_ptr<GeometryObject>>(m, "GeometryObject", "Class represents geometry objects defined by triangular surface elements.") .def( py::init< const std::string&, const std::vector<std::vector<double>>, const std::vector<std::vector<int>>, const bool, const std::string&, const std::vector<std::shared_ptr<SurfaceRegion>>, std::shared_ptr<SurfaceClass>, const std::vector<std::shared_ptr<InitialSurfaceRelease>>, std::shared_ptr<Color>, const RegionNodeType, std::shared_ptr<Region>, std::shared_ptr<Region> >(), py::arg("name"), py::arg("vertex_list"), py::arg("wall_list"), py::arg("is_bngl_compartment") = false, py::arg("surface_compartment_name") = STR_UNSET, py::arg("surface_regions") = std::vector<std::shared_ptr<SurfaceRegion>>(), py::arg("surface_class") = nullptr, py::arg("initial_surface_releases") = std::vector<std::shared_ptr<InitialSurfaceRelease>>(), py::arg("initial_color") = nullptr, py::arg("node_type") = RegionNodeType::UNSET, py::arg("left_node") = nullptr, py::arg("right_node") = nullptr ) .def("check_semantics", &GeometryObject::check_semantics) .def("__copy__", &GeometryObject::copy_geometry_object) .def("__deepcopy__", &GeometryObject::deepcopy_geometry_object, py::arg("memo")) .def("__str__", &GeometryObject::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &GeometryObject::__eq__, py::arg("other")) .def("translate", &GeometryObject::translate, py::arg("move"), "Move object by a specified vector. \nCannot be called after model was initialized.\n\n- move: 3D vector [x, y, z] that will be added to each vertex of this object.\n\n") .def("dump", &GeometryObject::dump) .def_property("name", &GeometryObject::get_name, &GeometryObject::set_name, "Name of the object. Also represents BNGL compartment name if 'is_bngl_compartment' is True.\n") .def_property("vertex_list", &GeometryObject::get_vertex_list, &GeometryObject::set_vertex_list, py::return_value_policy::reference, "List of [x,y,z] triplets specifying positions of individual vertices of each triangle.\n \n") .def_property("wall_list", &GeometryObject::get_wall_list, &GeometryObject::set_wall_list, py::return_value_policy::reference, "List of [a,b,c] triplets specifying each wall, individual values are indices into the \nvertex_list attribute.\n") .def_property("is_bngl_compartment", &GeometryObject::get_is_bngl_compartment, &GeometryObject::set_is_bngl_compartment, "Set to True if this object represents a 3D BNGL compartment. \nIts name will be then the BNGL compartment name. \n") .def_property("surface_compartment_name", &GeometryObject::get_surface_compartment_name, &GeometryObject::set_surface_compartment_name, "When is_bngl_compartment is True, this attribute can be set to specify its \nmembrane (2D) compartment name.\n") .def_property("surface_regions", &GeometryObject::get_surface_regions, &GeometryObject::set_surface_regions, py::return_value_policy::reference, "All surface regions associated with this geometry object.\n") .def_property("surface_class", &GeometryObject::get_surface_class, &GeometryObject::set_surface_class, "Surface class for the whole object's surface. It is applied to the whole surface of this object \nexcept for those surface regions that have their specific surface class set explicitly.\n") .def_property("initial_surface_releases", &GeometryObject::get_initial_surface_releases, &GeometryObject::set_initial_surface_releases, py::return_value_policy::reference, "Each item in this list defines either density or number of molecules to be released on this surface \nregions when simulation starts.\n") .def_property("initial_color", &GeometryObject::get_initial_color, &GeometryObject::set_initial_color, "Initial color for this geometry object. If a surface region has its color set, its value \nis used for the walls of that surface region.\n") ; } std::string GenGeometryObject::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("geometry_object") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("geometry_object"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.GeometryObject(" << nl; if (node_type != RegionNodeType::UNSET) { ss << ind << "node_type = " << node_type << "," << nl; } if (is_set(left_node)) { ss << ind << "left_node = " << left_node->export_to_python(out, ctx) << "," << nl; } if (is_set(right_node)) { ss << ind << "right_node = " << right_node->export_to_python(out, ctx) << "," << nl; } ss << ind << "name = " << "'" << name << "'" << "," << nl; ss << ind << "vertex_list = " << export_vec_vertex_list(out, ctx, exported_name) << "," << nl; ss << ind << "wall_list = " << export_vec_wall_list(out, ctx, exported_name) << "," << nl; if (is_bngl_compartment != false) { ss << ind << "is_bngl_compartment = " << is_bngl_compartment << "," << nl; } if (surface_compartment_name != STR_UNSET) { ss << ind << "surface_compartment_name = " << "'" << surface_compartment_name << "'" << "," << nl; } if (surface_regions != std::vector<std::shared_ptr<SurfaceRegion>>() && !skip_vectors_export()) { ss << ind << "surface_regions = " << export_vec_surface_regions(out, ctx, exported_name) << "," << nl; } if (is_set(surface_class)) { ss << ind << "surface_class = " << surface_class->export_to_python(out, ctx) << "," << nl; } if (initial_surface_releases != std::vector<std::shared_ptr<InitialSurfaceRelease>>() && !skip_vectors_export()) { ss << ind << "initial_surface_releases = " << export_vec_initial_surface_releases(out, ctx, exported_name) << "," << nl; } if (is_set(initial_color)) { ss << ind << "initial_color = " << initial_color->export_to_python(out, ctx) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenGeometryObject::export_vec_vertex_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < vertex_list.size(); i++) { const auto& item = vertex_list[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << "["; for (const auto& value: item) { ss << f_to_str(value) << ", "; } ss << "], "; } ss << "]"; return ss.str(); } std::string GenGeometryObject::export_vec_wall_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < wall_list.size(); i++) { const auto& item = wall_list[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << "["; for (const auto& value: item) { ss << value << ", "; } ss << "], "; } ss << "]"; return ss.str(); } std::string GenGeometryObject::export_vec_surface_regions(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < surface_regions.size(); i++) { const auto& item = surface_regions[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } std::string GenGeometryObject::export_vec_initial_surface_releases(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < initial_surface_releases.size(); i++) { const auto& item = initial_surface_releases[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_component.h
.h
3,986
119
/****************************************************************************** * * Copyright (C) 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 API_GEN_COMPONENT_H #define API_GEN_COMPONENT_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Component; class ComponentType; class PythonExportContext; #define COMPONENT_CTOR() \ Component( \ std::shared_ptr<ComponentType> component_type_, \ const std::string& state_ = "STATE_UNSET", \ const int bond_ = BOND_UNBOUND \ ) { \ class_name = "Component"; \ component_type = component_type_; \ state = state_; \ bond = bond_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Component(DefaultCtorArgType) : \ GenComponent(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenComponent: public BaseDataClass { public: GenComponent() { } GenComponent(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Component> copy_component() const; std::shared_ptr<Component> deepcopy_component(py::dict = py::dict()) const; virtual bool __eq__(const Component& other) const; virtual bool eq_nonarray_attributes(const Component& other, const bool ignore_name = false) const; bool operator == (const Component& other) const { return __eq__(other);} bool operator != (const Component& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- std::shared_ptr<ComponentType> component_type; virtual void set_component_type(std::shared_ptr<ComponentType> new_component_type_) { if (initialized) { throw RuntimeError("Value 'component_type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; component_type = new_component_type_; } virtual std::shared_ptr<ComponentType> get_component_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return component_type; } std::string state; virtual void set_state(const std::string& new_state_) { if (initialized) { throw RuntimeError("Value 'state' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; state = new_state_; } virtual const std::string& get_state() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return state; } int bond; virtual void set_bond(const int new_bond_) { if (initialized) { throw RuntimeError("Value 'bond' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; bond = new_bond_; } virtual int get_bond() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return bond; } // --- methods --- virtual std::string to_bngl_str() const = 0; }; // GenComponent class Component; py::class_<Component> define_pybinding_Component(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COMPONENT_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_release_site.h
.h
11,091
285
/****************************************************************************** * * Copyright (C) 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 API_GEN_RELEASE_SITE_H #define API_GEN_RELEASE_SITE_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ReleaseSite; class Complex; class MoleculeReleaseInfo; class Region; class ReleasePattern; class PythonExportContext; #define RELEASE_SITE_CTOR() \ ReleaseSite( \ const std::string& name_, \ std::shared_ptr<Complex> complex_ = nullptr, \ const std::vector<std::shared_ptr<MoleculeReleaseInfo>> molecule_list_ = std::vector<std::shared_ptr<MoleculeReleaseInfo>>(), \ const double release_time_ = 0, \ std::shared_ptr<ReleasePattern> release_pattern_ = nullptr, \ const Shape shape_ = Shape::UNSET, \ std::shared_ptr<Region> region_ = nullptr, \ const std::vector<double> location_ = std::vector<double>(), \ const double site_diameter_ = 0, \ const double site_radius_ = FLT_UNSET, \ const double number_to_release_ = FLT_UNSET, \ const double density_ = FLT_UNSET, \ const double concentration_ = FLT_UNSET, \ const double release_probability_ = 1 \ ) { \ class_name = "ReleaseSite"; \ name = name_; \ complex = complex_; \ molecule_list = molecule_list_; \ release_time = release_time_; \ release_pattern = release_pattern_; \ shape = shape_; \ region = region_; \ location = location_; \ site_diameter = site_diameter_; \ site_radius = site_radius_; \ number_to_release = number_to_release_; \ density = density_; \ concentration = concentration_; \ release_probability = release_probability_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ReleaseSite(DefaultCtorArgType) : \ GenReleaseSite(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenReleaseSite: public BaseDataClass { public: GenReleaseSite() { } GenReleaseSite(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ReleaseSite> copy_release_site() const; std::shared_ptr<ReleaseSite> deepcopy_release_site(py::dict = py::dict()) const; virtual bool __eq__(const ReleaseSite& other) const; virtual bool eq_nonarray_attributes(const ReleaseSite& other, const bool ignore_name = false) const; bool operator == (const ReleaseSite& other) const { return __eq__(other);} bool operator != (const ReleaseSite& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_molecule_list(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_location(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::shared_ptr<Complex> complex; virtual void set_complex(std::shared_ptr<Complex> new_complex_) { if (initialized) { throw RuntimeError("Value 'complex' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; complex = new_complex_; } virtual std::shared_ptr<Complex> get_complex() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return complex; } std::vector<std::shared_ptr<MoleculeReleaseInfo>> molecule_list; virtual void set_molecule_list(const std::vector<std::shared_ptr<MoleculeReleaseInfo>> new_molecule_list_) { if (initialized) { throw RuntimeError("Value 'molecule_list' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; molecule_list = new_molecule_list_; } virtual std::vector<std::shared_ptr<MoleculeReleaseInfo>>& get_molecule_list() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return molecule_list; } double release_time; virtual void set_release_time(const double new_release_time_) { if (initialized) { throw RuntimeError("Value 'release_time' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; release_time = new_release_time_; } virtual double get_release_time() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return release_time; } std::shared_ptr<ReleasePattern> release_pattern; virtual void set_release_pattern(std::shared_ptr<ReleasePattern> new_release_pattern_) { if (initialized) { throw RuntimeError("Value 'release_pattern' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; release_pattern = new_release_pattern_; } virtual std::shared_ptr<ReleasePattern> get_release_pattern() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return release_pattern; } Shape shape; virtual void set_shape(const Shape new_shape_) { if (initialized) { throw RuntimeError("Value 'shape' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; shape = new_shape_; } virtual Shape get_shape() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return shape; } std::shared_ptr<Region> region; virtual void set_region(std::shared_ptr<Region> new_region_) { if (initialized) { throw RuntimeError("Value 'region' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; region = new_region_; } virtual std::shared_ptr<Region> get_region() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return region; } std::vector<double> location; virtual void set_location(const std::vector<double> new_location_) { if (initialized) { throw RuntimeError("Value 'location' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; location = new_location_; } virtual std::vector<double>& get_location() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return location; } double site_diameter; virtual void set_site_diameter(const double new_site_diameter_) { if (initialized) { throw RuntimeError("Value 'site_diameter' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; site_diameter = new_site_diameter_; } virtual double get_site_diameter() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return site_diameter; } double site_radius; virtual void set_site_radius(const double new_site_radius_) { if (initialized) { throw RuntimeError("Value 'site_radius' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; site_radius = new_site_radius_; } virtual double get_site_radius() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return site_radius; } double number_to_release; virtual void set_number_to_release(const double new_number_to_release_) { if (initialized) { throw RuntimeError("Value 'number_to_release' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; number_to_release = new_number_to_release_; } virtual double get_number_to_release() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return number_to_release; } double density; virtual void set_density(const double new_density_) { if (initialized) { throw RuntimeError("Value 'density' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; density = new_density_; } virtual double get_density() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return density; } double concentration; virtual void set_concentration(const double new_concentration_) { if (initialized) { throw RuntimeError("Value 'concentration' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; concentration = new_concentration_; } virtual double get_concentration() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return concentration; } double release_probability; virtual void set_release_probability(const double new_release_probability_) { if (initialized) { throw RuntimeError("Value 'release_probability' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; release_probability = new_release_probability_; } virtual double get_release_probability() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return release_probability; } // --- methods --- }; // GenReleaseSite class ReleaseSite; py::class_<ReleaseSite> define_pybinding_ReleaseSite(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_RELEASE_SITE_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_subsystem.cpp
.cpp
12,723
272
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_subsystem.h" #include "api/subsystem.h" #include "api/elementary_molecule_type.h" #include "api/reaction_rule.h" #include "api/species.h" #include "api/surface_class.h" namespace MCell { namespace API { std::shared_ptr<Subsystem> GenSubsystem::copy_subsystem() const { std::shared_ptr<Subsystem> res = std::make_shared<Subsystem>(DefaultCtorArgType()); res->species = species; res->reaction_rules = reaction_rules; res->surface_classes = surface_classes; res->elementary_molecule_types = elementary_molecule_types; return res; } std::shared_ptr<Subsystem> GenSubsystem::deepcopy_subsystem(py::dict) const { std::shared_ptr<Subsystem> res = std::make_shared<Subsystem>(DefaultCtorArgType()); for (const auto& item: species) { res->species.push_back((is_set(item)) ? item->deepcopy_species() : nullptr); } for (const auto& item: reaction_rules) { res->reaction_rules.push_back((is_set(item)) ? item->deepcopy_reaction_rule() : nullptr); } for (const auto& item: surface_classes) { res->surface_classes.push_back((is_set(item)) ? item->deepcopy_surface_class() : nullptr); } for (const auto& item: elementary_molecule_types) { res->elementary_molecule_types.push_back((is_set(item)) ? item->deepcopy_elementary_molecule_type() : nullptr); } return res; } bool GenSubsystem::__eq__(const Subsystem& other) const { return vec_ptr_eq(species, other.species) && vec_ptr_eq(reaction_rules, other.reaction_rules) && vec_ptr_eq(surface_classes, other.surface_classes) && vec_ptr_eq(elementary_molecule_types, other.elementary_molecule_types); } bool GenSubsystem::eq_nonarray_attributes(const Subsystem& other, const bool ignore_name) const { return true /*species*/ && true /*reaction_rules*/ && true /*surface_classes*/ && true /*elementary_molecule_types*/; } std::string GenSubsystem::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "Subsystem" << ": " << "\n" << ind + " " << "species=" << vec_ptr_to_str(species, all_details, ind + " ") << ", " << "\n" << ind + " " << "reaction_rules=" << vec_ptr_to_str(reaction_rules, all_details, ind + " ") << ", " << "\n" << ind + " " << "surface_classes=" << vec_ptr_to_str(surface_classes, all_details, ind + " ") << ", " << "\n" << ind + " " << "elementary_molecule_types=" << vec_ptr_to_str(elementary_molecule_types, all_details, ind + " "); return ss.str(); } py::class_<Subsystem> define_pybinding_Subsystem(py::module& m) { return py::class_<Subsystem, std::shared_ptr<Subsystem>>(m, "Subsystem", "Subsystem usually defines a reaction network. It is a collection of \nspecies and reaction rules that use these species. \nThe main motivation for introducing such an object to MCell4 is to have \na class independent on that particular initial model state and observables that \nonly contains reactions. This way, one can define independent reusable subsystems\nand possibly merge them together when creating a model that includes multiple reaction \nnetworks. \n") .def( py::init< const std::vector<std::shared_ptr<Species>>, const std::vector<std::shared_ptr<ReactionRule>>, const std::vector<std::shared_ptr<SurfaceClass>>, const std::vector<std::shared_ptr<ElementaryMoleculeType>> >(), py::arg("species") = std::vector<std::shared_ptr<Species>>(), py::arg("reaction_rules") = std::vector<std::shared_ptr<ReactionRule>>(), py::arg("surface_classes") = std::vector<std::shared_ptr<SurfaceClass>>(), py::arg("elementary_molecule_types") = std::vector<std::shared_ptr<ElementaryMoleculeType>>() ) .def("__copy__", &Subsystem::copy_subsystem) .def("__deepcopy__", &Subsystem::deepcopy_subsystem, py::arg("memo")) .def("__str__", &Subsystem::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Subsystem::__eq__, py::arg("other")) .def("add_species", &Subsystem::add_species, py::arg("s"), "Add a reference to a Species object to the species list.\n- s\n") .def("find_species", &Subsystem::find_species, py::arg("name"), "Find a Species object using name in the species list. \nReturns None if no such species is found.\n\n- name\n") .def("add_reaction_rule", &Subsystem::add_reaction_rule, py::arg("r"), "Add a reference to a ReactionRule object to the reaction_rules list.\n- r\n") .def("find_reaction_rule", &Subsystem::find_reaction_rule, py::arg("name"), "Find a ReactionRule object using name in the reaction_rules list. \nReturns None if no such reaction rule is found.\n\n- name\n") .def("add_surface_class", &Subsystem::add_surface_class, py::arg("sc"), "Add a reference to a SurfaceClass object to the surface_classes list.\n- sc\n") .def("find_surface_class", &Subsystem::find_surface_class, py::arg("name"), "Find a SurfaceClass object using name in the surface_classes list. \nReturns None if no such surface class is found.\n\n- name\n") .def("add_elementary_molecule_type", &Subsystem::add_elementary_molecule_type, py::arg("mt"), "Add a reference to an ElementaryMoleculeType object to the elementary_molecule_types list.\n- mt\n") .def("find_elementary_molecule_type", &Subsystem::find_elementary_molecule_type, py::arg("name"), "Find an ElementaryMoleculeType object using name in the elementary_molecule_types list. \nReturns None if no such elementary molecule type is found.\n\n- name\n") .def("load_bngl_molecule_types_and_reaction_rules", &Subsystem::load_bngl_molecule_types_and_reaction_rules, py::arg("file_name"), py::arg("parameter_overrides") = std::map<std::string, double>(), "Parses a BNGL file, only reads molecule types and reaction rules sections, \ni.e. ignores observables and seed species. \nParameter values are evaluated and the result value is directly used. \nCompartments names are stored in rxn rules as strings because compartments belong \nto geometry objects and the subsystem is independent on specific geometry.\nHowever, the compartments and their objects must be defined before initialization.\n\n- file_name: Path to the BNGL file to be loaded.\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n") .def("dump", &Subsystem::dump) .def_property("species", &Subsystem::get_species, &Subsystem::set_species, py::return_value_policy::reference, "List of species to be included in the model for initialization.\nUsed usually only for simple species (species that are defined using a\nsingle molecule type without components such as 'A').\nOther species may be created inside simulation \n") .def_property("reaction_rules", &Subsystem::get_reaction_rules, &Subsystem::set_reaction_rules, py::return_value_policy::reference) .def_property("surface_classes", &Subsystem::get_surface_classes, &Subsystem::set_surface_classes, py::return_value_policy::reference) .def_property("elementary_molecule_types", &Subsystem::get_elementary_molecule_types, &Subsystem::set_elementary_molecule_types, py::return_value_policy::reference, "Contains list of elementary molecule types with their diffusion constants and other information. \nPopulated when a BNGL file is loaded and also on initialization from Species objects present in \nthe species list.\n") ; } std::string GenSubsystem::export_to_python(std::ostream& out, PythonExportContext& ctx) { std::string exported_name = "subsystem"; bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Subsystem(" << nl; if (species != std::vector<std::shared_ptr<Species>>() && !skip_vectors_export()) { ss << ind << "species = " << export_vec_species(out, ctx, exported_name) << "," << nl; } if (reaction_rules != std::vector<std::shared_ptr<ReactionRule>>() && !skip_vectors_export()) { ss << ind << "reaction_rules = " << export_vec_reaction_rules(out, ctx, exported_name) << "," << nl; } if (surface_classes != std::vector<std::shared_ptr<SurfaceClass>>() && !skip_vectors_export()) { ss << ind << "surface_classes = " << export_vec_surface_classes(out, ctx, exported_name) << "," << nl; } if (elementary_molecule_types != std::vector<std::shared_ptr<ElementaryMoleculeType>>() && !skip_vectors_export()) { ss << ind << "elementary_molecule_types = " << export_vec_elementary_molecule_types(out, ctx, exported_name) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenSubsystem::export_vec_species(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_species"; } else { exported_name = "species"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < species.size(); i++) { const auto& item = species[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenSubsystem::export_vec_reaction_rules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_reaction_rules"; } else { exported_name = "reaction_rules"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < reaction_rules.size(); i++) { const auto& item = reaction_rules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenSubsystem::export_vec_surface_classes(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_surface_classes"; } else { exported_name = "surface_classes"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < surface_classes.size(); i++) { const auto& item = surface_classes[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenSubsystem::export_vec_elementary_molecule_types(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_elementary_molecule_types"; } else { exported_name = "elementary_molecule_types"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < elementary_molecule_types.size(); i++) { const auto& item = elementary_molecule_types[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_elementary_molecule_type.cpp
.cpp
10,843
221
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_elementary_molecule_type.h" #include "api/elementary_molecule_type.h" #include "api/component.h" #include "api/component_type.h" #include "api/elementary_molecule.h" namespace MCell { namespace API { void GenElementaryMoleculeType::check_semantics() const { if (!is_set(name)) { throw ValueError("Parameter 'name' must be set."); } } void GenElementaryMoleculeType::set_initialized() { vec_set_initialized(components); initialized = true; } void GenElementaryMoleculeType::set_all_attributes_as_default_or_unset() { class_name = "ElementaryMoleculeType"; name = STR_UNSET; components = std::vector<std::shared_ptr<ComponentType>>(); diffusion_constant_2d = FLT_UNSET; diffusion_constant_3d = FLT_UNSET; custom_time_step = FLT_UNSET; custom_space_step = FLT_UNSET; target_only = false; } std::shared_ptr<ElementaryMoleculeType> GenElementaryMoleculeType::copy_elementary_molecule_type() const { std::shared_ptr<ElementaryMoleculeType> res = std::make_shared<ElementaryMoleculeType>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->components = components; res->diffusion_constant_2d = diffusion_constant_2d; res->diffusion_constant_3d = diffusion_constant_3d; res->custom_time_step = custom_time_step; res->custom_space_step = custom_space_step; res->target_only = target_only; return res; } std::shared_ptr<ElementaryMoleculeType> GenElementaryMoleculeType::deepcopy_elementary_molecule_type(py::dict) const { std::shared_ptr<ElementaryMoleculeType> res = std::make_shared<ElementaryMoleculeType>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; for (const auto& item: components) { res->components.push_back((is_set(item)) ? item->deepcopy_component_type() : nullptr); } res->diffusion_constant_2d = diffusion_constant_2d; res->diffusion_constant_3d = diffusion_constant_3d; res->custom_time_step = custom_time_step; res->custom_space_step = custom_space_step; res->target_only = target_only; return res; } bool GenElementaryMoleculeType::__eq__(const ElementaryMoleculeType& other) const { return name == other.name && vec_ptr_eq(components, other.components) && diffusion_constant_2d == other.diffusion_constant_2d && diffusion_constant_3d == other.diffusion_constant_3d && custom_time_step == other.custom_time_step && custom_space_step == other.custom_space_step && target_only == other.target_only; } bool GenElementaryMoleculeType::eq_nonarray_attributes(const ElementaryMoleculeType& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*components*/ && diffusion_constant_2d == other.diffusion_constant_2d && diffusion_constant_3d == other.diffusion_constant_3d && custom_time_step == other.custom_time_step && custom_space_step == other.custom_space_step && target_only == other.target_only; } std::string GenElementaryMoleculeType::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "\n" << ind + " " << "components=" << vec_ptr_to_str(components, all_details, ind + " ") << ", " << "\n" << ind + " " << "diffusion_constant_2d=" << diffusion_constant_2d << ", " << "diffusion_constant_3d=" << diffusion_constant_3d << ", " << "custom_time_step=" << custom_time_step << ", " << "custom_space_step=" << custom_space_step << ", " << "target_only=" << target_only; return ss.str(); } py::class_<ElementaryMoleculeType> define_pybinding_ElementaryMoleculeType(py::module& m) { return py::class_<ElementaryMoleculeType, std::shared_ptr<ElementaryMoleculeType>>(m, "ElementaryMoleculeType", "An elementary molecule type is a base indivisible entity. It is the same as \na molecule type in BNGL entered in section molecule types. \nThe 'elementary' prefix was added to distinguish it clearly from molecules in \nsimulation.\n") .def( py::init< const std::string&, const std::vector<std::shared_ptr<ComponentType>>, const double, const double, const double, const double, const bool >(), py::arg("name"), py::arg("components") = std::vector<std::shared_ptr<ComponentType>>(), py::arg("diffusion_constant_2d") = FLT_UNSET, py::arg("diffusion_constant_3d") = FLT_UNSET, py::arg("custom_time_step") = FLT_UNSET, py::arg("custom_space_step") = FLT_UNSET, py::arg("target_only") = false ) .def("check_semantics", &ElementaryMoleculeType::check_semantics) .def("__copy__", &ElementaryMoleculeType::copy_elementary_molecule_type) .def("__deepcopy__", &ElementaryMoleculeType::deepcopy_elementary_molecule_type, py::arg("memo")) .def("__str__", &ElementaryMoleculeType::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ElementaryMoleculeType::__eq__, py::arg("other")) .def("inst", &ElementaryMoleculeType::inst, py::arg("components") = std::vector<std::shared_ptr<Component>>(), py::arg("compartment_name") = STR_UNSET, "Create an elementary molecule based on this elementary molecule type.\n- components: Instances of components for the the created elementary molecule.\nNot all components need to be specified in case when the elementary \nmolecule is used in a pattern.\n \n\n\n- compartment_name: Optional specification of compartment name for the created elementary molecule. \n\n\n") .def("to_bngl_str", &ElementaryMoleculeType::to_bngl_str, "Creates a string that corresponds to its BNGL representation.") .def("dump", &ElementaryMoleculeType::dump) .def_property("name", &ElementaryMoleculeType::get_name, &ElementaryMoleculeType::set_name, "Name of this elementary molecule type.") .def_property("components", &ElementaryMoleculeType::get_components, &ElementaryMoleculeType::set_components, py::return_value_policy::reference, "List of components used by this elementary molecule type.") .def_property("diffusion_constant_2d", &ElementaryMoleculeType::get_diffusion_constant_2d, &ElementaryMoleculeType::set_diffusion_constant_2d, "Elementary molecule based on this type is constrained to a surface\nand diffuses with the specified diffusion constant.\nD can be zero, in which case the molecule doesn’t move. \nThe units of D are cm^2 /s.\n") .def_property("diffusion_constant_3d", &ElementaryMoleculeType::get_diffusion_constant_3d, &ElementaryMoleculeType::set_diffusion_constant_3d, "Elementary molecule based on this type diffuses in space with the \nspecified diffusion constant D. \nD can be zero, in which case the molecule doesn’t move. \nThe units of D are cm^2 /s.\n") .def_property("custom_time_step", &ElementaryMoleculeType::get_custom_time_step, &ElementaryMoleculeType::set_custom_time_step, "This molecule should take timesteps of length custom_time_step (in seconds). \nUse either this or custom_time_step, not both.\n") .def_property("custom_space_step", &ElementaryMoleculeType::get_custom_space_step, &ElementaryMoleculeType::set_custom_space_step, "This molecule should take steps of average length given by the custom_space_step value (in microns). \nUse either this or custom_time_step, not both.\n") .def_property("target_only", &ElementaryMoleculeType::get_target_only, &ElementaryMoleculeType::set_target_only, "This molecule will not initiate reactions when it runs into other molecules. This\nsetting can speed up simulations when applied to a molecule at high concentrations \nthat reacts with a molecule at low concentrations (it is more efficient for\nthe low-concentration molecule to trigger the reactions). This directive does\nnot affect unimolecular reactions. \n") ; } std::string GenElementaryMoleculeType::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("elementary_molecule_type") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("elementary_molecule_type"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ElementaryMoleculeType(" << nl; ss << ind << "name = " << "'" << name << "'" << "," << nl; if (components != std::vector<std::shared_ptr<ComponentType>>() && !skip_vectors_export()) { ss << ind << "components = " << export_vec_components(out, ctx, exported_name) << "," << nl; } if (diffusion_constant_2d != FLT_UNSET) { ss << ind << "diffusion_constant_2d = " << f_to_str(diffusion_constant_2d) << "," << nl; } if (diffusion_constant_3d != FLT_UNSET) { ss << ind << "diffusion_constant_3d = " << f_to_str(diffusion_constant_3d) << "," << nl; } if (custom_time_step != FLT_UNSET) { ss << ind << "custom_time_step = " << f_to_str(custom_time_step) << "," << nl; } if (custom_space_step != FLT_UNSET) { ss << ind << "custom_space_step = " << f_to_str(custom_space_step) << "," << nl; } if (target_only != false) { ss << ind << "target_only = " << target_only << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenElementaryMoleculeType::export_vec_components(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < components.size(); i++) { const auto& item = components[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_region.h
.h
4,191
120
/****************************************************************************** * * Copyright (C) 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 API_GEN_REGION_H #define API_GEN_REGION_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Region; class PythonExportContext; #define REGION_CTOR() \ Region( \ const RegionNodeType node_type_ = RegionNodeType::UNSET, \ std::shared_ptr<Region> left_node_ = nullptr, \ std::shared_ptr<Region> right_node_ = nullptr \ ) { \ class_name = "Region"; \ node_type = node_type_; \ left_node = left_node_; \ right_node = right_node_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Region(DefaultCtorArgType) : \ GenRegion(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenRegion: public BaseDataClass { public: GenRegion() { } GenRegion(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Region> copy_region() const; std::shared_ptr<Region> deepcopy_region(py::dict = py::dict()) const; virtual bool __eq__(const Region& other) const; virtual bool eq_nonarray_attributes(const Region& other, const bool ignore_name = false) const; bool operator == (const Region& other) const { return __eq__(other);} bool operator != (const Region& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- RegionNodeType node_type; virtual void set_node_type(const RegionNodeType new_node_type_) { if (initialized) { throw RuntimeError("Value 'node_type' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; node_type = new_node_type_; } virtual RegionNodeType get_node_type() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return node_type; } std::shared_ptr<Region> left_node; virtual void set_left_node(std::shared_ptr<Region> new_left_node_) { if (initialized) { throw RuntimeError("Value 'left_node' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; left_node = new_left_node_; } virtual std::shared_ptr<Region> get_left_node() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return left_node; } std::shared_ptr<Region> right_node; virtual void set_right_node(std::shared_ptr<Region> new_right_node_) { if (initialized) { throw RuntimeError("Value 'right_node' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; right_node = new_right_node_; } virtual std::shared_ptr<Region> get_right_node() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return right_node; } // --- methods --- virtual std::shared_ptr<Region> __add__(std::shared_ptr<Region> other) = 0; virtual std::shared_ptr<Region> __sub__(std::shared_ptr<Region> other) = 0; virtual std::shared_ptr<Region> __mul__(std::shared_ptr<Region> other) = 0; }; // GenRegion class Region; py::class_<Region> define_pybinding_Region(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_REGION_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_initial_surface_release.cpp
.cpp
6,024
168
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_initial_surface_release.h" #include "api/initial_surface_release.h" #include "api/complex.h" namespace MCell { namespace API { void GenInitialSurfaceRelease::check_semantics() const { if (!is_set(complex)) { throw ValueError("Parameter 'complex' must be set."); } } void GenInitialSurfaceRelease::set_initialized() { if (is_set(complex)) { complex->set_initialized(); } initialized = true; } void GenInitialSurfaceRelease::set_all_attributes_as_default_or_unset() { class_name = "InitialSurfaceRelease"; complex = nullptr; number_to_release = INT_UNSET; density = FLT_UNSET; } std::shared_ptr<InitialSurfaceRelease> GenInitialSurfaceRelease::copy_initial_surface_release() const { std::shared_ptr<InitialSurfaceRelease> res = std::make_shared<InitialSurfaceRelease>(DefaultCtorArgType()); res->class_name = class_name; res->complex = complex; res->number_to_release = number_to_release; res->density = density; return res; } std::shared_ptr<InitialSurfaceRelease> GenInitialSurfaceRelease::deepcopy_initial_surface_release(py::dict) const { std::shared_ptr<InitialSurfaceRelease> res = std::make_shared<InitialSurfaceRelease>(DefaultCtorArgType()); res->class_name = class_name; res->complex = is_set(complex) ? complex->deepcopy_complex() : nullptr; res->number_to_release = number_to_release; res->density = density; return res; } bool GenInitialSurfaceRelease::__eq__(const InitialSurfaceRelease& other) const { return ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && number_to_release == other.number_to_release && density == other.density; } bool GenInitialSurfaceRelease::eq_nonarray_attributes(const InitialSurfaceRelease& other, const bool ignore_name) const { return ( (is_set(complex)) ? (is_set(other.complex) ? (complex->__eq__(*other.complex)) : false ) : (is_set(other.complex) ? false : true ) ) && number_to_release == other.number_to_release && density == other.density; } std::string GenInitialSurfaceRelease::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "complex=" << "(" << ((complex != nullptr) ? complex->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "number_to_release=" << number_to_release << ", " << "density=" << density; return ss.str(); } py::class_<InitialSurfaceRelease> define_pybinding_InitialSurfaceRelease(py::module& m) { return py::class_<InitialSurfaceRelease, std::shared_ptr<InitialSurfaceRelease>>(m, "InitialSurfaceRelease", "Defines molecules to be released onto a SurfaceRegion right when simulation starts") .def( py::init< std::shared_ptr<Complex>, const int, const double >(), py::arg("complex"), py::arg("number_to_release") = INT_UNSET, py::arg("density") = FLT_UNSET ) .def("check_semantics", &InitialSurfaceRelease::check_semantics) .def("__copy__", &InitialSurfaceRelease::copy_initial_surface_release) .def("__deepcopy__", &InitialSurfaceRelease::deepcopy_initial_surface_release, py::arg("memo")) .def("__str__", &InitialSurfaceRelease::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &InitialSurfaceRelease::__eq__, py::arg("other")) .def("dump", &InitialSurfaceRelease::dump) .def_property("complex", &InitialSurfaceRelease::get_complex, &InitialSurfaceRelease::set_complex, "Defines the species of the molecule that will be released.\n") .def_property("number_to_release", &InitialSurfaceRelease::get_number_to_release, &InitialSurfaceRelease::set_number_to_release, "Number of molecules to be released onto a region,\nonly one of number_to_release and density can be set.\n") .def_property("density", &InitialSurfaceRelease::get_density, &InitialSurfaceRelease::set_density, "Density of molecules to be released onto a region,\nonly one of number_to_release and density can be set.\n") ; } std::string GenInitialSurfaceRelease::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "initial_surface_release_" + std::to_string(ctx.postinc_counter("initial_surface_release")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.InitialSurfaceRelease(" << nl; ss << ind << "complex = " << complex->export_to_python(out, ctx) << "," << nl; if (number_to_release != INT_UNSET) { ss << ind << "number_to_release = " << number_to_release << "," << nl; } if (density != FLT_UNSET) { ss << ind << "density = " << f_to_str(density) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_introspection.cpp
.cpp
5,065
80
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_introspection.h" #include "api/introspection.h" #include "api/color.h" #include "api/complex.h" #include "api/geometry_object.h" #include "api/molecule.h" #include "api/wall.h" namespace MCell { namespace API { std::shared_ptr<Introspection> GenIntrospection::copy_introspection() const { std::shared_ptr<Introspection> res = std::make_shared<Introspection>(DefaultCtorArgType()); return res; } std::shared_ptr<Introspection> GenIntrospection::deepcopy_introspection(py::dict) const { std::shared_ptr<Introspection> res = std::make_shared<Introspection>(DefaultCtorArgType()); return res; } bool GenIntrospection::__eq__(const Introspection& other) const { return true ; } bool GenIntrospection::eq_nonarray_attributes(const Introspection& other, const bool ignore_name) const { return true ; } std::string GenIntrospection::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "Introspection"; return ss.str(); } py::class_<Introspection> define_pybinding_Introspection(py::module& m) { return py::class_<Introspection, std::shared_ptr<Introspection>>(m, "Introspection", "Only internal. This class is used only as a base class to Model, it is not provided through API. Defines interface to introspect simulation state.") .def( py::init< >() ) .def("__copy__", &Introspection::copy_introspection) .def("__deepcopy__", &Introspection::deepcopy_introspection, py::arg("memo")) .def("__str__", &Introspection::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Introspection::__eq__, py::arg("other")) .def("get_molecule_ids", &Introspection::get_molecule_ids, py::arg("pattern") = nullptr, "Returns a list of ids of molecules.\nIf the arguments pattern is not set, the list of all molecule ids is returned. \nIf the argument pattern is set, the list of all molecule ids whose species match \nthe pattern is returned. \n\n- pattern: BNGL pattern to select molecules based on their species, might use compartments.\n\n") .def("get_molecule", &Introspection::get_molecule, py::arg("id"), "Returns a information on a molecule from the simulated environment, \nNone if the molecule does not exist.\n\n- id: Unique id of the molecule to be retrieved.\n\n") .def("get_species_name", &Introspection::get_species_name, py::arg("species_id"), "Returns a string representing canonical species name in the BNGL format.\n\n- species_id: Id of the species.\n\n") .def("get_vertex", &Introspection::get_vertex, py::arg("object"), py::arg("vertex_index"), "Returns coordinates of a vertex.\n- object\n- vertex_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("get_wall", &Introspection::get_wall, py::arg("object"), py::arg("wall_index"), "Returns information about a wall belonging to a given object.\n- object: Geometry object whose wall to retrieve.\n\n- wall_index: This is the index of the wall in the geometry object's walls (wall_list).\n\n") .def("get_vertex_unit_normal", &Introspection::get_vertex_unit_normal, py::arg("object"), py::arg("vertex_index"), "Returns sum of all wall normals that use this vertex converted to a unit vector of \nlength 1 um (micrometer).\nThis represents the unit vector pointing outwards from the vertex.\n\n- object: Geometry object whose vertex to retrieve.\n\n- vertex_index: This is the index of the vertex in the geometry object's vertex_list.\n\n") .def("get_wall_unit_normal", &Introspection::get_wall_unit_normal, py::arg("object"), py::arg("wall_index"), "Returns wall normal converted to a unit vector of length 1um.\n- object: Geometry object whose wall's normal to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("get_wall_color", &Introspection::get_wall_color, py::arg("object"), py::arg("wall_index"), "Returns color of a wall.\n- object: Geometry object whose wall's color to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("set_wall_color", &Introspection::set_wall_color, py::arg("object"), py::arg("wall_index"), py::arg("color"), "Sets color of a wall.\n- object: Geometry object whose wall's color to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n- color: Color to be set.\n\n") .def("dump", &Introspection::dump) ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_reaction_info.cpp
.cpp
8,115
160
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_reaction_info.h" #include "api/reaction_info.h" #include "api/geometry_object.h" #include "api/reaction_rule.h" namespace MCell { namespace API { std::shared_ptr<ReactionInfo> GenReactionInfo::copy_reaction_info() const { std::shared_ptr<ReactionInfo> res = std::make_shared<ReactionInfo>(DefaultCtorArgType()); res->type = type; res->reactant_ids = reactant_ids; res->product_ids = product_ids; res->reaction_rule = reaction_rule; res->time = time; res->pos3d = pos3d; res->geometry_object = geometry_object; res->wall_index = wall_index; res->pos2d = pos2d; return res; } std::shared_ptr<ReactionInfo> GenReactionInfo::deepcopy_reaction_info(py::dict) const { std::shared_ptr<ReactionInfo> res = std::make_shared<ReactionInfo>(DefaultCtorArgType()); res->type = type; res->reactant_ids = reactant_ids; res->product_ids = product_ids; res->reaction_rule = is_set(reaction_rule) ? reaction_rule->deepcopy_reaction_rule() : nullptr; res->time = time; res->pos3d = pos3d; res->geometry_object = is_set(geometry_object) ? geometry_object->deepcopy_geometry_object() : nullptr; res->wall_index = wall_index; res->pos2d = pos2d; return res; } bool GenReactionInfo::__eq__(const ReactionInfo& other) const { return type == other.type && reactant_ids == other.reactant_ids && product_ids == other.product_ids && ( (is_set(reaction_rule)) ? (is_set(other.reaction_rule) ? (reaction_rule->__eq__(*other.reaction_rule)) : false ) : (is_set(other.reaction_rule) ? false : true ) ) && time == other.time && pos3d == other.pos3d && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && pos2d == other.pos2d; } bool GenReactionInfo::eq_nonarray_attributes(const ReactionInfo& other, const bool ignore_name) const { return type == other.type && true /*reactant_ids*/ && true /*product_ids*/ && ( (is_set(reaction_rule)) ? (is_set(other.reaction_rule) ? (reaction_rule->__eq__(*other.reaction_rule)) : false ) : (is_set(other.reaction_rule) ? false : true ) ) && time == other.time && true /*pos3d*/ && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && true /*pos2d*/; } std::string GenReactionInfo::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "ReactionInfo" << ": " << "type=" << type << ", " << "reactant_ids=" << vec_nonptr_to_str(reactant_ids, all_details, ind + " ") << ", " << "product_ids=" << vec_nonptr_to_str(product_ids, all_details, ind + " ") << ", " << "\n" << ind + " " << "reaction_rule=" << "(" << ((reaction_rule != nullptr) ? reaction_rule->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "time=" << time << ", " << "pos3d=" << vec_nonptr_to_str(pos3d, all_details, ind + " ") << ", " << "\n" << ind + " " << "geometry_object=" << "(" << ((geometry_object != nullptr) ? geometry_object->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall_index=" << wall_index << ", " << "pos2d=" << vec_nonptr_to_str(pos2d, all_details, ind + " "); return ss.str(); } py::class_<ReactionInfo> define_pybinding_ReactionInfo(py::module& m) { return py::class_<ReactionInfo, std::shared_ptr<ReactionInfo>>(m, "ReactionInfo", "Data structure passed to a reaction callback registered with \nModel.register_reaction_callback.\n") .def( py::init< >() ) .def("__copy__", &ReactionInfo::copy_reaction_info) .def("__deepcopy__", &ReactionInfo::deepcopy_reaction_info, py::arg("memo")) .def("__str__", &ReactionInfo::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ReactionInfo::__eq__, py::arg("other")) .def("dump", &ReactionInfo::dump) .def_property("type", &ReactionInfo::get_type, &ReactionInfo::set_type, "Specifies whether the reaction is unimolecular or bimolecular and\nalso provides information on reactant types. \n") .def_property("reactant_ids", &ReactionInfo::get_reactant_ids, &ReactionInfo::set_reactant_ids, py::return_value_policy::reference, "IDs of the reacting molecules, contains 1 ID for a unimolecular or a molecule+surface class reaction, \n2 IDs for a bimolecular reaction.\nFor a bimolecular reaction, the first ID is always the molecule that diffused and the second one \nis the molecule that was hit.\nIDs can be used to obtain the location of the molecules. The position of the first molecule obtained through \nmodel.get_molecule() is the position of the diffusing molecule before the collision.\nAll the reactants are removed after return from this callback, unless they are kept by the reaction such as A in A + B -> A + C. \n") .def_property("product_ids", &ReactionInfo::get_product_ids, &ReactionInfo::set_product_ids, py::return_value_policy::reference, "IDs of reaction product molecules. They already exist in the simulated system together with reactants; however reactants \nwill be removed after return from this callback. \n") .def_property("reaction_rule", &ReactionInfo::get_reaction_rule, &ReactionInfo::set_reaction_rule, "Reaction rule of the reaction that occured.") .def_property("time", &ReactionInfo::get_time, &ReactionInfo::set_time, "Time of the reaction.") .def_property("pos3d", &ReactionInfo::get_pos3d, &ReactionInfo::set_pos3d, py::return_value_policy::reference, "Specifies where reaction occurred in the 3d space, the specific meaning depends on the reaction type:\n- unimolecular reaction - position of the reacting molecule,\n- volume-volume or surface-surface reaction - position of the first reactant,\n- volume-surface reaction - position where the volume molecule hit the wall with the surface molecule.\n") .def_property("geometry_object", &ReactionInfo::get_geometry_object, &ReactionInfo::set_geometry_object, "The object on whose surface where the reaction occurred.\nSet only for surface reactions or reactions with surface classes.\n") .def_property("wall_index", &ReactionInfo::get_wall_index, &ReactionInfo::set_wall_index, "Set only for surface reactions or reactions with surface classes.\nIndex of wall belonging to the geometry_object where the reaction occured, \ni.e. wall where a volume molecule hit the surface molecule or\nwall where the diffusing surface reactant reacted.\n") .def_property("pos2d", &ReactionInfo::get_pos2d, &ReactionInfo::set_pos2d, py::return_value_policy::reference, "Set only for surface reactions or reactions with surface classes.\nSpecifies where reaction occurred in the 2d UV coordinates defined by the wall where the reaction occured, \nthe rspecific meaning depends on the reaction type:\n- unimolecular reaction - position of the reacting molecule,\n- volume-surface and surface-surface reaction - position of the second reactant.\n \n ") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_data_utils.h
.h
792
33
/****************************************************************************** * * Copyright (C) 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 API_GEN_DATA_UTILS_H #define API_GEN_DATA_UTILS_H #include "api/api_common.h" namespace MCell { namespace API { class PythonExportContext; namespace data_utils { std::vector<std::vector<double>> load_dat_file(const std::string& file_name); } // namespace data_utils void define_pybinding_data_utils(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_DATA_UTILS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_base_chkpt_mol.cpp
.cpp
6,779
208
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_base_chkpt_mol.h" #include "api/base_chkpt_mol.h" #include "api/species.h" namespace MCell { namespace API { void GenBaseChkptMol::check_semantics() const { if (!is_set(id)) { throw ValueError("Parameter 'id' must be set."); } if (!is_set(species)) { throw ValueError("Parameter 'species' must be set."); } if (!is_set(diffusion_time)) { throw ValueError("Parameter 'diffusion_time' must be set."); } if (!is_set(birthday)) { throw ValueError("Parameter 'birthday' must be set."); } if (!is_set(flags)) { throw ValueError("Parameter 'flags' must be set."); } } void GenBaseChkptMol::set_initialized() { if (is_set(species)) { species->set_initialized(); } initialized = true; } void GenBaseChkptMol::set_all_attributes_as_default_or_unset() { class_name = "BaseChkptMol"; id = INT_UNSET; species = nullptr; diffusion_time = FLT_UNSET; birthday = FLT_UNSET; flags = INT_UNSET; unimol_rxn_time = FLT_UNSET; } std::shared_ptr<BaseChkptMol> GenBaseChkptMol::copy_base_chkpt_mol() const { std::shared_ptr<BaseChkptMol> res = std::make_shared<BaseChkptMol>(DefaultCtorArgType()); res->class_name = class_name; res->id = id; res->species = species; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } std::shared_ptr<BaseChkptMol> GenBaseChkptMol::deepcopy_base_chkpt_mol(py::dict) const { std::shared_ptr<BaseChkptMol> res = std::make_shared<BaseChkptMol>(DefaultCtorArgType()); res->class_name = class_name; res->id = id; res->species = is_set(species) ? species->deepcopy_species() : nullptr; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } bool GenBaseChkptMol::__eq__(const BaseChkptMol& other) const { return id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } bool GenBaseChkptMol::eq_nonarray_attributes(const BaseChkptMol& other, const bool ignore_name) const { return id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } std::string GenBaseChkptMol::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "id=" << id << ", " << "\n" << ind + " " << "species=" << "(" << ((species != nullptr) ? species->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "diffusion_time=" << diffusion_time << ", " << "birthday=" << birthday << ", " << "flags=" << flags << ", " << "unimol_rxn_time=" << unimol_rxn_time; return ss.str(); } py::class_<BaseChkptMol> define_pybinding_BaseChkptMol(py::module& m) { return py::class_<BaseChkptMol, std::shared_ptr<BaseChkptMol>>(m, "BaseChkptMol", "Base class for checkpointed molecules.\nNot to be used directly. All times are in seconds.\n") .def( py::init< const int, std::shared_ptr<Species>, const double, const double, const int, const double >(), py::arg("id"), py::arg("species"), py::arg("diffusion_time"), py::arg("birthday"), py::arg("flags"), py::arg("unimol_rxn_time") = FLT_UNSET ) .def("check_semantics", &BaseChkptMol::check_semantics) .def("__copy__", &BaseChkptMol::copy_base_chkpt_mol) .def("__deepcopy__", &BaseChkptMol::deepcopy_base_chkpt_mol, py::arg("memo")) .def("__str__", &BaseChkptMol::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &BaseChkptMol::__eq__, py::arg("other")) .def("dump", &BaseChkptMol::dump) .def_property("id", &BaseChkptMol::get_id, &BaseChkptMol::set_id) .def_property("species", &BaseChkptMol::get_species, &BaseChkptMol::set_species) .def_property("diffusion_time", &BaseChkptMol::get_diffusion_time, &BaseChkptMol::set_diffusion_time) .def_property("birthday", &BaseChkptMol::get_birthday, &BaseChkptMol::set_birthday) .def_property("flags", &BaseChkptMol::get_flags, &BaseChkptMol::set_flags) .def_property("unimol_rxn_time", &BaseChkptMol::get_unimol_rxn_time, &BaseChkptMol::set_unimol_rxn_time) ; } std::string GenBaseChkptMol::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "base_chkpt_mol_" + std::to_string(ctx.postinc_counter("base_chkpt_mol")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.BaseChkptMol(" << nl; ss << ind << "id = " << id << "," << nl; ss << ind << "species = " << species->export_to_python(out, ctx) << "," << nl; ss << ind << "diffusion_time = " << f_to_str(diffusion_time) << "," << nl; ss << ind << "birthday = " << f_to_str(birthday) << "," << nl; ss << ind << "flags = " << flags << "," << nl; if (unimol_rxn_time != FLT_UNSET) { ss << ind << "unimol_rxn_time = " << f_to_str(unimol_rxn_time) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_release_pattern.h
.h
4,921
135
/****************************************************************************** * * Copyright (C) 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 API_GEN_RELEASE_PATTERN_H #define API_GEN_RELEASE_PATTERN_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class ReleasePattern; class PythonExportContext; #define RELEASE_PATTERN_CTOR() \ ReleasePattern( \ const std::string& name_ = STR_UNSET, \ const double release_interval_ = TIME_INFINITY, \ const double train_duration_ = TIME_INFINITY, \ const double train_interval_ = TIME_INFINITY, \ const int number_of_trains_ = 1 \ ) { \ class_name = "ReleasePattern"; \ name = name_; \ release_interval = release_interval_; \ train_duration = train_duration_; \ train_interval = train_interval_; \ number_of_trains = number_of_trains_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ReleasePattern(DefaultCtorArgType) : \ GenReleasePattern(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenReleasePattern: public BaseDataClass { public: GenReleasePattern() { } GenReleasePattern(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ReleasePattern> copy_release_pattern() const; std::shared_ptr<ReleasePattern> deepcopy_release_pattern(py::dict = py::dict()) const; virtual bool __eq__(const ReleasePattern& other) const; virtual bool eq_nonarray_attributes(const ReleasePattern& other, const bool ignore_name = false) const; bool operator == (const ReleasePattern& other) const { return __eq__(other);} bool operator != (const ReleasePattern& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- double release_interval; virtual void set_release_interval(const double new_release_interval_) { if (initialized) { throw RuntimeError("Value 'release_interval' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; release_interval = new_release_interval_; } virtual double get_release_interval() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return release_interval; } double train_duration; virtual void set_train_duration(const double new_train_duration_) { if (initialized) { throw RuntimeError("Value 'train_duration' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; train_duration = new_train_duration_; } virtual double get_train_duration() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return train_duration; } double train_interval; virtual void set_train_interval(const double new_train_interval_) { if (initialized) { throw RuntimeError("Value 'train_interval' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; train_interval = new_train_interval_; } virtual double get_train_interval() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return train_interval; } int number_of_trains; virtual void set_number_of_trains(const int new_number_of_trains_) { if (initialized) { throw RuntimeError("Value 'number_of_trains' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; number_of_trains = new_number_of_trains_; } virtual int get_number_of_trains() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return number_of_trains; } // --- methods --- }; // GenReleasePattern class ReleasePattern; py::class_<ReleasePattern> define_pybinding_ReleasePattern(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_RELEASE_PATTERN_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_mol_wall_hit_info.h
.h
3,053
105
/****************************************************************************** * * Copyright (C) 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 API_GEN_MOL_WALL_HIT_INFO_H #define API_GEN_MOL_WALL_HIT_INFO_H #include "api/api_common.h" namespace MCell { namespace API { class MolWallHitInfo; class GeometryObject; class PythonExportContext; class GenMolWallHitInfo { public: GenMolWallHitInfo() { } GenMolWallHitInfo(DefaultCtorArgType) { } virtual ~GenMolWallHitInfo() {} std::shared_ptr<MolWallHitInfo> copy_mol_wall_hit_info() const; std::shared_ptr<MolWallHitInfo> deepcopy_mol_wall_hit_info(py::dict = py::dict()) const; virtual bool __eq__(const MolWallHitInfo& other) const; virtual bool eq_nonarray_attributes(const MolWallHitInfo& other, const bool ignore_name = false) const; bool operator == (const MolWallHitInfo& other) const { return __eq__(other);} bool operator != (const MolWallHitInfo& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; // --- attributes --- int molecule_id; virtual void set_molecule_id(const int new_molecule_id_) { molecule_id = new_molecule_id_; } virtual int get_molecule_id() const { return molecule_id; } std::shared_ptr<GeometryObject> geometry_object; virtual void set_geometry_object(std::shared_ptr<GeometryObject> new_geometry_object_) { geometry_object = new_geometry_object_; } virtual std::shared_ptr<GeometryObject> get_geometry_object() const { return geometry_object; } int wall_index; virtual void set_wall_index(const int new_wall_index_) { wall_index = new_wall_index_; } virtual int get_wall_index() const { return wall_index; } double time; virtual void set_time(const double new_time_) { time = new_time_; } virtual double get_time() const { return time; } std::vector<double> pos3d; virtual void set_pos3d(const std::vector<double> new_pos3d_) { pos3d = new_pos3d_; } virtual std::vector<double>& get_pos3d() { return pos3d; } double time_before_hit; virtual void set_time_before_hit(const double new_time_before_hit_) { time_before_hit = new_time_before_hit_; } virtual double get_time_before_hit() const { return time_before_hit; } std::vector<double> pos3d_before_hit; virtual void set_pos3d_before_hit(const std::vector<double> new_pos3d_before_hit_) { pos3d_before_hit = new_pos3d_before_hit_; } virtual std::vector<double>& get_pos3d_before_hit() { return pos3d_before_hit; } // --- methods --- }; // GenMolWallHitInfo class MolWallHitInfo; py::class_<MolWallHitInfo> define_pybinding_MolWallHitInfo(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_MOL_WALL_HIT_INFO_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_notifications.cpp
.cpp
7,930
179
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_notifications.h" #include "api/notifications.h" namespace MCell { namespace API { void GenNotifications::check_semantics() const { } void GenNotifications::set_initialized() { initialized = true; } void GenNotifications::set_all_attributes_as_default_or_unset() { class_name = "Notifications"; bng_verbosity_level = 0; rxn_and_species_report = false; simulation_stats_every_n_iterations = 0; rxn_probability_changed = true; iteration_report = true; wall_overlap_report = false; } std::shared_ptr<Notifications> GenNotifications::copy_notifications() const { std::shared_ptr<Notifications> res = std::make_shared<Notifications>(DefaultCtorArgType()); res->class_name = class_name; res->bng_verbosity_level = bng_verbosity_level; res->rxn_and_species_report = rxn_and_species_report; res->simulation_stats_every_n_iterations = simulation_stats_every_n_iterations; res->rxn_probability_changed = rxn_probability_changed; res->iteration_report = iteration_report; res->wall_overlap_report = wall_overlap_report; return res; } std::shared_ptr<Notifications> GenNotifications::deepcopy_notifications(py::dict) const { std::shared_ptr<Notifications> res = std::make_shared<Notifications>(DefaultCtorArgType()); res->class_name = class_name; res->bng_verbosity_level = bng_verbosity_level; res->rxn_and_species_report = rxn_and_species_report; res->simulation_stats_every_n_iterations = simulation_stats_every_n_iterations; res->rxn_probability_changed = rxn_probability_changed; res->iteration_report = iteration_report; res->wall_overlap_report = wall_overlap_report; return res; } bool GenNotifications::__eq__(const Notifications& other) const { return bng_verbosity_level == other.bng_verbosity_level && rxn_and_species_report == other.rxn_and_species_report && simulation_stats_every_n_iterations == other.simulation_stats_every_n_iterations && rxn_probability_changed == other.rxn_probability_changed && iteration_report == other.iteration_report && wall_overlap_report == other.wall_overlap_report; } bool GenNotifications::eq_nonarray_attributes(const Notifications& other, const bool ignore_name) const { return bng_verbosity_level == other.bng_verbosity_level && rxn_and_species_report == other.rxn_and_species_report && simulation_stats_every_n_iterations == other.simulation_stats_every_n_iterations && rxn_probability_changed == other.rxn_probability_changed && iteration_report == other.iteration_report && wall_overlap_report == other.wall_overlap_report; } std::string GenNotifications::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "bng_verbosity_level=" << bng_verbosity_level << ", " << "rxn_and_species_report=" << rxn_and_species_report << ", " << "simulation_stats_every_n_iterations=" << simulation_stats_every_n_iterations << ", " << "rxn_probability_changed=" << rxn_probability_changed << ", " << "iteration_report=" << iteration_report << ", " << "wall_overlap_report=" << wall_overlap_report; return ss.str(); } py::class_<Notifications> define_pybinding_Notifications(py::module& m) { return py::class_<Notifications, std::shared_ptr<Notifications>>(m, "Notifications") .def( py::init< const int, const bool, const int, const bool, const bool, const bool >(), py::arg("bng_verbosity_level") = 0, py::arg("rxn_and_species_report") = false, py::arg("simulation_stats_every_n_iterations") = 0, py::arg("rxn_probability_changed") = true, py::arg("iteration_report") = true, py::arg("wall_overlap_report") = false ) .def("check_semantics", &Notifications::check_semantics) .def("__copy__", &Notifications::copy_notifications) .def("__deepcopy__", &Notifications::deepcopy_notifications, py::arg("memo")) .def("__str__", &Notifications::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Notifications::__eq__, py::arg("other")) .def("dump", &Notifications::dump) .def_property("bng_verbosity_level", &Notifications::get_bng_verbosity_level, &Notifications::set_bng_verbosity_level, "Sets verbosity level that enables printouts of extra information on BioNetGen \nspecies and rules created and used during simulation.\n") .def_property("rxn_and_species_report", &Notifications::get_rxn_and_species_report, &Notifications::set_rxn_and_species_report, "When set to True, simulation generates files rxn_report_SEED.txt, and \nspecies_report_SEED.txt that contain details on reaction classes and species \nthat were created based on reaction rules. \n") .def_property("simulation_stats_every_n_iterations", &Notifications::get_simulation_stats_every_n_iterations, &Notifications::set_simulation_stats_every_n_iterations, "When set to a value other than 0, internal simulation stats will be printed. \n") .def_property("rxn_probability_changed", &Notifications::get_rxn_probability_changed, &Notifications::set_rxn_probability_changed, "When True, information that a reaction's probability has changed is printed during simulation. \n") .def_property("iteration_report", &Notifications::get_iteration_report, &Notifications::set_iteration_report, "When True, a running report of how many iterations have completed, chosen based \non the total number of iterations, will be printed during simulation.\n") .def_property("wall_overlap_report", &Notifications::get_wall_overlap_report, &Notifications::set_wall_overlap_report, "When True, information on wall overlaps will be printed. \n") ; } std::string GenNotifications::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "notifications_" + std::to_string(ctx.postinc_counter("notifications")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Notifications(" << nl; if (bng_verbosity_level != 0) { ss << ind << "bng_verbosity_level = " << bng_verbosity_level << "," << nl; } if (rxn_and_species_report != false) { ss << ind << "rxn_and_species_report = " << rxn_and_species_report << "," << nl; } if (simulation_stats_every_n_iterations != 0) { ss << ind << "simulation_stats_every_n_iterations = " << simulation_stats_every_n_iterations << "," << nl; } if (rxn_probability_changed != true) { ss << ind << "rxn_probability_changed = " << rxn_probability_changed << "," << nl; } if (iteration_report != true) { ss << ind << "iteration_report = " << iteration_report << "," << nl; } if (wall_overlap_report != false) { ss << ind << "wall_overlap_report = " << wall_overlap_report << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_complex.h
.h
4,645
124
/****************************************************************************** * * Copyright (C) 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 API_GEN_COMPLEX_H #define API_GEN_COMPLEX_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Complex; class ElementaryMolecule; class Species; class PythonExportContext; #define COMPLEX_CTOR() \ Complex( \ const std::string& name_ = STR_UNSET, \ const std::vector<std::shared_ptr<ElementaryMolecule>> elementary_molecules_ = std::vector<std::shared_ptr<ElementaryMolecule>>(), \ const Orientation orientation_ = Orientation::DEFAULT, \ const std::string& compartment_name_ = STR_UNSET \ ) { \ class_name = "Complex"; \ name = name_; \ elementary_molecules = elementary_molecules_; \ orientation = orientation_; \ compartment_name = compartment_name_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Complex(DefaultCtorArgType) : \ GenComplex(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenComplex: public BaseDataClass { public: GenComplex() { } GenComplex(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Complex> copy_complex() const; std::shared_ptr<Complex> deepcopy_complex(py::dict = py::dict()) const; virtual bool __eq__(const Complex& other) const; virtual bool eq_nonarray_attributes(const Complex& other, const bool ignore_name = false) const; bool operator == (const Complex& other) const { return __eq__(other);} bool operator != (const Complex& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; virtual std::string export_vec_elementary_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<ElementaryMolecule>> elementary_molecules; virtual void set_elementary_molecules(const std::vector<std::shared_ptr<ElementaryMolecule>> new_elementary_molecules_) { if (initialized) { throw RuntimeError("Value 'elementary_molecules' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; elementary_molecules = new_elementary_molecules_; } virtual std::vector<std::shared_ptr<ElementaryMolecule>>& get_elementary_molecules() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return elementary_molecules; } Orientation orientation; virtual void set_orientation(const Orientation new_orientation_) { if (initialized) { throw RuntimeError("Value 'orientation' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; orientation = new_orientation_; } virtual Orientation get_orientation() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return orientation; } std::string compartment_name; virtual void set_compartment_name(const std::string& new_compartment_name_) { if (initialized) { throw RuntimeError("Value 'compartment_name' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; compartment_name = new_compartment_name_; } virtual const std::string& get_compartment_name() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return compartment_name; } // --- methods --- virtual std::string to_bngl_str() const = 0; virtual std::shared_ptr<Species> as_species() = 0; }; // GenComplex class Complex; py::class_<Complex> define_pybinding_Complex(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COMPLEX_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_surface_property.cpp
.cpp
6,459
167
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_surface_property.h" #include "api/surface_property.h" #include "api/complex.h" namespace MCell { namespace API { void GenSurfaceProperty::check_semantics() const { } void GenSurfaceProperty::set_initialized() { if (is_set(affected_complex_pattern)) { affected_complex_pattern->set_initialized(); } initialized = true; } void GenSurfaceProperty::set_all_attributes_as_default_or_unset() { class_name = "SurfaceProperty"; type = SurfacePropertyType::UNSET; affected_complex_pattern = nullptr; concentration = FLT_UNSET; } std::shared_ptr<SurfaceProperty> GenSurfaceProperty::copy_surface_property() const { std::shared_ptr<SurfaceProperty> res = std::make_shared<SurfaceProperty>(DefaultCtorArgType()); res->class_name = class_name; res->type = type; res->affected_complex_pattern = affected_complex_pattern; res->concentration = concentration; return res; } std::shared_ptr<SurfaceProperty> GenSurfaceProperty::deepcopy_surface_property(py::dict) const { std::shared_ptr<SurfaceProperty> res = std::make_shared<SurfaceProperty>(DefaultCtorArgType()); res->class_name = class_name; res->type = type; res->affected_complex_pattern = is_set(affected_complex_pattern) ? affected_complex_pattern->deepcopy_complex() : nullptr; res->concentration = concentration; return res; } bool GenSurfaceProperty::__eq__(const SurfaceProperty& other) const { return type == other.type && ( (is_set(affected_complex_pattern)) ? (is_set(other.affected_complex_pattern) ? (affected_complex_pattern->__eq__(*other.affected_complex_pattern)) : false ) : (is_set(other.affected_complex_pattern) ? false : true ) ) && concentration == other.concentration; } bool GenSurfaceProperty::eq_nonarray_attributes(const SurfaceProperty& other, const bool ignore_name) const { return type == other.type && ( (is_set(affected_complex_pattern)) ? (is_set(other.affected_complex_pattern) ? (affected_complex_pattern->__eq__(*other.affected_complex_pattern)) : false ) : (is_set(other.affected_complex_pattern) ? false : true ) ) && concentration == other.concentration; } std::string GenSurfaceProperty::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "type=" << type << ", " << "\n" << ind + " " << "affected_complex_pattern=" << "(" << ((affected_complex_pattern != nullptr) ? affected_complex_pattern->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "concentration=" << concentration; return ss.str(); } py::class_<SurfaceProperty> define_pybinding_SurfaceProperty(py::module& m) { return py::class_<SurfaceProperty, std::shared_ptr<SurfaceProperty>>(m, "SurfaceProperty", "Single property for a SurfaceClass.") .def( py::init< const SurfacePropertyType, std::shared_ptr<Complex>, const double >(), py::arg("type") = SurfacePropertyType::UNSET, py::arg("affected_complex_pattern") = nullptr, py::arg("concentration") = FLT_UNSET ) .def("check_semantics", &SurfaceProperty::check_semantics) .def("__copy__", &SurfaceProperty::copy_surface_property) .def("__deepcopy__", &SurfaceProperty::deepcopy_surface_property, py::arg("memo")) .def("__str__", &SurfaceProperty::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &SurfaceProperty::__eq__, py::arg("other")) .def("dump", &SurfaceProperty::dump) .def_property("type", &SurfaceProperty::get_type, &SurfaceProperty::set_type, "Must be set. See SurfacePropertyType for options.\n") .def_property("affected_complex_pattern", &SurfaceProperty::get_affected_complex_pattern, &SurfaceProperty::set_affected_complex_pattern, "A complex pattern with optional orientation must be set.\nDefault orientation means that the pattern matches any orientation.\nFor concentration or flux clamp the orientation specifies on which side \nwill be the concentration held (UP is front or outside, DOWN is back or \ninside, and DEFAULT, ANY or NONE is on both sides).\nThe complex pattern must not use compartments.\n") .def_property("concentration", &SurfaceProperty::get_concentration, &SurfaceProperty::set_concentration, "Specifies concentration when type is SurfacePropertyType.CLAMP_CONCENTRATION or \nSurfacePropertyType.CLAMP_FLUX. Represents concentration of the imagined opposide side \nof the wall that has this concentration or flux clamped.\n") ; } std::string GenSurfaceProperty::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "surface_property_" + std::to_string(ctx.postinc_counter("surface_property")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.SurfaceProperty(" << nl; if (type != SurfacePropertyType::UNSET) { ss << ind << "type = " << type << "," << nl; } if (is_set(affected_complex_pattern)) { ss << ind << "affected_complex_pattern = " << affected_complex_pattern->export_to_python(out, ctx) << "," << nl; } if (concentration != FLT_UNSET) { ss << ind << "concentration = " << f_to_str(concentration) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_notifications.h
.h
6,561
165
/****************************************************************************** * * Copyright (C) 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 API_GEN_NOTIFICATIONS_H #define API_GEN_NOTIFICATIONS_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Notifications; class PythonExportContext; #define NOTIFICATIONS_CTOR() \ Notifications( \ const int bng_verbosity_level_ = 0, \ const bool rxn_and_species_report_ = false, \ const int simulation_stats_every_n_iterations_ = 0, \ const bool rxn_probability_changed_ = true, \ const bool iteration_report_ = true, \ const bool wall_overlap_report_ = false \ ) { \ class_name = "Notifications"; \ bng_verbosity_level = bng_verbosity_level_; \ rxn_and_species_report = rxn_and_species_report_; \ simulation_stats_every_n_iterations = simulation_stats_every_n_iterations_; \ rxn_probability_changed = rxn_probability_changed_; \ iteration_report = iteration_report_; \ wall_overlap_report = wall_overlap_report_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Notifications(DefaultCtorArgType) : \ GenNotifications(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenNotifications: public BaseDataClass { public: GenNotifications() { } GenNotifications(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Notifications> copy_notifications() const; std::shared_ptr<Notifications> deepcopy_notifications(py::dict = py::dict()) const; virtual bool __eq__(const Notifications& other) const; virtual bool eq_nonarray_attributes(const Notifications& other, const bool ignore_name = false) const; bool operator == (const Notifications& other) const { return __eq__(other);} bool operator != (const Notifications& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- int bng_verbosity_level; virtual void set_bng_verbosity_level(const int new_bng_verbosity_level_) { if (initialized) { throw RuntimeError("Value 'bng_verbosity_level' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; bng_verbosity_level = new_bng_verbosity_level_; } virtual int get_bng_verbosity_level() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return bng_verbosity_level; } bool rxn_and_species_report; virtual void set_rxn_and_species_report(const bool new_rxn_and_species_report_) { if (initialized) { throw RuntimeError("Value 'rxn_and_species_report' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rxn_and_species_report = new_rxn_and_species_report_; } virtual bool get_rxn_and_species_report() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rxn_and_species_report; } int simulation_stats_every_n_iterations; virtual void set_simulation_stats_every_n_iterations(const int new_simulation_stats_every_n_iterations_) { if (initialized) { throw RuntimeError("Value 'simulation_stats_every_n_iterations' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; simulation_stats_every_n_iterations = new_simulation_stats_every_n_iterations_; } virtual int get_simulation_stats_every_n_iterations() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return simulation_stats_every_n_iterations; } bool rxn_probability_changed; virtual void set_rxn_probability_changed(const bool new_rxn_probability_changed_) { if (initialized) { throw RuntimeError("Value 'rxn_probability_changed' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rxn_probability_changed = new_rxn_probability_changed_; } virtual bool get_rxn_probability_changed() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rxn_probability_changed; } bool iteration_report; virtual void set_iteration_report(const bool new_iteration_report_) { if (initialized) { throw RuntimeError("Value 'iteration_report' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; iteration_report = new_iteration_report_; } virtual bool get_iteration_report() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return iteration_report; } bool wall_overlap_report; virtual void set_wall_overlap_report(const bool new_wall_overlap_report_) { if (initialized) { throw RuntimeError("Value 'wall_overlap_report' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_overlap_report = new_wall_overlap_report_; } virtual bool get_wall_overlap_report() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_overlap_report; } // --- methods --- }; // GenNotifications class Notifications; py::class_<Notifications> define_pybinding_Notifications(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_NOTIFICATIONS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_species.cpp
.cpp
12,379
246
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_species.h" #include "api/species.h" #include "api/complex.h" #include "api/elementary_molecule.h" #include "api/species.h" namespace MCell { namespace API { void GenSpecies::check_semantics() const { } void GenSpecies::set_initialized() { vec_set_initialized(elementary_molecules); initialized = true; } void GenSpecies::set_all_attributes_as_default_or_unset() { class_name = "Species"; name = STR_UNSET; diffusion_constant_2d = FLT_UNSET; diffusion_constant_3d = FLT_UNSET; custom_time_step = FLT_UNSET; custom_space_step = FLT_UNSET; target_only = false; name = STR_UNSET; elementary_molecules = std::vector<std::shared_ptr<ElementaryMolecule>>(); orientation = Orientation::DEFAULT; compartment_name = STR_UNSET; } std::shared_ptr<Species> GenSpecies::copy_species() const { std::shared_ptr<Species> res = std::make_shared<Species>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->diffusion_constant_2d = diffusion_constant_2d; res->diffusion_constant_3d = diffusion_constant_3d; res->custom_time_step = custom_time_step; res->custom_space_step = custom_space_step; res->target_only = target_only; res->name = name; res->elementary_molecules = elementary_molecules; res->orientation = orientation; res->compartment_name = compartment_name; return res; } std::shared_ptr<Species> GenSpecies::deepcopy_species(py::dict) const { std::shared_ptr<Species> res = std::make_shared<Species>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->diffusion_constant_2d = diffusion_constant_2d; res->diffusion_constant_3d = diffusion_constant_3d; res->custom_time_step = custom_time_step; res->custom_space_step = custom_space_step; res->target_only = target_only; res->name = name; for (const auto& item: elementary_molecules) { res->elementary_molecules.push_back((is_set(item)) ? item->deepcopy_elementary_molecule() : nullptr); } res->orientation = orientation; res->compartment_name = compartment_name; return res; } bool GenSpecies::__eq__(const Species& other) const { return name == other.name && diffusion_constant_2d == other.diffusion_constant_2d && diffusion_constant_3d == other.diffusion_constant_3d && custom_time_step == other.custom_time_step && custom_space_step == other.custom_space_step && target_only == other.target_only && name == other.name && vec_ptr_eq(elementary_molecules, other.elementary_molecules) && orientation == other.orientation && compartment_name == other.compartment_name; } bool GenSpecies::eq_nonarray_attributes(const Species& other, const bool ignore_name) const { return (ignore_name || name == other.name) && diffusion_constant_2d == other.diffusion_constant_2d && diffusion_constant_3d == other.diffusion_constant_3d && custom_time_step == other.custom_time_step && custom_space_step == other.custom_space_step && target_only == other.target_only && (ignore_name || name == other.name) && true /*elementary_molecules*/ && orientation == other.orientation && compartment_name == other.compartment_name; } std::string GenSpecies::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "diffusion_constant_2d=" << diffusion_constant_2d << ", " << "diffusion_constant_3d=" << diffusion_constant_3d << ", " << "custom_time_step=" << custom_time_step << ", " << "custom_space_step=" << custom_space_step << ", " << "target_only=" << target_only << ", " << "name=" << name << ", " << "\n" << ind + " " << "elementary_molecules=" << vec_ptr_to_str(elementary_molecules, all_details, ind + " ") << ", " << "\n" << ind + " " << "orientation=" << orientation << ", " << "compartment_name=" << compartment_name; return ss.str(); } py::class_<Species> define_pybinding_Species(py::module& m) { return py::class_<Species, Complex, std::shared_ptr<Species>>(m, "Species", "There are three ways how to use this class:\n1) definition of simple species - in this case 'name' is \na single identifier and at least 'diffusion_constant_2d' or \n'diffusion_constant_3d' must be provided.\nExample: m.Species('A', diffusion_constant_3d=1e-6). \nSuch a definition must be added to subsystem or model so that \nduring model initialization this species is transformed to MCell \nrepresentation and an ElementaryMoleculeType 'A' with a given \ndiffusion constant is created as well.\n2) full definition of complex species - in this case the \ninherited attribute 'elementary_molecules' from Complex\nis used as a definition of the complex and this gives information \non diffusion constants of the used elementary molecules.\nExample: m.Species(elementary_molecules=[ei1, ei2]). \nSuch a definition must be added to subsystem or model. \n3) declaration of species - in this case only 'name' in the form of \nan BNGL string is provided. The complex instance specified by the name \nmust be fully qualified (i.e. all components are present and those \ncomponents that have a state have their state set).\nNo information on diffusion constants and other properties of \nused elementary molecules is provided, it must be provided elsewhere.\nExample: m.Species('A(b!1).B(a!1)').\nThis is a common form of usage when reaction rules are provided in a BNGL file.\nSuch declaration does no need to be added to subsystem or model.\nThis form is used as argument in cases where a fully qualified instance \nmust be provided such as in molecule releases.\n \n") .def( py::init< const std::string&, const double, const double, const double, const double, const bool, const std::vector<std::shared_ptr<ElementaryMolecule>>, const Orientation, const std::string& >(), py::arg("name") = STR_UNSET, py::arg("diffusion_constant_2d") = FLT_UNSET, py::arg("diffusion_constant_3d") = FLT_UNSET, py::arg("custom_time_step") = FLT_UNSET, py::arg("custom_space_step") = FLT_UNSET, py::arg("target_only") = false, py::arg("elementary_molecules") = std::vector<std::shared_ptr<ElementaryMolecule>>(), py::arg("orientation") = Orientation::DEFAULT, py::arg("compartment_name") = STR_UNSET ) .def("check_semantics", &Species::check_semantics) .def("__copy__", &Species::copy_species) .def("__deepcopy__", &Species::deepcopy_species, py::arg("memo")) .def("__str__", &Species::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Species::__eq__, py::arg("other")) .def("inst", &Species::inst, py::arg("orientation") = Orientation::DEFAULT, py::arg("compartment_name") = STR_UNSET, "Creates a copy of a Complex from this Species with specified orientation and compartment name. \n\n- orientation: Maximum one of orientation or compartment_name can be set, not both.\n\n- compartment_name: Maximum one of orientation or compartment_name can be set, not both.\n\n") .def("dump", &Species::dump) .def_property("name", &Species::get_name, &Species::set_name, "Name of the species in the BNGL format. \nOne must either specify name or elementary_molecules (inherited from Complex). \nThis argument name is parsed during model initialization. \n") .def_property("diffusion_constant_2d", &Species::get_diffusion_constant_2d, &Species::set_diffusion_constant_2d, "This molecule is constrained to surface with diffusion constant D. \nD can be zero, in which case the molecule doesn’t move. \nThe units of D are cm^2/s.\n") .def_property("diffusion_constant_3d", &Species::get_diffusion_constant_3d, &Species::set_diffusion_constant_3d, "This molecule diffuses in space with diffusion constant D. \nD can be zero, in which case the molecule doesn’t move. \nThe units of D are cm^2/s.\n \n") .def_property("custom_time_step", &Species::get_custom_time_step, &Species::set_custom_time_step, "Optional setting of a custom time step for this specific species. \nA molecule of this species should take timesteps of length custom_time_step (in seconds). \nUse either this or custom_time_step.\n") .def_property("custom_space_step", &Species::get_custom_space_step, &Species::set_custom_space_step, "Optional setting of a custom space step for this specific species. \nA molecule of this species should take steps of average length custom_space_step (in microns). \nUse either this or custom_time_step.\n \n") .def_property("target_only", &Species::get_target_only, &Species::set_target_only, "A molecule of this species will not initiate reactions when it runs into other molecules. This\nsetting can speed up simulations when applied to a molecule at high concentrations \nthat reacts with a molecule at low concentrations (it is more efficient for\nthe low-concentration molecule to trigger the reactions). This directive does\nnot affect unimolecular reactions.\n") ; } std::string GenSpecies::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("species") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("species"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Species(" << nl; if (name != STR_UNSET) { ss << ind << "name = " << "'" << name << "'" << "," << nl; } if (elementary_molecules != std::vector<std::shared_ptr<ElementaryMolecule>>() && !skip_vectors_export()) { ss << ind << "elementary_molecules = " << export_vec_elementary_molecules(out, ctx, exported_name) << "," << nl; } if (orientation != Orientation::DEFAULT) { ss << ind << "orientation = " << orientation << "," << nl; } if (compartment_name != STR_UNSET) { ss << ind << "compartment_name = " << "'" << compartment_name << "'" << "," << nl; } if (diffusion_constant_2d != FLT_UNSET) { ss << ind << "diffusion_constant_2d = " << f_to_str(diffusion_constant_2d) << "," << nl; } if (diffusion_constant_3d != FLT_UNSET) { ss << ind << "diffusion_constant_3d = " << f_to_str(diffusion_constant_3d) << "," << nl; } if (custom_time_step != FLT_UNSET) { ss << ind << "custom_time_step = " << f_to_str(custom_time_step) << "," << nl; } if (custom_space_step != FLT_UNSET) { ss << ind << "custom_space_step = " << f_to_str(custom_space_step) << "," << nl; } if (target_only != false) { ss << ind << "target_only = " << target_only << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenSpecies::export_vec_elementary_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < elementary_molecules.size(); i++) { const auto& item = elementary_molecules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_release_pattern.cpp
.cpp
6,584
167
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_release_pattern.h" #include "api/release_pattern.h" namespace MCell { namespace API { void GenReleasePattern::check_semantics() const { } void GenReleasePattern::set_initialized() { initialized = true; } void GenReleasePattern::set_all_attributes_as_default_or_unset() { class_name = "ReleasePattern"; name = STR_UNSET; release_interval = TIME_INFINITY; train_duration = TIME_INFINITY; train_interval = TIME_INFINITY; number_of_trains = 1; } std::shared_ptr<ReleasePattern> GenReleasePattern::copy_release_pattern() const { std::shared_ptr<ReleasePattern> res = std::make_shared<ReleasePattern>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->release_interval = release_interval; res->train_duration = train_duration; res->train_interval = train_interval; res->number_of_trains = number_of_trains; return res; } std::shared_ptr<ReleasePattern> GenReleasePattern::deepcopy_release_pattern(py::dict) const { std::shared_ptr<ReleasePattern> res = std::make_shared<ReleasePattern>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->release_interval = release_interval; res->train_duration = train_duration; res->train_interval = train_interval; res->number_of_trains = number_of_trains; return res; } bool GenReleasePattern::__eq__(const ReleasePattern& other) const { return name == other.name && release_interval == other.release_interval && train_duration == other.train_duration && train_interval == other.train_interval && number_of_trains == other.number_of_trains; } bool GenReleasePattern::eq_nonarray_attributes(const ReleasePattern& other, const bool ignore_name) const { return (ignore_name || name == other.name) && release_interval == other.release_interval && train_duration == other.train_duration && train_interval == other.train_interval && number_of_trains == other.number_of_trains; } std::string GenReleasePattern::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "release_interval=" << release_interval << ", " << "train_duration=" << train_duration << ", " << "train_interval=" << train_interval << ", " << "number_of_trains=" << number_of_trains; return ss.str(); } py::class_<ReleasePattern> define_pybinding_ReleasePattern(py::module& m) { return py::class_<ReleasePattern, std::shared_ptr<ReleasePattern>>(m, "ReleasePattern", "Defines a release pattern that specifies repeating molecule releases. \nCan be used by a ReleaseSite.\n") .def( py::init< const std::string&, const double, const double, const double, const int >(), py::arg("name") = STR_UNSET, py::arg("release_interval") = TIME_INFINITY, py::arg("train_duration") = TIME_INFINITY, py::arg("train_interval") = TIME_INFINITY, py::arg("number_of_trains") = 1 ) .def("check_semantics", &ReleasePattern::check_semantics) .def("__copy__", &ReleasePattern::copy_release_pattern) .def("__deepcopy__", &ReleasePattern::deepcopy_release_pattern, py::arg("memo")) .def("__str__", &ReleasePattern::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ReleasePattern::__eq__, py::arg("other")) .def("dump", &ReleasePattern::dump) .def_property("name", &ReleasePattern::get_name, &ReleasePattern::set_name, "Name of the release pattern.") .def_property("release_interval", &ReleasePattern::get_release_interval, &ReleasePattern::set_release_interval, "During a train of releases, release molecules after every t seconds. \nDefault is to release only once.\n") .def_property("train_duration", &ReleasePattern::get_train_duration, &ReleasePattern::set_train_duration, "The train of releases lasts for t seconds before turning off. \nDefault is to never turn off.\n") .def_property("train_interval", &ReleasePattern::get_train_interval, &ReleasePattern::set_train_interval, "A new train of releases happens every t seconds. \nDefault is to never have a new train. \nThe train interval must not be shorter than the train duration.\n") .def_property("number_of_trains", &ReleasePattern::get_number_of_trains, &ReleasePattern::set_number_of_trains, "Repeat the release process for n trains of releases. Default is one train.\nFor unlimited number of trains use a constant NUMBER_OF_TRAINS_UNLIMITED.\n") ; } std::string GenReleasePattern::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("release_pattern") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("release_pattern"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ReleasePattern(" << nl; if (name != STR_UNSET) { ss << ind << "name = " << "'" << name << "'" << "," << nl; } if (release_interval != TIME_INFINITY) { ss << ind << "release_interval = " << f_to_str(release_interval) << "," << nl; } if (train_duration != TIME_INFINITY) { ss << ind << "train_duration = " << f_to_str(train_duration) << "," << nl; } if (train_interval != TIME_INFINITY) { ss << ind << "train_interval = " << f_to_str(train_interval) << "," << nl; } if (number_of_trains != 1) { ss << ind << "number_of_trains = " << number_of_trains << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_subsystem.h
.h
5,134
116
/****************************************************************************** * * Copyright (C) 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 API_GEN_SUBSYSTEM_H #define API_GEN_SUBSYSTEM_H #include "api/api_common.h" #include "api/base_export_class.h" namespace MCell { namespace API { class Subsystem; class ElementaryMoleculeType; class ReactionRule; class Species; class SurfaceClass; class PythonExportContext; #define SUBSYSTEM_CTOR() \ Subsystem( \ const std::vector<std::shared_ptr<Species>> species_ = std::vector<std::shared_ptr<Species>>(), \ const std::vector<std::shared_ptr<ReactionRule>> reaction_rules_ = std::vector<std::shared_ptr<ReactionRule>>(), \ const std::vector<std::shared_ptr<SurfaceClass>> surface_classes_ = std::vector<std::shared_ptr<SurfaceClass>>(), \ const std::vector<std::shared_ptr<ElementaryMoleculeType>> elementary_molecule_types_ = std::vector<std::shared_ptr<ElementaryMoleculeType>>() \ ) { \ species = species_; \ reaction_rules = reaction_rules_; \ surface_classes = surface_classes_; \ elementary_molecule_types = elementary_molecule_types_; \ } \ Subsystem(DefaultCtorArgType){ \ } class GenSubsystem: public BaseExportClass { public: GenSubsystem() { } GenSubsystem(DefaultCtorArgType) { } virtual ~GenSubsystem() {} std::shared_ptr<Subsystem> copy_subsystem() const; std::shared_ptr<Subsystem> deepcopy_subsystem(py::dict = py::dict()) const; virtual bool __eq__(const Subsystem& other) const; virtual bool eq_nonarray_attributes(const Subsystem& other, const bool ignore_name = false) const; bool operator == (const Subsystem& other) const { return __eq__(other);} bool operator != (const Subsystem& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_species(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_reaction_rules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_surface_classes(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_elementary_molecule_types(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<Species>> species; virtual void set_species(const std::vector<std::shared_ptr<Species>> new_species_) { species = new_species_; } virtual std::vector<std::shared_ptr<Species>>& get_species() { return species; } std::vector<std::shared_ptr<ReactionRule>> reaction_rules; virtual void set_reaction_rules(const std::vector<std::shared_ptr<ReactionRule>> new_reaction_rules_) { reaction_rules = new_reaction_rules_; } virtual std::vector<std::shared_ptr<ReactionRule>>& get_reaction_rules() { return reaction_rules; } std::vector<std::shared_ptr<SurfaceClass>> surface_classes; virtual void set_surface_classes(const std::vector<std::shared_ptr<SurfaceClass>> new_surface_classes_) { surface_classes = new_surface_classes_; } virtual std::vector<std::shared_ptr<SurfaceClass>>& get_surface_classes() { return surface_classes; } std::vector<std::shared_ptr<ElementaryMoleculeType>> elementary_molecule_types; virtual void set_elementary_molecule_types(const std::vector<std::shared_ptr<ElementaryMoleculeType>> new_elementary_molecule_types_) { elementary_molecule_types = new_elementary_molecule_types_; } virtual std::vector<std::shared_ptr<ElementaryMoleculeType>>& get_elementary_molecule_types() { return elementary_molecule_types; } // --- methods --- virtual void add_species(std::shared_ptr<Species> s) = 0; virtual std::shared_ptr<Species> find_species(const std::string& name) = 0; virtual void add_reaction_rule(std::shared_ptr<ReactionRule> r) = 0; virtual std::shared_ptr<ReactionRule> find_reaction_rule(const std::string& name) = 0; virtual void add_surface_class(std::shared_ptr<SurfaceClass> sc) = 0; virtual std::shared_ptr<SurfaceClass> find_surface_class(const std::string& name) = 0; virtual void add_elementary_molecule_type(std::shared_ptr<ElementaryMoleculeType> mt) = 0; virtual std::shared_ptr<ElementaryMoleculeType> find_elementary_molecule_type(const std::string& name) = 0; virtual void load_bngl_molecule_types_and_reaction_rules(const std::string& file_name, const std::map<std::string, double>& parameter_overrides = std::map<std::string, double>()) = 0; }; // GenSubsystem class Subsystem; py::class_<Subsystem> define_pybinding_Subsystem(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_SUBSYSTEM_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_constants.h
.h
8,439
294
/****************************************************************************** * * Copyright (C) 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 API_GEN_CONSTANTS #define API_GEN_CONSTANTS #include <string> #include <climits> #include <cfloat> #include "api/globals.h" namespace MCell { namespace API { const std::string STATE_UNSET = "STATE_UNSET"; const int STATE_UNSET_INT = -1; const int BOND_UNBOUND = -1; const int BOND_BOUND = -2; const int BOND_ANY = -3; const double PARTITION_EDGE_EXTRA_MARGIN_UM = 0.01; const int DEFAULT_COUNT_BUFFER_SIZE = 100; const std::string ALL_MOLECULES = "ALL_MOLECULES"; const std::string ALL_VOLUME_MOLECULES = "ALL_VOLUME_MOLECULES"; const std::string ALL_SURFACE_MOLECULES = "ALL_SURFACE_MOLECULES"; const std::string DEFAULT_CHECKPOINTS_DIR = "checkpoints"; const std::string DEFAULT_SEED_DIR_PREFIX = "seed_"; const int DEFAULT_SEED_DIR_DIGITS = 5; const std::string DEFAULT_ITERATION_DIR_PREFIX = "it_"; const int ID_INVALID = -1; const int NUMBER_OF_TRAINS_UNLIMITED = -1; const double TIME_INFINITY = 1e140; const int INT_UNSET = INT32_MAX; const double FLT_UNSET = FLT_MAX; const int RNG_SIZE = 256; enum class Orientation { DOWN = -1, NONE = 0, UP = 1, NOT_SET = 2, ANY = 3, DEFAULT = 4 }; static inline std::ostream& operator << (std::ostream& out, const Orientation v) { switch (v) { case Orientation::DOWN: out << "m.Orientation.DOWN"; break; case Orientation::NONE: out << "m.Orientation.NONE"; break; case Orientation::UP: out << "m.Orientation.UP"; break; case Orientation::NOT_SET: out << "m.Orientation.NOT_SET"; break; case Orientation::ANY: out << "m.Orientation.ANY"; break; case Orientation::DEFAULT: out << "m.Orientation.DEFAULT"; break; } return out; }; enum class Notification { NONE = 0, BRIEF = 1, FULL = 2 }; static inline std::ostream& operator << (std::ostream& out, const Notification v) { switch (v) { case Notification::NONE: out << "m.Notification.NONE"; break; case Notification::BRIEF: out << "m.Notification.BRIEF"; break; case Notification::FULL: out << "m.Notification.FULL"; break; } return out; }; enum class WarningLevel { IGNORE = 0, WARNING = 1, ERROR = 2 }; static inline std::ostream& operator << (std::ostream& out, const WarningLevel v) { switch (v) { case WarningLevel::IGNORE: out << "m.WarningLevel.IGNORE"; break; case WarningLevel::WARNING: out << "m.WarningLevel.WARNING"; break; case WarningLevel::ERROR: out << "m.WarningLevel.ERROR"; break; } return out; }; enum class VizMode { ASCII = 0, CELLBLENDER_V1 = 1, CELLBLENDER = 2 }; static inline std::ostream& operator << (std::ostream& out, const VizMode v) { switch (v) { case VizMode::ASCII: out << "m.VizMode.ASCII"; break; case VizMode::CELLBLENDER_V1: out << "m.VizMode.CELLBLENDER_V1"; break; case VizMode::CELLBLENDER: out << "m.VizMode.CELLBLENDER"; break; } return out; }; enum class Shape { UNSET = 0, SPHERICAL = 1, REGION_EXPR = 2, LIST = 3, COMPARTMENT = 4 }; static inline std::ostream& operator << (std::ostream& out, const Shape v) { switch (v) { case Shape::UNSET: out << "m.Shape.UNSET"; break; case Shape::SPHERICAL: out << "m.Shape.SPHERICAL"; break; case Shape::REGION_EXPR: out << "m.Shape.REGION_EXPR"; break; case Shape::LIST: out << "m.Shape.LIST"; break; case Shape::COMPARTMENT: out << "m.Shape.COMPARTMENT"; break; } return out; }; enum class SurfacePropertyType { UNSET = 0, REACTIVE = 1, REFLECTIVE = 2, TRANSPARENT = 3, ABSORPTIVE = 4, CONCENTRATION_CLAMP = 5, FLUX_CLAMP = 6 }; static inline std::ostream& operator << (std::ostream& out, const SurfacePropertyType v) { switch (v) { case SurfacePropertyType::UNSET: out << "m.SurfacePropertyType.UNSET"; break; case SurfacePropertyType::REACTIVE: out << "m.SurfacePropertyType.REACTIVE"; break; case SurfacePropertyType::REFLECTIVE: out << "m.SurfacePropertyType.REFLECTIVE"; break; case SurfacePropertyType::TRANSPARENT: out << "m.SurfacePropertyType.TRANSPARENT"; break; case SurfacePropertyType::ABSORPTIVE: out << "m.SurfacePropertyType.ABSORPTIVE"; break; case SurfacePropertyType::CONCENTRATION_CLAMP: out << "m.SurfacePropertyType.CONCENTRATION_CLAMP"; break; case SurfacePropertyType::FLUX_CLAMP: out << "m.SurfacePropertyType.FLUX_CLAMP"; break; } return out; }; enum class ExprNodeType { UNSET = 0, LEAF = 1, ADD = 2, SUB = 3 }; static inline std::ostream& operator << (std::ostream& out, const ExprNodeType v) { switch (v) { case ExprNodeType::UNSET: out << "m.ExprNodeType.UNSET"; break; case ExprNodeType::LEAF: out << "m.ExprNodeType.LEAF"; break; case ExprNodeType::ADD: out << "m.ExprNodeType.ADD"; break; case ExprNodeType::SUB: out << "m.ExprNodeType.SUB"; break; } return out; }; enum class RegionNodeType { UNSET = 0, LEAF_GEOMETRY_OBJECT = 1, LEAF_SURFACE_REGION = 2, UNION = 3, DIFFERENCE = 4, INTERSECT = 5 }; static inline std::ostream& operator << (std::ostream& out, const RegionNodeType v) { switch (v) { case RegionNodeType::UNSET: out << "m.RegionNodeType.UNSET"; break; case RegionNodeType::LEAF_GEOMETRY_OBJECT: out << "m.RegionNodeType.LEAF_GEOMETRY_OBJECT"; break; case RegionNodeType::LEAF_SURFACE_REGION: out << "m.RegionNodeType.LEAF_SURFACE_REGION"; break; case RegionNodeType::UNION: out << "m.RegionNodeType.UNION"; break; case RegionNodeType::DIFFERENCE: out << "m.RegionNodeType.DIFFERENCE"; break; case RegionNodeType::INTERSECT: out << "m.RegionNodeType.INTERSECT"; break; } return out; }; enum class ReactionType { UNSET = 0, UNIMOL_VOLUME = 1, UNIMOL_SURFACE = 2, VOLUME_VOLUME = 3, VOLUME_SURFACE = 4, SURFACE_SURFACE = 5 }; static inline std::ostream& operator << (std::ostream& out, const ReactionType v) { switch (v) { case ReactionType::UNSET: out << "m.ReactionType.UNSET"; break; case ReactionType::UNIMOL_VOLUME: out << "m.ReactionType.UNIMOL_VOLUME"; break; case ReactionType::UNIMOL_SURFACE: out << "m.ReactionType.UNIMOL_SURFACE"; break; case ReactionType::VOLUME_VOLUME: out << "m.ReactionType.VOLUME_VOLUME"; break; case ReactionType::VOLUME_SURFACE: out << "m.ReactionType.VOLUME_SURFACE"; break; case ReactionType::SURFACE_SURFACE: out << "m.ReactionType.SURFACE_SURFACE"; break; } return out; }; enum class MoleculeType { UNSET = 0, VOLUME = 1, SURFACE = 2 }; static inline std::ostream& operator << (std::ostream& out, const MoleculeType v) { switch (v) { case MoleculeType::UNSET: out << "m.MoleculeType.UNSET"; break; case MoleculeType::VOLUME: out << "m.MoleculeType.VOLUME"; break; case MoleculeType::SURFACE: out << "m.MoleculeType.SURFACE"; break; } return out; }; enum class BNGSimulationMethod { NONE = 0, ODE = 1, SSA = 2, PLA = 3, NF = 4 }; static inline std::ostream& operator << (std::ostream& out, const BNGSimulationMethod v) { switch (v) { case BNGSimulationMethod::NONE: out << "m.BNGSimulationMethod.NONE"; break; case BNGSimulationMethod::ODE: out << "m.BNGSimulationMethod.ODE"; break; case BNGSimulationMethod::SSA: out << "m.BNGSimulationMethod.SSA"; break; case BNGSimulationMethod::PLA: out << "m.BNGSimulationMethod.PLA"; break; case BNGSimulationMethod::NF: out << "m.BNGSimulationMethod.NF"; break; } return out; }; enum class CountOutputFormat { UNSET = 0, AUTOMATIC_FROM_EXTENSION = 1, DAT = 2, GDAT = 3 }; static inline std::ostream& operator << (std::ostream& out, const CountOutputFormat v) { switch (v) { case CountOutputFormat::UNSET: out << "m.CountOutputFormat.UNSET"; break; case CountOutputFormat::AUTOMATIC_FROM_EXTENSION: out << "m.CountOutputFormat.AUTOMATIC_FROM_EXTENSION"; break; case CountOutputFormat::DAT: out << "m.CountOutputFormat.DAT"; break; case CountOutputFormat::GDAT: out << "m.CountOutputFormat.GDAT"; break; } return out; }; void define_pybinding_constants(py::module& m); void define_pybinding_enums(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_CONSTANTS
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_model.cpp
.cpp
46,902
564
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_model.h" #include "api/model.h" #include "api/base_chkpt_mol.h" #include "api/color.h" #include "api/complex.h" #include "api/api_config.h" #include "api/count.h" #include "api/elementary_molecule_type.h" #include "api/geometry_object.h" #include "api/instantiation.h" #include "api/mol_wall_hit_info.h" #include "api/molecule.h" #include "api/notifications.h" #include "api/observables.h" #include "api/reaction_info.h" #include "api/reaction_rule.h" #include "api/region.h" #include "api/release_site.h" #include "api/species.h" #include "api/subsystem.h" #include "api/surface_class.h" #include "api/viz_output.h" #include "api/wall.h" #include "api/wall_wall_hit_info.h" #include "api/warnings.h" namespace MCell { namespace API { std::shared_ptr<Model> GenModel::copy_model() const { std::shared_ptr<Model> res = std::make_shared<Model>(DefaultCtorArgType()); res->config = config; res->warnings = warnings; res->notifications = notifications; res->species = species; res->reaction_rules = reaction_rules; res->surface_classes = surface_classes; res->elementary_molecule_types = elementary_molecule_types; res->release_sites = release_sites; res->geometry_objects = geometry_objects; res->checkpointed_molecules = checkpointed_molecules; res->viz_outputs = viz_outputs; res->counts = counts; return res; } std::shared_ptr<Model> GenModel::deepcopy_model(py::dict) const { std::shared_ptr<Model> res = std::make_shared<Model>(DefaultCtorArgType()); res->config = config; res->warnings = warnings; res->notifications = notifications; for (const auto& item: species) { res->species.push_back((is_set(item)) ? item->deepcopy_species() : nullptr); } for (const auto& item: reaction_rules) { res->reaction_rules.push_back((is_set(item)) ? item->deepcopy_reaction_rule() : nullptr); } for (const auto& item: surface_classes) { res->surface_classes.push_back((is_set(item)) ? item->deepcopy_surface_class() : nullptr); } for (const auto& item: elementary_molecule_types) { res->elementary_molecule_types.push_back((is_set(item)) ? item->deepcopy_elementary_molecule_type() : nullptr); } for (const auto& item: release_sites) { res->release_sites.push_back((is_set(item)) ? item->deepcopy_release_site() : nullptr); } for (const auto& item: geometry_objects) { res->geometry_objects.push_back((is_set(item)) ? item->deepcopy_geometry_object() : nullptr); } for (const auto& item: checkpointed_molecules) { res->checkpointed_molecules.push_back((is_set(item)) ? item->deepcopy_base_chkpt_mol() : nullptr); } for (const auto& item: viz_outputs) { res->viz_outputs.push_back((is_set(item)) ? item->deepcopy_viz_output() : nullptr); } for (const auto& item: counts) { res->counts.push_back((is_set(item)) ? item->deepcopy_count() : nullptr); } return res; } bool GenModel::__eq__(const Model& other) const { return config == other.config && warnings == other.warnings && notifications == other.notifications && vec_ptr_eq(species, other.species) && vec_ptr_eq(reaction_rules, other.reaction_rules) && vec_ptr_eq(surface_classes, other.surface_classes) && vec_ptr_eq(elementary_molecule_types, other.elementary_molecule_types) && vec_ptr_eq(release_sites, other.release_sites) && vec_ptr_eq(geometry_objects, other.geometry_objects) && vec_ptr_eq(checkpointed_molecules, other.checkpointed_molecules) && vec_ptr_eq(viz_outputs, other.viz_outputs) && vec_ptr_eq(counts, other.counts); } bool GenModel::eq_nonarray_attributes(const Model& other, const bool ignore_name) const { return config == other.config && warnings == other.warnings && notifications == other.notifications && true /*species*/ && true /*reaction_rules*/ && true /*surface_classes*/ && true /*elementary_molecule_types*/ && true /*release_sites*/ && true /*geometry_objects*/ && true /*checkpointed_molecules*/ && true /*viz_outputs*/ && true /*counts*/; } std::string GenModel::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << "Model" << ": " << "\n" << ind + " " << "config=" << "(" << config.to_str(all_details, ind + " ") << ")" << ", " << "\n" << ind + " " << "warnings=" << "(" << warnings.to_str(all_details, ind + " ") << ")" << ", " << "\n" << ind + " " << "notifications=" << "(" << notifications.to_str(all_details, ind + " ") << ")" << ", " << "\n" << ind + " " << "species=" << vec_ptr_to_str(species, all_details, ind + " ") << ", " << "\n" << ind + " " << "reaction_rules=" << vec_ptr_to_str(reaction_rules, all_details, ind + " ") << ", " << "\n" << ind + " " << "surface_classes=" << vec_ptr_to_str(surface_classes, all_details, ind + " ") << ", " << "\n" << ind + " " << "elementary_molecule_types=" << vec_ptr_to_str(elementary_molecule_types, all_details, ind + " ") << ", " << "\n" << ind + " " << "release_sites=" << vec_ptr_to_str(release_sites, all_details, ind + " ") << ", " << "\n" << ind + " " << "geometry_objects=" << vec_ptr_to_str(geometry_objects, all_details, ind + " ") << ", " << "\n" << ind + " " << "checkpointed_molecules=" << vec_ptr_to_str(checkpointed_molecules, all_details, ind + " ") << ", " << "\n" << ind + " " << "viz_outputs=" << vec_ptr_to_str(viz_outputs, all_details, ind + " ") << ", " << "\n" << ind + " " << "counts=" << vec_ptr_to_str(counts, all_details, ind + " "); return ss.str(); } py::class_<Model> define_pybinding_Model(py::module& m) { return py::class_<Model, std::shared_ptr<Model>>(m, "Model", "This is the main class that is used to assemble all simulation input \nand configuration. It also provides methods to do initialization,\nrun simulation, and introspect the running simulation.\n") .def( py::init< >() ) .def("__copy__", &Model::copy_model) .def("__deepcopy__", &Model::deepcopy_model, py::arg("memo")) .def("__str__", &Model::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Model::__eq__, py::arg("other")) .def("initialize", &Model::initialize, py::arg("print_copyright") = true, "Initializes model, initialization blocks most of changes to \ncontained components. \n\n- print_copyright: Prints information about MCell.\n\n") .def("run_iterations", &Model::run_iterations, py::arg("iterations"), "Runs specified number of iterations. Returns the number of iterations\nexecuted (it might be less than the requested number of iterations when \na checkpoint was scheduled). \n\n- iterations: Number of iterations to run. Value is truncated to an integer.\n\n") .def("end_simulation", &Model::end_simulation, py::arg("print_final_report") = true, "Generates the last visualization and reaction output (if they are included \nin the model), then flushes all buffers and optionally prints simulation report. \nBuffers are also flushed when the Model object is destroyed such as when Ctrl-C\nis pressed during simulation. \n\n- print_final_report: Print information on simulation time and counts of selected events.\n\n") .def("add_subsystem", &Model::add_subsystem, py::arg("subsystem"), "Adds all components of a Subsystem object to the model.\n- subsystem\n") .def("add_instantiation", &Model::add_instantiation, py::arg("instantiation"), "Adds all components of an Instantiation object to the model.\n- instantiation\n") .def("add_observables", &Model::add_observables, py::arg("observables"), "Adds all counts and viz outputs of an Observables object to the model.\n- observables\n") .def("dump_internal_state", &Model::dump_internal_state, py::arg("with_geometry") = false, "Prints out the simulation engine's internal state, mainly for debugging.\n- with_geometry: Include geometry in the dump.\n\n") .def("export_data_model", &Model::export_data_model, py::arg("file") = STR_UNSET, "Exports the current state of the model into a data model JSON format.\nDoes not export state of molecules.\nMust be called after model initialization.\nAlways exports the current state, i.e. with the current geometry and reaction rates. \nEvents (ReleaseSites and VizOutputs) with scheduled time other than zero are not exported correctly yet. \n\n- file: If file is not set, then uses the first VizOutput to determine the target directory \nand creates name using the current iteration. Fails if argument file is not set and \nthere is no VizOutput in the model.\n\n\n") .def("export_viz_data_model", &Model::export_viz_data_model, py::arg("file") = STR_UNSET, "Same as export_data_model, only the created data model will contain only information required for visualization\nin CellBlender. This makes the loading of the model by CellBlender faster and also allows to avoid potential\ncompatibility issues.\nMust be called after model initialization.\n\n- file: Optional path to the output data model file.\n\n") .def("export_geometry", &Model::export_geometry, py::arg("output_files_prefix") = STR_UNSET, "Exports model geometry as Wavefront OBJ format. \nMust be called after model initialization.\nDoes not export material colors (yet).\n\n- output_files_prefix: Optional prefix for .obj and .mtl files that will be created on export. \nIf output_files_prefix is not set, then uses the first VizOutput to determine the target directory \nand creates names using the current iteration. Fails if argument output_files_prefix is not set and \nthere is no VizOutput in the model.\n\n\n") .def("release_molecules", &Model::release_molecules, py::arg("release_site"), "Performs immediate release of molecules based on the definition of the release site argument.\nThe ReleaseSite.release_time must not be in the past and must be within the current iteration \nmeaning that the time must be greater or equal iteration * time_step and less than (iteration + 1) * time_step.\nThe ReleaseEvent must not use a release_pattern because this is an immediate release and it is not \nscheduled into the global scheduler.\n\n- release_site\n") .def("run_reaction", &Model::run_reaction, py::arg("reaction_rule"), py::arg("reactant_ids"), py::arg("time"), "Run a single reaction on reactants. Callbacks will be called if they are registered for the given reaction.\nReturns a list of product IDs.\nNote: only unimolecular reactions are currently supported.\n\n- reaction_rule: Reaction rule to run.\n\n- reactant_ids: The number of reactants for a unimolecular reaction must be 1 and for a bimolecular reaction must be 2.\nReactants for a bimolecular reaction do not have to be listed in the same order as in the reaction rule definition. \n\n\n- time: Precise time in seconds when this reaction occurs. Important to know for how long the products\nwill be diffused when they are created in a middle of a time step. \n\n\n") .def("add_vertex_move", &Model::add_vertex_move, py::arg("object"), py::arg("vertex_index"), py::arg("displacement"), "Appends information about a displacement for given object's vertex into an internal list of vertex moves. \nTo do the actual geometry change, call Model.apply_vertex_moves.\nThe reason why we first need to collect all changes and then apply them all at the same time is for performance\nreasons. \n\n- object: Object whose vertex will be changed.\n\n- vertex_index: Index of vertex in object's vertex list that will be changed.\n\n- displacement: Change of vertex coordinates [x, y, z] (in um) that will be added to the current \ncoordinates of the vertex.\n\n\n") .def("apply_vertex_moves", &Model::apply_vertex_moves, py::arg("collect_wall_wall_hits") = false, py::arg("randomize_order") = true, "Applies all the vertex moves specified with Model.add_vertex_move call.\n\nAll affected vertices are first divided based on to which geometery object they belong. \nThen each object is manipulated one by one. \n\nDuring vertex moves, collisions are checked:\na) When a moved vertex hits a wall of another object, it is stopped at the wall.\nb) When a second object's vertex would end up inside the moved object, the vertex move \nthat would cause it is canceled (its displacement set to 0) because finding the maximum \ndistance we can move is too computationally expensive. To minimize the impact of this \ncancellation, the vertices should be moved only by a small distance.\n\nApplying vertex moves also takes paired molecules into account: \nWhen moves are applied to an object, all moved molecules that are paired are collected.\nFor each of the paired molecules, we collect displacements for each \nof the vertices of the 'primary' wall where this molecule is located (that were provided by the user \nthrough add_vertex_move, and were possibly truncated due to collisions).\nThen we find the second wall where the second molecule of the pair is located.\nFor each of the vertices of all 'secondary' walls, we collect a list of displacements\nthat move the vertices of 'primary' walls. \nThen, an average displacement is computed for each vertex, and these average displacements\nare used to move the 'secondary' walls.\nWhen a 'primary' wall collides, its displacement is clamped or canceled. This is true even if \nit collides with a 'secondary' wall that would be otherwise moved. So, the displacement of the \n'primary' wall will mostly just pull the 'secondary' wall, not push. Therefore it is needed \nthat both objects are active and pull each other. \n\nThis process is well commented in MCell code: \n`partition.cpp <https://github.com/mcellteam/mcell/blob/master/src4/partition.cpp>`_ in functions\napply_vertex_moves, apply_vertex_moves_per_object, and move_walls_with_paired_molecules. \n \nWhen argument collect_wall_wall_hits is True, a list of wall pairs that collided is returned,\nwhen collect_wall_wall_hits is False, an empty list is returned.\n\n- collect_wall_wall_hits: When set to True, a list of wall pairs that collided is returned,\notherwise an empty list is returned.\n\n\n- randomize_order: When set to True (default), the ordering of the vertex move list created by add_vertex_move\ncalls is randomized. This allows to avoid any bias in the resulting positions of surface\nmolecules. \nHowever, the individual vertex moves are then sorted by the object to which the vertex belongs\nand the moves are applied object by object for correctness. Setting this to True also radomizes the \norder of objects to which the vertex moves are applied.\n\n\n") .def("pair_molecules", &Model::pair_molecules, py::arg("id1"), py::arg("id2"), "Sets that two surface molecules are paired. Paired molecules bind walls together\nand when one wall is moved, the wall that is bound through a paired molecule is moved as well.\nThrows exception if the molecule ids are not surface molecules.\nThrows exception if the molecules are on the same object. \nThrows exception if any of the molecules is already paired.\nMay be called only after model initialization.\n\n- id1\n- id2\n") .def("unpair_molecules", &Model::unpair_molecules, py::arg("id1"), py::arg("id2"), "Sets that two surface molecules are not paired. \nThrows exception if the molecule ids are not surface molecules. \nThrows exception if the molecules are not paired together.\nMay be called only after model initialization.\n\n- id1\n- id2\n") .def("get_paired_molecule", &Model::get_paired_molecule, py::arg("id"), "Return id of the molecule to which the molecule with 'id' is paired.\nReturns ID_INVALID (-1) when the molecule is not paired.\nMay be called only after model initialization.\n\n- id\n") .def("get_paired_molecules", &Model::get_paired_molecules, "Returns a dictionary that contains all molecules that are paired.\nMolecule ids are keys and the value associated with the key is the second paired molecule.\nThe returned dictionary is a copy and any changes made to it are ignored by MCell.\nNote: The reason why uint32 is used as the base type for the dictionary but type int is used\neverywhere else for molecule ids is only for performance reasons. \n") .def("register_mol_wall_hit_callback", &Model::register_mol_wall_hit_callback, py::arg("function"), py::arg("context"), py::arg("object") = nullptr, py::arg("species") = nullptr, "Register a callback for event when a molecule hits a wall. \nMay be called only after model initialization because it internally uses geometry object\nand species ids that are set during the initialization. \n\n- function: Callback function to be called. \nThe function must have two arguments MolWallHitInfo and context.\nDo not modify the received MolWallHitInfo object since it may be reused for other \nwall hit callbacks (e.g. when the first callback is for a specific geometry object and \nthe second callback is for any geometry object). \nThe context object (py::object type argument) is on the other hand provided \nto be modified and one can for instance use it to count the number of hits.. \n\n\n- context: Context passed to the callback function, the callback function can store\ninformation to this object. Some context must be always passed, even when \nit is a useless python object. \n\n\n- object: Only hits of this object will be reported, any object hit is reported when not set.\n\n- species: Only hits of molecules of this species will be reported, any hit of volume molecules of \nany species is reported when this argument is not set.\nSets an internal flag for this species to make sure that the species id does not change \nduring simulation. \n\n\n") .def("register_reaction_callback", &Model::register_reaction_callback, py::arg("function"), py::arg("context"), py::arg("reaction_rule"), "Defines a function to be called when a reaction was processed.\nIt is allowed to do state modifications except for removing reacting molecules, \nthey will be removed automatically after return from this callback. \nUnlimited number of reaction callbacks is allowed. \nMay be called only after model initialization because it internally uses \nreaction rule ids that are set during the initialization. \n\n- function: Callback function to be called. \nThe function must have two arguments ReactionInfo and context.\nCalled right after a reaction occured but before the reactants were removed.\nAfter return the reaction proceeds and reactants are removed (unless they were kept\nby the reaction such as with reaction A + B -> A + C).\n\n\n- context: Context passed to the callback function, the callback function can store\ninformation to this object. Some context must be always passed, even when \nit is a useless python object. \n\n\n- reaction_rule: The callback function will be called whenever this reaction rule is applied.\n\n") .def("load_bngl", &Model::load_bngl, py::arg("file_name"), py::arg("observables_path_or_file") = STR_UNSET, py::arg("default_release_region") = nullptr, py::arg("parameter_overrides") = std::map<std::string, double>(), py::arg("observables_output_format") = CountOutputFormat::AUTOMATIC_FROM_EXTENSION, "Loads sections: molecule types, reaction rules, seed species, and observables from a BNGL file\nand creates objects in the current model according to it.\nAll elementary molecule types used in the seed species section must be defined in subsystem.\nIf an item in the seed species section does not have its compartment set,\nthe argument default_region must be set and the molecules are released into or onto the \ndefault_region. \n\n- file_name: Path to the BNGL file to be loaded.\n\n- observables_path_or_file: Directory prefix or file name where observable values will be stored.\nIf a directory such as './react_data/seed_' + str(SEED).zfill(5) + '/' or an empty \nstring/unset is used, each observable gets its own file and the output file format for created Count \nobjects is CountOutputFormat.DAT.\nWhen not set, this path is used: './react_data/seed_' + str(model.config.seed).zfill(5) + '/'.\nIf a file has a .gdat extension such as \n'./react_data/seed_' + str(SEED).zfill(5) + '/counts.gdat', all observable are stored in this \nfile and the output file format for created Count objects is CountOutputFormat.GDAT.\nMust not be empty when observables_output_format is explicitly set to CountOutputFormat.GDAT.\n\n\n- default_release_region: Used as region for releases for seed species that have no compartments specified.\n\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n- observables_output_format: Selection of output format. Default setting uses automatic detection\nbased on contents of the 'observables_path_or_file' attribute.\n\n\n") .def("export_to_bngl", &Model::export_to_bngl, py::arg("file_name"), py::arg("simulation_method") = BNGSimulationMethod::ODE, "Exports all defined species, reaction rules and applicable observables\nas a BNGL file that can be then loaded by MCell4 or BioNetGen. \nThe resulting file should be validated that it produces expected results. \nMany MCell features cannot be exported into BNGL and when such a feature is \nencountered the export fails with a RuntimeError exception.\nHowever, the export code tries to export as much as possible and one can catch\nthe RuntimeError exception and use the possibly incomplete BNGL file anyway. \n\n- file_name: Output file name.\n\n- simulation_method: Selection of the BioNetGen simulation method. \nSelects BioNetGen action to run with the selected simulation method.\nFor BNGSimulationMethod.NF the export is limited to a single volume and\na single surface and the enerated rates use volume and surface area so that \nsimulation with NFSim produces corect results. \n\n\n") .def("save_checkpoint", &Model::save_checkpoint, py::arg("custom_dir") = STR_UNSET, "Saves current model state as checkpoint. \nThe default directory structure is checkpoints/seed_<SEED>/it_<ITERATION>,\nit can be changed by setting 'custom_dir'.\nIf used during an iteration such as in a callback, an event is scheduled for the \nbeginning of the next iteration. This scheduled event saves the checkpoint. \n\n- custom_dir: Sets custom directory where the checkpoint will be stored. \nThe default is 'checkpoints/seed_<SEED>/it_<ITERATION>'. \n\n\n") .def("schedule_checkpoint", &Model::schedule_checkpoint, py::arg("iteration") = 0, py::arg("continue_simulation") = false, py::arg("custom_dir") = STR_UNSET, "Schedules checkpoint save event that will occur when an iteration is started. \nThis means that it will be executed right before any other events scheduled for \nthe given iteration are executed.\nCan be called asynchronously at any time after initialization.\n\n- iteration: Specifies iteration number when the checkpoint save will occur. \nPlease note that iterations are counted from 0.\nTo schedule a checkpoint for the closest time as possible, keep the default value 0,\nthis will schedule checkpoint for the beginning of the iteration with number current iteration + 1. \nIf calling schedule_checkpoint from a different thread (e.g. by using threading.Timer), \nit is highly recommended to keep the default value 0 or choose some time that will be \nfor sure in the future.\n\n\n- continue_simulation: When false, saving the checkpoint means that we want to terminate the simulation \nright after the save. The currently running function Model.run_iterations\nwill not simulate any following iterations and execution will return from this function\nto execute the next statement which is usually 'model.end_simulation()'.\nWhen true, the checkpoint is saved and simulation continues uninterrupted.\n \n\n\n- custom_dir: Sets custom directory where the checkpoint will be stored. \nThe default is 'checkpoints/seed_<SEED>/it_<ITERATION>'. \n\n\n") .def("add_species", &Model::add_species, py::arg("s"), "Add a reference to a Species object to the species list.\n- s\n") .def("find_species", &Model::find_species, py::arg("name"), "Find a Species object using name in the species list. \nReturns None if no such species is found.\n\n- name\n") .def("add_reaction_rule", &Model::add_reaction_rule, py::arg("r"), "Add a reference to a ReactionRule object to the reaction_rules list.\n- r\n") .def("find_reaction_rule", &Model::find_reaction_rule, py::arg("name"), "Find a ReactionRule object using name in the reaction_rules list. \nReturns None if no such reaction rule is found.\n\n- name\n") .def("add_surface_class", &Model::add_surface_class, py::arg("sc"), "Add a reference to a SurfaceClass object to the surface_classes list.\n- sc\n") .def("find_surface_class", &Model::find_surface_class, py::arg("name"), "Find a SurfaceClass object using name in the surface_classes list. \nReturns None if no such surface class is found.\n\n- name\n") .def("add_elementary_molecule_type", &Model::add_elementary_molecule_type, py::arg("mt"), "Add a reference to an ElementaryMoleculeType object to the elementary_molecule_types list.\n- mt\n") .def("find_elementary_molecule_type", &Model::find_elementary_molecule_type, py::arg("name"), "Find an ElementaryMoleculeType object using name in the elementary_molecule_types list. \nReturns None if no such elementary molecule type is found.\n\n- name\n") .def("load_bngl_molecule_types_and_reaction_rules", &Model::load_bngl_molecule_types_and_reaction_rules, py::arg("file_name"), py::arg("parameter_overrides") = std::map<std::string, double>(), "Parses a BNGL file, only reads molecule types and reaction rules sections, \ni.e. ignores observables and seed species. \nParameter values are evaluated and the result value is directly used. \nCompartments names are stored in rxn rules as strings because compartments belong \nto geometry objects and the subsystem is independent on specific geometry.\nHowever, the compartments and their objects must be defined before initialization.\n\n- file_name: Path to the BNGL file to be loaded.\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n") .def("add_release_site", &Model::add_release_site, py::arg("s"), "Adds a reference to the release site s to the list of release sites.\n- s\n") .def("find_release_site", &Model::find_release_site, py::arg("name"), "Finds a release site by its name, returns None if no such release site is present.\n- name\n") .def("add_geometry_object", &Model::add_geometry_object, py::arg("o"), "Adds a reference to the geometry object o to the list of geometry objects.\n- o\n") .def("find_geometry_object", &Model::find_geometry_object, py::arg("name"), "Finds a geometry object by its name, returns None if no such geometry object is present.\n- name\n") .def("find_volume_compartment_object", &Model::find_volume_compartment_object, py::arg("name"), "Finds a geometry object by its name, the geometry object must be a BNGL compartment.\nReturns None if no such geometry object is present.\n\n- name\n") .def("find_surface_compartment_object", &Model::find_surface_compartment_object, py::arg("name"), "Finds a geometry object that is a BNGL compartment and its surface name is name.\nReturns None if no such geometry object is present.\n\n- name\n") .def("load_bngl_compartments_and_seed_species", &Model::load_bngl_compartments_and_seed_species, py::arg("file_name"), py::arg("default_release_region") = nullptr, py::arg("parameter_overrides") = std::map<std::string, double>(), "First loads section compartments and for each 3D compartment that does not \nalready exist as a geometry object in this Instantiation object, creates a \nbox with compartment's volume and also sets its 2D (membrane) compartment name.\nWhen multiple identical geometry objects are added to the final Model object, \nonly one copy is left so one can merge multiple Instantiation objects that created \ncompartments assuming that their volume is the same. \nThen loads section seed species from a BNGL file and creates release sites according to it.\nAll elementary molecule types used in the seed species section must be already defined in subsystem.\nIf an item in the BNGL seed species section does not have its compartment set,\nthe argument default_region must be set and the molecules are then released into or onto the \ndefault_region. \n\n- file_name: Path to the BNGL file.\n\n- default_release_region: Used as region for releases for seed species that have no compartments specified.\n\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n") .def("add_viz_output", &Model::add_viz_output, py::arg("viz_output"), "Adds a reference to the viz_output object to the list of visualization output specifications.\n- viz_output\n") .def("add_count", &Model::add_count, py::arg("count"), "Adds a reference to the count object to the list of count specifications.\n- count\n") .def("find_count", &Model::find_count, py::arg("name"), "Finds a count object by its name, returns None if no such count is present.\n- name\n") .def("load_bngl_observables", &Model::load_bngl_observables, py::arg("file_name"), py::arg("observables_path_or_file") = STR_UNSET, py::arg("parameter_overrides") = std::map<std::string, double>(), py::arg("observables_output_format") = CountOutputFormat::AUTOMATIC_FROM_EXTENSION, "Loads section observables from a BNGL file and creates Count objects according to it.\nAll elementary molecule types used in the seed species section must be defined in subsystem.\n\n- file_name: Path to the BNGL file.\n\n- observables_path_or_file: Directory prefix or file name where observable values will be stored.\nIf a directory such as './react_data/seed_' + str(SEED).zfill(5) + '/' or an empty \nstring/unset is used, each observable gets its own file and the output file format for created Count \nobjects is CountOutputFormat.DAT.\nWhen not set, this path is used: './react_data/seed_' + str(model.config.seed).zfill(5) + '/'.\nIf a file has a .gdat extension such as \n'./react_data/seed_' + str(SEED).zfill(5) + '/counts.gdat', all observable are stored in this \nfile and the output file format for created Count objects is CountOutputFormat.GDAT.\nMust not be empty when observables_output_format is explicitly set to CountOutputFormat.GDAT.\n\n\n- parameter_overrides: For each key k in the parameter_overrides, if it is defined in the BNGL's parameters section,\nits value is ignored and instead value parameter_overrides[k] is used.\n\n\n- observables_output_format: Selection of output format. Default setting uses automatic detection\nbased on contents of the 'observables_path_or_file' attribute.\n \n\n\n") .def("get_molecule_ids", &Model::get_molecule_ids, py::arg("pattern") = nullptr, "Returns a list of ids of molecules.\nIf the arguments pattern is not set, the list of all molecule ids is returned. \nIf the argument pattern is set, the list of all molecule ids whose species match \nthe pattern is returned. \n\n- pattern: BNGL pattern to select molecules based on their species, might use compartments.\n\n") .def("get_molecule", &Model::get_molecule, py::arg("id"), "Returns a information on a molecule from the simulated environment, \nNone if the molecule does not exist.\n\n- id: Unique id of the molecule to be retrieved.\n\n") .def("get_species_name", &Model::get_species_name, py::arg("species_id"), "Returns a string representing canonical species name in the BNGL format.\n\n- species_id: Id of the species.\n\n") .def("get_vertex", &Model::get_vertex, py::arg("object"), py::arg("vertex_index"), "Returns coordinates of a vertex.\n- object\n- vertex_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("get_wall", &Model::get_wall, py::arg("object"), py::arg("wall_index"), "Returns information about a wall belonging to a given object.\n- object: Geometry object whose wall to retrieve.\n\n- wall_index: This is the index of the wall in the geometry object's walls (wall_list).\n\n") .def("get_vertex_unit_normal", &Model::get_vertex_unit_normal, py::arg("object"), py::arg("vertex_index"), "Returns sum of all wall normals that use this vertex converted to a unit vector of \nlength 1 um (micrometer).\nThis represents the unit vector pointing outwards from the vertex.\n\n- object: Geometry object whose vertex to retrieve.\n\n- vertex_index: This is the index of the vertex in the geometry object's vertex_list.\n\n") .def("get_wall_unit_normal", &Model::get_wall_unit_normal, py::arg("object"), py::arg("wall_index"), "Returns wall normal converted to a unit vector of length 1um.\n- object: Geometry object whose wall's normal to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("get_wall_color", &Model::get_wall_color, py::arg("object"), py::arg("wall_index"), "Returns color of a wall.\n- object: Geometry object whose wall's color to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n") .def("set_wall_color", &Model::set_wall_color, py::arg("object"), py::arg("wall_index"), py::arg("color"), "Sets color of a wall.\n- object: Geometry object whose wall's color to retrieve.\n\n- wall_index: This is the index of the vertex in the geometry object's walls (wall_list).\n\n- color: Color to be set.\n\n") .def("dump", &Model::dump) .def_property("config", &Model::get_config, &Model::set_config, "Simulation configuration.") .def_property("warnings", &Model::get_warnings, &Model::set_warnings, "Configuration on how to report warnings.") .def_property("notifications", &Model::get_notifications, &Model::set_notifications, "Configuration on how to report certain notifications.") .def_property("species", &Model::get_species, &Model::set_species, py::return_value_policy::reference, "List of species to be included in the model for initialization.\nUsed usually only for simple species (species that are defined using a\nsingle molecule type without components such as 'A').\nOther species may be created inside simulation \n") .def_property("reaction_rules", &Model::get_reaction_rules, &Model::set_reaction_rules, py::return_value_policy::reference) .def_property("surface_classes", &Model::get_surface_classes, &Model::set_surface_classes, py::return_value_policy::reference) .def_property("elementary_molecule_types", &Model::get_elementary_molecule_types, &Model::set_elementary_molecule_types, py::return_value_policy::reference, "Contains list of elementary molecule types with their diffusion constants and other information. \nPopulated when a BNGL file is loaded and also on initialization from Species objects present in \nthe species list.\n") .def_property("release_sites", &Model::get_release_sites, &Model::set_release_sites, py::return_value_policy::reference, "List of release sites to be included in the model. \n") .def_property("geometry_objects", &Model::get_geometry_objects, &Model::set_geometry_objects, py::return_value_policy::reference, "List of geometry objects to be included in the model. \n") .def_property("checkpointed_molecules", &Model::get_checkpointed_molecules, &Model::set_checkpointed_molecules, py::return_value_policy::reference, "Used when resuming simulation from a checkpoint.\n") .def_property("viz_outputs", &Model::get_viz_outputs, &Model::set_viz_outputs, py::return_value_policy::reference, "List of visualization outputs to be included in the model.\nThere is usually just one VizOutput object. \n") .def_property("counts", &Model::get_counts, &Model::set_counts, py::return_value_policy::reference, "List of counts to be included in the model.\n") ; } std::string GenModel::export_to_python(std::ostream& out, PythonExportContext& ctx) { # if 0 // not to be used std::string exported_name = "model"; bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.Model(" << nl; if (species != std::vector<std::shared_ptr<Species>>() && !skip_vectors_export()) { ss << ind << "species = " << export_vec_species(out, ctx, exported_name) << "," << nl; } if (reaction_rules != std::vector<std::shared_ptr<ReactionRule>>() && !skip_vectors_export()) { ss << ind << "reaction_rules = " << export_vec_reaction_rules(out, ctx, exported_name) << "," << nl; } if (surface_classes != std::vector<std::shared_ptr<SurfaceClass>>() && !skip_vectors_export()) { ss << ind << "surface_classes = " << export_vec_surface_classes(out, ctx, exported_name) << "," << nl; } if (elementary_molecule_types != std::vector<std::shared_ptr<ElementaryMoleculeType>>() && !skip_vectors_export()) { ss << ind << "elementary_molecule_types = " << export_vec_elementary_molecule_types(out, ctx, exported_name) << "," << nl; } if (release_sites != std::vector<std::shared_ptr<ReleaseSite>>() && !skip_vectors_export()) { ss << ind << "release_sites = " << export_vec_release_sites(out, ctx, exported_name) << "," << nl; } if (geometry_objects != std::vector<std::shared_ptr<GeometryObject>>() && !skip_vectors_export()) { ss << ind << "geometry_objects = " << export_vec_geometry_objects(out, ctx, exported_name) << "," << nl; } if (checkpointed_molecules != std::vector<std::shared_ptr<BaseChkptMol>>() && !skip_vectors_export()) { ss << ind << "checkpointed_molecules = " << export_vec_checkpointed_molecules(out, ctx, exported_name) << "," << nl; } if (viz_outputs != std::vector<std::shared_ptr<VizOutput>>() && !skip_vectors_export()) { ss << ind << "viz_outputs = " << export_vec_viz_outputs(out, ctx, exported_name) << "," << nl; } if (counts != std::vector<std::shared_ptr<Count>>() && !skip_vectors_export()) { ss << ind << "counts = " << export_vec_counts(out, ctx, exported_name) << "," << nl; } if (config != Config()) { ss << ind << "config = " << config.export_to_python(out, ctx) << "," << nl; } if (warnings != Warnings()) { ss << ind << "warnings = " << warnings.export_to_python(out, ctx) << "," << nl; } if (notifications != Notifications()) { ss << ind << "notifications = " << notifications.export_to_python(out, ctx) << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } #else // # if 0 assert(false); return ""; #endif } std::string GenModel::export_vec_species(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_species"; } else { exported_name = "species"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < species.size(); i++) { const auto& item = species[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_reaction_rules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_reaction_rules"; } else { exported_name = "reaction_rules"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < reaction_rules.size(); i++) { const auto& item = reaction_rules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_surface_classes(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_surface_classes"; } else { exported_name = "surface_classes"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < surface_classes.size(); i++) { const auto& item = surface_classes[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_elementary_molecule_types(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_elementary_molecule_types"; } else { exported_name = "elementary_molecule_types"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < elementary_molecule_types.size(); i++) { const auto& item = elementary_molecule_types[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_release_sites(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_release_sites"; } else { exported_name = "release_sites"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < release_sites.size(); i++) { const auto& item = release_sites[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_geometry_objects(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_geometry_objects"; } else { exported_name = "geometry_objects"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < geometry_objects.size(); i++) { const auto& item = geometry_objects[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_checkpointed_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_checkpointed_molecules"; } else { exported_name = "checkpointed_molecules"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < checkpointed_molecules.size(); i++) { const auto& item = checkpointed_molecules[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_viz_outputs(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_viz_outputs"; } else { exported_name = "viz_outputs"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < viz_outputs.size(); i++) { const auto& item = viz_outputs[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } std::string GenModel::export_vec_counts(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // prints vector into 'out' and returns name of the generated list std::stringstream ss; std::string exported_name; if (parent_name != ""){ exported_name = parent_name+ "_counts"; } else { exported_name = "counts"; } ss << exported_name << " = [\n"; for (size_t i = 0; i < counts.size(); i++) { const auto& item = counts[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "\n]\n\n"; out << ss.str(); return exported_name; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_chkpt_surf_mol.cpp
.cpp
9,755
291
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_chkpt_surf_mol.h" #include "api/chkpt_surf_mol.h" #include "api/geometry_object.h" #include "api/species.h" namespace MCell { namespace API { void GenChkptSurfMol::check_semantics() const { if (!is_set(pos)) { throw ValueError("Parameter 'pos' must be set."); } if (!is_set(orientation)) { throw ValueError("Parameter 'orientation' must be set."); } if (!is_set(geometry_object)) { throw ValueError("Parameter 'geometry_object' must be set."); } if (!is_set(wall_index)) { throw ValueError("Parameter 'wall_index' must be set."); } if (!is_set(grid_tile_index)) { throw ValueError("Parameter 'grid_tile_index' must be set."); } if (!is_set(id)) { throw ValueError("Parameter 'id' must be set."); } if (!is_set(species)) { throw ValueError("Parameter 'species' must be set."); } if (!is_set(diffusion_time)) { throw ValueError("Parameter 'diffusion_time' must be set."); } if (!is_set(birthday)) { throw ValueError("Parameter 'birthday' must be set."); } if (!is_set(flags)) { throw ValueError("Parameter 'flags' must be set."); } } void GenChkptSurfMol::set_initialized() { if (is_set(geometry_object)) { geometry_object->set_initialized(); } if (is_set(species)) { species->set_initialized(); } initialized = true; } void GenChkptSurfMol::set_all_attributes_as_default_or_unset() { class_name = "ChkptSurfMol"; pos = VEC2_UNSET; orientation = Orientation::NOT_SET; geometry_object = nullptr; wall_index = INT_UNSET; grid_tile_index = INT_UNSET; id = INT_UNSET; species = nullptr; diffusion_time = FLT_UNSET; birthday = FLT_UNSET; flags = INT_UNSET; unimol_rxn_time = FLT_UNSET; } std::shared_ptr<ChkptSurfMol> GenChkptSurfMol::copy_chkpt_surf_mol() const { std::shared_ptr<ChkptSurfMol> res = std::make_shared<ChkptSurfMol>(DefaultCtorArgType()); res->class_name = class_name; res->pos = pos; res->orientation = orientation; res->geometry_object = geometry_object; res->wall_index = wall_index; res->grid_tile_index = grid_tile_index; res->id = id; res->species = species; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } std::shared_ptr<ChkptSurfMol> GenChkptSurfMol::deepcopy_chkpt_surf_mol(py::dict) const { std::shared_ptr<ChkptSurfMol> res = std::make_shared<ChkptSurfMol>(DefaultCtorArgType()); res->class_name = class_name; res->pos = pos; res->orientation = orientation; res->geometry_object = is_set(geometry_object) ? geometry_object->deepcopy_geometry_object() : nullptr; res->wall_index = wall_index; res->grid_tile_index = grid_tile_index; res->id = id; res->species = is_set(species) ? species->deepcopy_species() : nullptr; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } bool GenChkptSurfMol::__eq__(const ChkptSurfMol& other) const { return pos == other.pos && orientation == other.orientation && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && grid_tile_index == other.grid_tile_index && id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } bool GenChkptSurfMol::eq_nonarray_attributes(const ChkptSurfMol& other, const bool ignore_name) const { return pos == other.pos && orientation == other.orientation && ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && grid_tile_index == other.grid_tile_index && id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } std::string GenChkptSurfMol::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "pos=" << pos << ", " << "orientation=" << orientation << ", " << "\n" << ind + " " << "geometry_object=" << "(" << ((geometry_object != nullptr) ? geometry_object->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall_index=" << wall_index << ", " << "grid_tile_index=" << grid_tile_index << ", " << "id=" << id << ", " << "\n" << ind + " " << "species=" << "(" << ((species != nullptr) ? species->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "diffusion_time=" << diffusion_time << ", " << "birthday=" << birthday << ", " << "flags=" << flags << ", " << "unimol_rxn_time=" << unimol_rxn_time; return ss.str(); } py::class_<ChkptSurfMol> define_pybinding_ChkptSurfMol(py::module& m) { return py::class_<ChkptSurfMol, BaseChkptMol, std::shared_ptr<ChkptSurfMol>>(m, "ChkptSurfMol", "Class representing a checkpointed surface molecule.\nNot to be used directly.\n") .def( py::init< const Vec2&, const Orientation, std::shared_ptr<GeometryObject>, const int, const int, const int, std::shared_ptr<Species>, const double, const double, const int, const double >(), py::arg("pos"), py::arg("orientation"), py::arg("geometry_object"), py::arg("wall_index"), py::arg("grid_tile_index"), py::arg("id"), py::arg("species"), py::arg("diffusion_time"), py::arg("birthday"), py::arg("flags"), py::arg("unimol_rxn_time") = FLT_UNSET ) .def("check_semantics", &ChkptSurfMol::check_semantics) .def("__copy__", &ChkptSurfMol::copy_chkpt_surf_mol) .def("__deepcopy__", &ChkptSurfMol::deepcopy_chkpt_surf_mol, py::arg("memo")) .def("__str__", &ChkptSurfMol::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ChkptSurfMol::__eq__, py::arg("other")) .def("dump", &ChkptSurfMol::dump) .def_property("pos", &ChkptSurfMol::get_pos, &ChkptSurfMol::set_pos) .def_property("orientation", &ChkptSurfMol::get_orientation, &ChkptSurfMol::set_orientation) .def_property("geometry_object", &ChkptSurfMol::get_geometry_object, &ChkptSurfMol::set_geometry_object) .def_property("wall_index", &ChkptSurfMol::get_wall_index, &ChkptSurfMol::set_wall_index) .def_property("grid_tile_index", &ChkptSurfMol::get_grid_tile_index, &ChkptSurfMol::set_grid_tile_index) ; } std::string GenChkptSurfMol::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "chkpt_surf_mol_" + std::to_string(ctx.postinc_counter("chkpt_surf_mol")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ChkptSurfMol(" << nl; ss << ind << "id = " << id << "," << nl; ss << ind << "species = " << species->export_to_python(out, ctx) << "," << nl; ss << ind << "diffusion_time = " << f_to_str(diffusion_time) << "," << nl; ss << ind << "birthday = " << f_to_str(birthday) << "," << nl; ss << ind << "flags = " << flags << "," << nl; if (unimol_rxn_time != FLT_UNSET) { ss << ind << "unimol_rxn_time = " << f_to_str(unimol_rxn_time) << "," << nl; } ss << ind << "pos = " << "m.Vec2(" << f_to_str(pos.u) << ", " << f_to_str(pos.v)<< ")," << nl; ss << ind << "orientation = " << orientation << "," << nl; ss << ind << "geometry_object = " << geometry_object->export_to_python(out, ctx) << "," << nl; ss << ind << "wall_index = " << wall_index << "," << nl; ss << ind << "grid_tile_index = " << grid_tile_index << "," << nl; ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_count.h
.h
5,416
153
/****************************************************************************** * * Copyright (C) 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 API_GEN_COUNT_H #define API_GEN_COUNT_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Count; class CountTerm; class PythonExportContext; #define COUNT_CTOR() \ Count( \ const std::string& name_ = STR_UNSET, \ const std::string& file_name_ = STR_UNSET, \ std::shared_ptr<CountTerm> expression_ = nullptr, \ const double multiplier_ = 1, \ const double every_n_timesteps_ = 1, \ const CountOutputFormat output_format_ = CountOutputFormat::AUTOMATIC_FROM_EXTENSION \ ) { \ class_name = "Count"; \ name = name_; \ file_name = file_name_; \ expression = expression_; \ multiplier = multiplier_; \ every_n_timesteps = every_n_timesteps_; \ output_format = output_format_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Count(DefaultCtorArgType) : \ GenCount(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenCount: public BaseDataClass { public: GenCount() { } GenCount(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Count> copy_count() const; std::shared_ptr<Count> deepcopy_count(py::dict = py::dict()) const; virtual bool __eq__(const Count& other) const; virtual bool eq_nonarray_attributes(const Count& other, const bool ignore_name = false) const; bool operator == (const Count& other) const { return __eq__(other);} bool operator != (const Count& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- std::string file_name; virtual void set_file_name(const std::string& new_file_name_) { if (initialized) { throw RuntimeError("Value 'file_name' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; file_name = new_file_name_; } virtual const std::string& get_file_name() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return file_name; } std::shared_ptr<CountTerm> expression; virtual void set_expression(std::shared_ptr<CountTerm> new_expression_) { if (initialized) { throw RuntimeError("Value 'expression' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; expression = new_expression_; } virtual std::shared_ptr<CountTerm> get_expression() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return expression; } double multiplier; virtual void set_multiplier(const double new_multiplier_) { if (initialized) { throw RuntimeError("Value 'multiplier' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; multiplier = new_multiplier_; } virtual double get_multiplier() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return multiplier; } double every_n_timesteps; virtual void set_every_n_timesteps(const double new_every_n_timesteps_) { if (initialized) { throw RuntimeError("Value 'every_n_timesteps' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; every_n_timesteps = new_every_n_timesteps_; } virtual double get_every_n_timesteps() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return every_n_timesteps; } CountOutputFormat output_format; virtual void set_output_format(const CountOutputFormat new_output_format_) { if (initialized) { throw RuntimeError("Value 'output_format' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; output_format = new_output_format_; } virtual CountOutputFormat get_output_format() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return output_format; } // --- methods --- virtual double get_current_value() = 0; }; // GenCount class Count; py::class_<Count> define_pybinding_Count(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COUNT_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_reaction_rule.cpp
.cpp
14,487
275
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_reaction_rule.h" #include "api/reaction_rule.h" #include "api/complex.h" namespace MCell { namespace API { void GenReactionRule::check_semantics() const { } void GenReactionRule::set_initialized() { vec_set_initialized(reactants); vec_set_initialized(products); initialized = true; } void GenReactionRule::set_all_attributes_as_default_or_unset() { class_name = "ReactionRule"; name = STR_UNSET; reactants = std::vector<std::shared_ptr<Complex>>(); products = std::vector<std::shared_ptr<Complex>>(); fwd_rate = FLT_UNSET; rev_name = STR_UNSET; rev_rate = FLT_UNSET; variable_rate = std::vector<std::vector<double>>(); is_intermembrane_surface_reaction = false; } std::shared_ptr<ReactionRule> GenReactionRule::copy_reaction_rule() const { std::shared_ptr<ReactionRule> res = std::make_shared<ReactionRule>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; res->reactants = reactants; res->products = products; res->fwd_rate = fwd_rate; res->rev_name = rev_name; res->rev_rate = rev_rate; res->variable_rate = variable_rate; res->is_intermembrane_surface_reaction = is_intermembrane_surface_reaction; return res; } std::shared_ptr<ReactionRule> GenReactionRule::deepcopy_reaction_rule(py::dict) const { std::shared_ptr<ReactionRule> res = std::make_shared<ReactionRule>(DefaultCtorArgType()); res->class_name = class_name; res->name = name; for (const auto& item: reactants) { res->reactants.push_back((is_set(item)) ? item->deepcopy_complex() : nullptr); } for (const auto& item: products) { res->products.push_back((is_set(item)) ? item->deepcopy_complex() : nullptr); } res->fwd_rate = fwd_rate; res->rev_name = rev_name; res->rev_rate = rev_rate; res->variable_rate = variable_rate; res->is_intermembrane_surface_reaction = is_intermembrane_surface_reaction; return res; } bool GenReactionRule::__eq__(const ReactionRule& other) const { return name == other.name && vec_ptr_eq(reactants, other.reactants) && vec_ptr_eq(products, other.products) && fwd_rate == other.fwd_rate && rev_name == other.rev_name && rev_rate == other.rev_rate && variable_rate == other.variable_rate && is_intermembrane_surface_reaction == other.is_intermembrane_surface_reaction; } bool GenReactionRule::eq_nonarray_attributes(const ReactionRule& other, const bool ignore_name) const { return (ignore_name || name == other.name) && true /*reactants*/ && true /*products*/ && fwd_rate == other.fwd_rate && rev_name == other.rev_name && rev_rate == other.rev_rate && true /*variable_rate*/ && is_intermembrane_surface_reaction == other.is_intermembrane_surface_reaction; } std::string GenReactionRule::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "name=" << name << ", " << "\n" << ind + " " << "reactants=" << vec_ptr_to_str(reactants, all_details, ind + " ") << ", " << "\n" << ind + " " << "products=" << vec_ptr_to_str(products, all_details, ind + " ") << ", " << "\n" << ind + " " << "fwd_rate=" << fwd_rate << ", " << "rev_name=" << rev_name << ", " << "rev_rate=" << rev_rate << ", " << "variable_rate=" << vec_nonptr_to_str(variable_rate, all_details, ind + " ") << ", " << "is_intermembrane_surface_reaction=" << is_intermembrane_surface_reaction; return ss.str(); } py::class_<ReactionRule> define_pybinding_ReactionRule(py::module& m) { return py::class_<ReactionRule, std::shared_ptr<ReactionRule>>(m, "ReactionRule", "Represents a BioNetGen Language (BNGL) reaction rule. \nIn BNGL, a reaction is simply one or more transformations\napplied simultaneously to one or more species. The following\ntransformations (and their combinations) are allowed:\n * Forming a bond, e.g. A(b) + B(a) -> A(b!0).B(a!0)\n * Breaking a bond, e.g. A(b!0).B(a!0)-> A(b)+ B(a)\n * Changing of component state, e.g. X(y~0) -> X(y~p)\n * Creating a molecule, e.g. A(b) -> A(b) + C(d)\n * Destroying a molecule, e.g. A(b) + B(a) -> A(b) or A -> Null \n (Null here means that there is no product)\n * Changing species of a bound molecule when the molecule type has the \n same components, e.g. A(b!0).B(a!0)-> A(b!0).C(a!0)\n \nAlso compartments may be specified in reactants (patterns) and for products.\nSpecial compartment classes supported by MCell4 are @IN and @OUT.\nThey can be used in surface reactions to constrain a reaction with a volume molecule \nhitting a surface molecule from the inside or outside of the compartment, \ne.g. A(s)@IN + S(a) -> S(a!1).A(s!1) and/or to define the location of the \nproduct, e.g. S(a!1).A(s!1) -> S(a) + A(s)@OUT. \n") .def( py::init< const std::string&, const std::vector<std::shared_ptr<Complex>>, const std::vector<std::shared_ptr<Complex>>, const double, const std::string&, const double, const std::vector<std::vector<double>>, const bool >(), py::arg("name") = STR_UNSET, py::arg("reactants") = std::vector<std::shared_ptr<Complex>>(), py::arg("products") = std::vector<std::shared_ptr<Complex>>(), py::arg("fwd_rate") = FLT_UNSET, py::arg("rev_name") = STR_UNSET, py::arg("rev_rate") = FLT_UNSET, py::arg("variable_rate") = std::vector<std::vector<double>>(), py::arg("is_intermembrane_surface_reaction") = false ) .def("check_semantics", &ReactionRule::check_semantics) .def("__copy__", &ReactionRule::copy_reaction_rule) .def("__deepcopy__", &ReactionRule::deepcopy_reaction_rule, py::arg("memo")) .def("__str__", &ReactionRule::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ReactionRule::__eq__, py::arg("other")) .def("to_bngl_str", &ReactionRule::to_bngl_str, "Creates a string that corresponds to the reaction rule's BNGL representation, does not contain rates.") .def("dump", &ReactionRule::dump) .def_property("name", &ReactionRule::get_name, &ReactionRule::set_name, "Name of the reaction. If this is a reversible reaction, then it is the name of the \nreaction in forward direction.\n") .def_property("reactants", &ReactionRule::get_reactants, &ReactionRule::set_reactants, py::return_value_policy::reference, "List of reactant patterns. Must contain one or two patterns.") .def_property("products", &ReactionRule::get_products, &ReactionRule::set_products, py::return_value_policy::reference, "List of reactant patterns. May be empty.") .def_property("fwd_rate", &ReactionRule::get_fwd_rate, &ReactionRule::set_fwd_rate, "The units of the reaction rate for uni- and bimolecular reactions are:\n * [s^-1] for unimolecular reactions,\n * [N^-1*s^-1] bimolecular reactions between two surface molecules on different objects \n (this is a highly experimental feature and the unit will likely change in the future, \n not sure if probability is computed correctly, it works the way that the surface molecule \n is first diffused and then a potential collisions within the distance of Config.intermembrane_interaction_radius\n are evaluated). \nOther bimolecular reaction units depend on Model.config.use_bng_units settings.\nWhen use_bng_units is False (default), traditional MCell units are used: \n * [M^-1*s^-1] for bimolecular reactions between either two volume molecules, a volume molecule \n and a surface (molecule), \n * [um^2*N^-1*s^-1] bimolecular reactions between two surface molecules on the same surface, and\nWhen use_bng_units is True, units compatible with BioNetGen's ODE, SSA, and PLA solvers are used:\n * [um^3*N^-1*s^-1] for any bimolecular reactions, surface-surface reaction rate conversion assumes 10nm membrane thickness. \nM is the molarity of the solution and N the number of reactants.\nMay be changed after model initialization. \nSetting of value is ignored if the rate does not change. \nIf the new value differs from previous, updates all information related \nto the new rate including recomputation of reaction times for molecules if this is a\nunimolecular reaction.\n") .def_property("rev_name", &ReactionRule::get_rev_name, &ReactionRule::set_rev_name, "Name of the reaction in reverse direction. \n") .def_property("rev_rate", &ReactionRule::get_rev_rate, &ReactionRule::set_rev_rate, "Reverse reactions rate, reaction is unidirectional when not specified.\nMay be changed after model initialization, in the case behaves the same was as for \nchanging the 'fwd_rate'. \nUses the same units as 'fwd_rate'.\n") .def_property("variable_rate", &ReactionRule::get_variable_rate, &ReactionRule::set_variable_rate, py::return_value_policy::reference, "The array passed as this argument must have as its items a pair of floats (time in s, rate).\nMust be sorted by time (this is not checked). \nVariable rate is applicable only for irreversible reactions.\nWhen simulation starts and the table does not contain value for time 0, the initial fwd_rate is set to 0.\nWhen time advances after the last time in this table, the last rate is used for all subsequent iterations. \nMembers fwd_rate and rev_rate must not be set when setting this attribute through a constructor. \nWhen this attribute is set outside of the class constructor, fwd_rate is automatically reset to an 'unset' value.\nCannot be set after model initialization. \n") .def_property("is_intermembrane_surface_reaction", &ReactionRule::get_is_intermembrane_surface_reaction, &ReactionRule::set_is_intermembrane_surface_reaction, "Experimental, see addintinal explanation in 'fwd' rate.\nThen set to true, this is a special type of surface-surface reaction that \nallows for two surface molecules to react when they are on different geometrical objects. \nNote: This support is limited for now, the reaction rule must be in the form of A + B -> C + D \nwhere all reactants and products must be surface molecules and their orientation must be 'any' (default). \n") ; } std::string GenReactionRule::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = std::string("reaction_rule") + "_" + (is_set(name) ? fix_id(name) : std::to_string(ctx.postinc_counter("reaction_rule"))); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ReactionRule(" << nl; if (name != STR_UNSET) { ss << ind << "name = " << "'" << name << "'" << "," << nl; } if (reactants != std::vector<std::shared_ptr<Complex>>() && !skip_vectors_export()) { ss << ind << "reactants = " << export_vec_reactants(out, ctx, exported_name) << "," << nl; } if (products != std::vector<std::shared_ptr<Complex>>() && !skip_vectors_export()) { ss << ind << "products = " << export_vec_products(out, ctx, exported_name) << "," << nl; } if (fwd_rate != FLT_UNSET) { ss << ind << "fwd_rate = " << f_to_str(fwd_rate) << "," << nl; } if (rev_name != STR_UNSET) { ss << ind << "rev_name = " << "'" << rev_name << "'" << "," << nl; } if (rev_rate != FLT_UNSET) { ss << ind << "rev_rate = " << f_to_str(rev_rate) << "," << nl; } if (variable_rate != std::vector<std::vector<double>>() && !skip_vectors_export()) { ss << ind << "variable_rate = " << export_vec_variable_rate(out, ctx, exported_name) << "," << nl; } if (is_intermembrane_surface_reaction != false) { ss << ind << "is_intermembrane_surface_reaction = " << is_intermembrane_surface_reaction << "," << nl; } ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } std::string GenReactionRule::export_vec_reactants(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < reactants.size(); i++) { const auto& item = reactants[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } std::string GenReactionRule::export_vec_products(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < products.size(); i++) { const auto& item = products[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } if (!item->skip_python_export()) { std::string name = item->export_to_python(out, ctx); ss << name << ", "; } } ss << "]"; return ss.str(); } std::string GenReactionRule::export_vec_variable_rate(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name) { // does not print the array itself to 'out' and returns the whole list std::stringstream ss; ss << "["; for (size_t i = 0; i < variable_rate.size(); i++) { const auto& item = variable_rate[i]; if (i == 0) { ss << " "; } else if (i % 16 == 0) { ss << "\n "; } ss << "["; for (const auto& value: item) { ss << f_to_str(value) << ", "; } ss << "], "; } ss << "]"; return ss.str(); } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_chkpt_vol_mol.cpp
.cpp
6,655
215
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_chkpt_vol_mol.h" #include "api/chkpt_vol_mol.h" #include "api/species.h" namespace MCell { namespace API { void GenChkptVolMol::check_semantics() const { if (!is_set(pos)) { throw ValueError("Parameter 'pos' must be set."); } if (!is_set(id)) { throw ValueError("Parameter 'id' must be set."); } if (!is_set(species)) { throw ValueError("Parameter 'species' must be set."); } if (!is_set(diffusion_time)) { throw ValueError("Parameter 'diffusion_time' must be set."); } if (!is_set(birthday)) { throw ValueError("Parameter 'birthday' must be set."); } if (!is_set(flags)) { throw ValueError("Parameter 'flags' must be set."); } } void GenChkptVolMol::set_initialized() { if (is_set(species)) { species->set_initialized(); } initialized = true; } void GenChkptVolMol::set_all_attributes_as_default_or_unset() { class_name = "ChkptVolMol"; pos = VEC3_UNSET; id = INT_UNSET; species = nullptr; diffusion_time = FLT_UNSET; birthday = FLT_UNSET; flags = INT_UNSET; unimol_rxn_time = FLT_UNSET; } std::shared_ptr<ChkptVolMol> GenChkptVolMol::copy_chkpt_vol_mol() const { std::shared_ptr<ChkptVolMol> res = std::make_shared<ChkptVolMol>(DefaultCtorArgType()); res->class_name = class_name; res->pos = pos; res->id = id; res->species = species; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } std::shared_ptr<ChkptVolMol> GenChkptVolMol::deepcopy_chkpt_vol_mol(py::dict) const { std::shared_ptr<ChkptVolMol> res = std::make_shared<ChkptVolMol>(DefaultCtorArgType()); res->class_name = class_name; res->pos = pos; res->id = id; res->species = is_set(species) ? species->deepcopy_species() : nullptr; res->diffusion_time = diffusion_time; res->birthday = birthday; res->flags = flags; res->unimol_rxn_time = unimol_rxn_time; return res; } bool GenChkptVolMol::__eq__(const ChkptVolMol& other) const { return pos == other.pos && id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } bool GenChkptVolMol::eq_nonarray_attributes(const ChkptVolMol& other, const bool ignore_name) const { return pos == other.pos && id == other.id && ( (is_set(species)) ? (is_set(other.species) ? (species->__eq__(*other.species)) : false ) : (is_set(other.species) ? false : true ) ) && diffusion_time == other.diffusion_time && birthday == other.birthday && flags == other.flags && unimol_rxn_time == other.unimol_rxn_time; } std::string GenChkptVolMol::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "pos=" << pos << ", " << "id=" << id << ", " << "\n" << ind + " " << "species=" << "(" << ((species != nullptr) ? species->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "diffusion_time=" << diffusion_time << ", " << "birthday=" << birthday << ", " << "flags=" << flags << ", " << "unimol_rxn_time=" << unimol_rxn_time; return ss.str(); } py::class_<ChkptVolMol> define_pybinding_ChkptVolMol(py::module& m) { return py::class_<ChkptVolMol, BaseChkptMol, std::shared_ptr<ChkptVolMol>>(m, "ChkptVolMol", "Class representing a checkpointed volume molecule.\nNot to be used directly.\n") .def( py::init< const Vec3&, const int, std::shared_ptr<Species>, const double, const double, const int, const double >(), py::arg("pos"), py::arg("id"), py::arg("species"), py::arg("diffusion_time"), py::arg("birthday"), py::arg("flags"), py::arg("unimol_rxn_time") = FLT_UNSET ) .def("check_semantics", &ChkptVolMol::check_semantics) .def("__copy__", &ChkptVolMol::copy_chkpt_vol_mol) .def("__deepcopy__", &ChkptVolMol::deepcopy_chkpt_vol_mol, py::arg("memo")) .def("__str__", &ChkptVolMol::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &ChkptVolMol::__eq__, py::arg("other")) .def("dump", &ChkptVolMol::dump) .def_property("pos", &ChkptVolMol::get_pos, &ChkptVolMol::set_pos) ; } std::string GenChkptVolMol::export_to_python(std::ostream& out, PythonExportContext& ctx) { if (!export_even_if_already_exported() && ctx.already_exported(this)) { return ctx.get_exported_name(this); } std::string exported_name = "chkpt_vol_mol_" + std::to_string(ctx.postinc_counter("chkpt_vol_mol")); if (!export_even_if_already_exported()) { ctx.add_exported(this, exported_name); } bool str_export = export_as_string_without_newlines(); std::string nl = ""; std::string ind = " "; std::stringstream ss; if (!str_export) { nl = "\n"; ind = " "; ss << exported_name << " = "; } ss << "m.ChkptVolMol(" << nl; ss << ind << "id = " << id << "," << nl; ss << ind << "species = " << species->export_to_python(out, ctx) << "," << nl; ss << ind << "diffusion_time = " << f_to_str(diffusion_time) << "," << nl; ss << ind << "birthday = " << f_to_str(birthday) << "," << nl; ss << ind << "flags = " << flags << "," << nl; if (unimol_rxn_time != FLT_UNSET) { ss << ind << "unimol_rxn_time = " << f_to_str(unimol_rxn_time) << "," << nl; } ss << ind << "pos = " << "m.Vec3(" << f_to_str(pos.x) << ", " << f_to_str(pos.y) << ", " << f_to_str(pos.z)<< ")," << nl; ss << ")" << nl << nl; if (!str_export) { out << ss.str(); return exported_name; } else { return ss.str(); } } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_model.h
.h
6,627
140
/****************************************************************************** * * Copyright (C) 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 API_GEN_MODEL_H #define API_GEN_MODEL_H #include "api/api_common.h" #include "api/api_config.h" #include "api/mol_wall_hit_info.h" #include "api/notifications.h" #include "api/reaction_info.h" #include "api/warnings.h" #include "api/subsystem.h" #include "api/instantiation.h" #include "api/observables.h" #include "api/introspection.h" namespace MCell { namespace API { class Model; class BaseChkptMol; class Color; class Complex; class Config; class Count; class ElementaryMoleculeType; class GeometryObject; class Instantiation; class MolWallHitInfo; class Molecule; class Notifications; class Observables; class ReactionInfo; class ReactionRule; class Region; class ReleaseSite; class Species; class Subsystem; class SurfaceClass; class VizOutput; class Wall; class WallWallHitInfo; class Warnings; class PythonExportContext; class GenModel: public Subsystem, public Instantiation, public Observables, public Introspection { public: GenModel() { } GenModel(DefaultCtorArgType) { } virtual ~GenModel() {} std::shared_ptr<Model> copy_model() const; std::shared_ptr<Model> deepcopy_model(py::dict = py::dict()) const; virtual bool __eq__(const Model& other) const; virtual bool eq_nonarray_attributes(const Model& other, const bool ignore_name = false) const; bool operator == (const Model& other) const { return __eq__(other);} bool operator != (const Model& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_species(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_reaction_rules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_surface_classes(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_elementary_molecule_types(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_release_sites(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_geometry_objects(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_checkpointed_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_viz_outputs(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); virtual std::string export_vec_counts(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- Config config; virtual void set_config(const Config& new_config_) { config = new_config_; } virtual const Config& get_config() const { return config; } Warnings warnings; virtual void set_warnings(const Warnings& new_warnings_) { warnings = new_warnings_; } virtual const Warnings& get_warnings() const { return warnings; } Notifications notifications; virtual void set_notifications(const Notifications& new_notifications_) { notifications = new_notifications_; } virtual const Notifications& get_notifications() const { return notifications; } // --- methods --- virtual void initialize(const bool print_copyright = true) = 0; virtual uint64_t run_iterations(const double iterations) = 0; virtual void end_simulation(const bool print_final_report = true) = 0; virtual void add_subsystem(std::shared_ptr<Subsystem> subsystem) = 0; virtual void add_instantiation(std::shared_ptr<Instantiation> instantiation) = 0; virtual void add_observables(std::shared_ptr<Observables> observables) = 0; virtual void dump_internal_state(const bool with_geometry = false) = 0; virtual void export_data_model(const std::string& file = STR_UNSET) = 0; virtual void export_viz_data_model(const std::string& file = STR_UNSET) = 0; virtual void export_geometry(const std::string& output_files_prefix = STR_UNSET) = 0; virtual void release_molecules(std::shared_ptr<ReleaseSite> release_site) = 0; virtual std::vector<int> run_reaction(std::shared_ptr<ReactionRule> reaction_rule, const std::vector<int> reactant_ids, const double time) = 0; virtual void add_vertex_move(std::shared_ptr<GeometryObject> object, const int vertex_index, const std::vector<double> displacement) = 0; virtual std::vector<std::shared_ptr<WallWallHitInfo>> apply_vertex_moves(const bool collect_wall_wall_hits = false, const bool randomize_order = true) = 0; virtual void pair_molecules(const int id1, const int id2) = 0; virtual void unpair_molecules(const int id1, const int id2) = 0; virtual int get_paired_molecule(const int id) = 0; virtual std::map<uint, uint> get_paired_molecules() = 0; virtual void register_mol_wall_hit_callback(const std::function<void(std::shared_ptr<MolWallHitInfo>, py::object)> function, py::object context, std::shared_ptr<GeometryObject> object = nullptr, std::shared_ptr<Species> species = nullptr) = 0; virtual void register_reaction_callback(const std::function<bool(std::shared_ptr<ReactionInfo>, py::object)> function, py::object context, std::shared_ptr<ReactionRule> reaction_rule) = 0; virtual void load_bngl(const std::string& file_name, const std::string& observables_path_or_file = STR_UNSET, std::shared_ptr<Region> default_release_region = nullptr, const std::map<std::string, double>& parameter_overrides = std::map<std::string, double>(), const CountOutputFormat observables_output_format = CountOutputFormat::AUTOMATIC_FROM_EXTENSION) = 0; virtual void export_to_bngl(const std::string& file_name, const BNGSimulationMethod simulation_method = BNGSimulationMethod::ODE) = 0; virtual void save_checkpoint(const std::string& custom_dir = STR_UNSET) = 0; virtual void schedule_checkpoint(const uint64_t iteration = 0, const bool continue_simulation = false, const std::string& custom_dir = STR_UNSET) = 0; }; // GenModel class Model; py::class_<Model> define_pybinding_Model(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_MODEL_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_base_chkpt_mol.h
.h
5,717
166
/****************************************************************************** * * Copyright (C) 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 API_GEN_BASE_CHKPT_MOL_H #define API_GEN_BASE_CHKPT_MOL_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class BaseChkptMol; class Species; class PythonExportContext; #define BASE_CHKPT_MOL_CTOR() \ BaseChkptMol( \ const int id_, \ std::shared_ptr<Species> species_, \ const double diffusion_time_, \ const double birthday_, \ const int flags_, \ const double unimol_rxn_time_ = FLT_UNSET \ ) { \ class_name = "BaseChkptMol"; \ id = id_; \ species = species_; \ diffusion_time = diffusion_time_; \ birthday = birthday_; \ flags = flags_; \ unimol_rxn_time = unimol_rxn_time_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ BaseChkptMol(DefaultCtorArgType) : \ GenBaseChkptMol(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenBaseChkptMol: public BaseDataClass { public: GenBaseChkptMol() { } GenBaseChkptMol(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<BaseChkptMol> copy_base_chkpt_mol() const; std::shared_ptr<BaseChkptMol> deepcopy_base_chkpt_mol(py::dict = py::dict()) const; virtual bool __eq__(const BaseChkptMol& other) const; virtual bool eq_nonarray_attributes(const BaseChkptMol& other, const bool ignore_name = false) const; bool operator == (const BaseChkptMol& other) const { return __eq__(other);} bool operator != (const BaseChkptMol& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- int id; virtual void set_id(const int new_id_) { if (initialized) { throw RuntimeError("Value 'id' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; id = new_id_; } virtual int get_id() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return id; } std::shared_ptr<Species> species; virtual void set_species(std::shared_ptr<Species> new_species_) { if (initialized) { throw RuntimeError("Value 'species' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; species = new_species_; } virtual std::shared_ptr<Species> get_species() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return species; } double diffusion_time; virtual void set_diffusion_time(const double new_diffusion_time_) { if (initialized) { throw RuntimeError("Value 'diffusion_time' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; diffusion_time = new_diffusion_time_; } virtual double get_diffusion_time() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return diffusion_time; } double birthday; virtual void set_birthday(const double new_birthday_) { if (initialized) { throw RuntimeError("Value 'birthday' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; birthday = new_birthday_; } virtual double get_birthday() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return birthday; } int flags; virtual void set_flags(const int new_flags_) { if (initialized) { throw RuntimeError("Value 'flags' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; flags = new_flags_; } virtual int get_flags() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return flags; } double unimol_rxn_time; virtual void set_unimol_rxn_time(const double new_unimol_rxn_time_) { if (initialized) { throw RuntimeError("Value 'unimol_rxn_time' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; unimol_rxn_time = new_unimol_rxn_time_; } virtual double get_unimol_rxn_time() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return unimol_rxn_time; } // --- methods --- }; // GenBaseChkptMol class BaseChkptMol; py::class_<BaseChkptMol> define_pybinding_BaseChkptMol(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_BASE_CHKPT_MOL_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_color.h
.h
4,688
149
/****************************************************************************** * * Copyright (C) 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 API_GEN_COLOR_H #define API_GEN_COLOR_H #include "api/api_common.h" #include "api/base_data_class.h" namespace MCell { namespace API { class Color; class PythonExportContext; #define COLOR_CTOR() \ Color( \ const double red_ = FLT_UNSET, \ const double green_ = FLT_UNSET, \ const double blue_ = FLT_UNSET, \ const double alpha_ = 1, \ const uint rgba_ = 0 \ ) { \ class_name = "Color"; \ red = red_; \ green = green_; \ blue = blue_; \ alpha = alpha_; \ rgba = rgba_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Color(DefaultCtorArgType) : \ GenColor(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenColor: public BaseDataClass { public: GenColor() { } GenColor(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Color> copy_color() const; std::shared_ptr<Color> deepcopy_color(py::dict = py::dict()) const; virtual bool __eq__(const Color& other) const; virtual bool eq_nonarray_attributes(const Color& other, const bool ignore_name = false) const; bool operator == (const Color& other) const { return __eq__(other);} bool operator != (const Color& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; std::string export_to_python(std::ostream& out, PythonExportContext& ctx) override; // --- attributes --- double red; virtual void set_red(const double new_red_) { if (initialized) { throw RuntimeError("Value 'red' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; red = new_red_; } virtual double get_red() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return red; } double green; virtual void set_green(const double new_green_) { if (initialized) { throw RuntimeError("Value 'green' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; green = new_green_; } virtual double get_green() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return green; } double blue; virtual void set_blue(const double new_blue_) { if (initialized) { throw RuntimeError("Value 'blue' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; blue = new_blue_; } virtual double get_blue() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return blue; } double alpha; virtual void set_alpha(const double new_alpha_) { if (initialized) { throw RuntimeError("Value 'alpha' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; alpha = new_alpha_; } virtual double get_alpha() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return alpha; } uint rgba; virtual void set_rgba(const uint new_rgba_) { if (initialized) { throw RuntimeError("Value 'rgba' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; rgba = new_rgba_; } virtual uint get_rgba() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return rgba; } // --- methods --- }; // GenColor class Color; py::class_<Color> define_pybinding_Color(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_COLOR_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_chkpt_surf_mol.h
.h
6,163
173
/****************************************************************************** * * Copyright (C) 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 API_GEN_CHKPT_SURF_MOL_H #define API_GEN_CHKPT_SURF_MOL_H #include "api/api_common.h" #include "api/base_chkpt_mol.h" namespace MCell { namespace API { class ChkptSurfMol; class GeometryObject; class Species; class PythonExportContext; #define CHKPT_SURF_MOL_CTOR() \ ChkptSurfMol( \ const Vec2& pos_, \ const Orientation orientation_, \ std::shared_ptr<GeometryObject> geometry_object_, \ const int wall_index_, \ const int grid_tile_index_, \ const int id_, \ std::shared_ptr<Species> species_, \ const double diffusion_time_, \ const double birthday_, \ const int flags_, \ const double unimol_rxn_time_ = FLT_UNSET \ ) : GenChkptSurfMol(id_,species_,diffusion_time_,birthday_,flags_,unimol_rxn_time_) { \ class_name = "ChkptSurfMol"; \ pos = pos_; \ orientation = orientation_; \ geometry_object = geometry_object_; \ wall_index = wall_index_; \ grid_tile_index = grid_tile_index_; \ id = id_; \ species = species_; \ diffusion_time = diffusion_time_; \ birthday = birthday_; \ flags = flags_; \ unimol_rxn_time = unimol_rxn_time_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ ChkptSurfMol(DefaultCtorArgType) : \ GenChkptSurfMol(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenChkptSurfMol: public BaseChkptMol { public: GenChkptSurfMol( const int id_, std::shared_ptr<Species> species_, const double diffusion_time_, const double birthday_, const int flags_, const double unimol_rxn_time_ = FLT_UNSET ) : BaseChkptMol(id_,species_,diffusion_time_,birthday_,flags_,unimol_rxn_time_) { } GenChkptSurfMol() : BaseChkptMol(DefaultCtorArgType()) { } GenChkptSurfMol(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<ChkptSurfMol> copy_chkpt_surf_mol() const; std::shared_ptr<ChkptSurfMol> deepcopy_chkpt_surf_mol(py::dict = py::dict()) const; virtual bool __eq__(const ChkptSurfMol& other) const; virtual bool eq_nonarray_attributes(const ChkptSurfMol& other, const bool ignore_name = false) const; bool operator == (const ChkptSurfMol& other) const { return __eq__(other);} bool operator != (const ChkptSurfMol& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); // --- attributes --- Vec2 pos; virtual void set_pos(const Vec2& new_pos_) { if (initialized) { throw RuntimeError("Value 'pos' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; pos = new_pos_; } virtual const Vec2& get_pos() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return pos; } Orientation orientation; virtual void set_orientation(const Orientation new_orientation_) { if (initialized) { throw RuntimeError("Value 'orientation' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; orientation = new_orientation_; } virtual Orientation get_orientation() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return orientation; } std::shared_ptr<GeometryObject> geometry_object; virtual void set_geometry_object(std::shared_ptr<GeometryObject> new_geometry_object_) { if (initialized) { throw RuntimeError("Value 'geometry_object' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; geometry_object = new_geometry_object_; } virtual std::shared_ptr<GeometryObject> get_geometry_object() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return geometry_object; } int wall_index; virtual void set_wall_index(const int new_wall_index_) { if (initialized) { throw RuntimeError("Value 'wall_index' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; wall_index = new_wall_index_; } virtual int get_wall_index() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return wall_index; } int grid_tile_index; virtual void set_grid_tile_index(const int new_grid_tile_index_) { if (initialized) { throw RuntimeError("Value 'grid_tile_index' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; grid_tile_index = new_grid_tile_index_; } virtual int get_grid_tile_index() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return grid_tile_index; } // --- methods --- }; // GenChkptSurfMol class ChkptSurfMol; py::class_<ChkptSurfMol> define_pybinding_ChkptSurfMol(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_CHKPT_SURF_MOL_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_species.h
.h
6,693
167
/****************************************************************************** * * Copyright (C) 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 API_GEN_SPECIES_H #define API_GEN_SPECIES_H #include "api/api_common.h" #include "api/complex.h" namespace MCell { namespace API { class Complex; class ElementaryMolecule; class Species; class PythonExportContext; #define SPECIES_CTOR() \ Species( \ const std::string& name_ = STR_UNSET, \ const double diffusion_constant_2d_ = FLT_UNSET, \ const double diffusion_constant_3d_ = FLT_UNSET, \ const double custom_time_step_ = FLT_UNSET, \ const double custom_space_step_ = FLT_UNSET, \ const bool target_only_ = false, \ const std::vector<std::shared_ptr<ElementaryMolecule>> elementary_molecules_ = std::vector<std::shared_ptr<ElementaryMolecule>>(), \ const Orientation orientation_ = Orientation::DEFAULT, \ const std::string& compartment_name_ = STR_UNSET \ ) : GenSpecies(name_,elementary_molecules_,orientation_,compartment_name_) { \ class_name = "Species"; \ name = name_; \ diffusion_constant_2d = diffusion_constant_2d_; \ diffusion_constant_3d = diffusion_constant_3d_; \ custom_time_step = custom_time_step_; \ custom_space_step = custom_space_step_; \ target_only = target_only_; \ elementary_molecules = elementary_molecules_; \ orientation = orientation_; \ compartment_name = compartment_name_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ Species(DefaultCtorArgType) : \ GenSpecies(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenSpecies: public Complex { public: GenSpecies( const std::string& name_ = STR_UNSET, const std::vector<std::shared_ptr<ElementaryMolecule>> elementary_molecules_ = std::vector<std::shared_ptr<ElementaryMolecule>>(), const Orientation orientation_ = Orientation::DEFAULT, const std::string& compartment_name_ = STR_UNSET ) : Complex(name_,elementary_molecules_,orientation_,compartment_name_) { } GenSpecies(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<Species> copy_species() const; std::shared_ptr<Species> deepcopy_species(py::dict = py::dict()) const; virtual bool __eq__(const Species& other) const; virtual bool eq_nonarray_attributes(const Species& other, const bool ignore_name = false) const; bool operator == (const Species& other) const { return __eq__(other);} bool operator != (const Species& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_elementary_molecules(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- double diffusion_constant_2d; virtual void set_diffusion_constant_2d(const double new_diffusion_constant_2d_) { if (initialized) { throw RuntimeError("Value 'diffusion_constant_2d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; diffusion_constant_2d = new_diffusion_constant_2d_; } virtual double get_diffusion_constant_2d() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return diffusion_constant_2d; } double diffusion_constant_3d; virtual void set_diffusion_constant_3d(const double new_diffusion_constant_3d_) { if (initialized) { throw RuntimeError("Value 'diffusion_constant_3d' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; diffusion_constant_3d = new_diffusion_constant_3d_; } virtual double get_diffusion_constant_3d() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return diffusion_constant_3d; } double custom_time_step; virtual void set_custom_time_step(const double new_custom_time_step_) { if (initialized) { throw RuntimeError("Value 'custom_time_step' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; custom_time_step = new_custom_time_step_; } virtual double get_custom_time_step() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return custom_time_step; } double custom_space_step; virtual void set_custom_space_step(const double new_custom_space_step_) { if (initialized) { throw RuntimeError("Value 'custom_space_step' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; custom_space_step = new_custom_space_step_; } virtual double get_custom_space_step() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return custom_space_step; } bool target_only; virtual void set_target_only(const bool new_target_only_) { if (initialized) { throw RuntimeError("Value 'target_only' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; target_only = new_target_only_; } virtual bool get_target_only() const { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return target_only; } // --- methods --- virtual std::shared_ptr<Complex> inst(const Orientation orientation = Orientation::DEFAULT, const std::string& compartment_name = STR_UNSET) = 0; }; // GenSpecies class Species; py::class_<Species> define_pybinding_Species(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_SPECIES_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_wall.cpp
.cpp
5,871
159
/****************************************************************************** * * Copyright (C) 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 <sstream> #include "api/pybind11_stl_include.h" #include "api/python_export_utils.h" #include "gen_wall.h" #include "api/wall.h" #include "api/geometry_object.h" namespace MCell { namespace API { void GenWall::check_semantics() const { if (!is_set(geometry_object)) { throw ValueError("Parameter 'geometry_object' must be set."); } if (!is_set(wall_index)) { throw ValueError("Parameter 'wall_index' must be set."); } if (!is_set(vertices)) { throw ValueError("Parameter 'vertices' must be set and the value must not be an empty list."); } if (!is_set(area)) { throw ValueError("Parameter 'area' must be set."); } if (!is_set(unit_normal)) { throw ValueError("Parameter 'unit_normal' must be set and the value must not be an empty list."); } } void GenWall::set_initialized() { if (is_set(geometry_object)) { geometry_object->set_initialized(); } initialized = true; } void GenWall::set_all_attributes_as_default_or_unset() { class_name = "Wall"; geometry_object = nullptr; wall_index = INT_UNSET; vertices = std::vector<std::vector<double>>(); area = FLT_UNSET; unit_normal = std::vector<double>(); is_movable = true; } std::shared_ptr<Wall> GenWall::copy_wall() const { std::shared_ptr<Wall> res = std::make_shared<Wall>(DefaultCtorArgType()); res->class_name = class_name; res->geometry_object = geometry_object; res->wall_index = wall_index; res->vertices = vertices; res->area = area; res->unit_normal = unit_normal; res->is_movable = is_movable; return res; } std::shared_ptr<Wall> GenWall::deepcopy_wall(py::dict) const { std::shared_ptr<Wall> res = std::make_shared<Wall>(DefaultCtorArgType()); res->class_name = class_name; res->geometry_object = is_set(geometry_object) ? geometry_object->deepcopy_geometry_object() : nullptr; res->wall_index = wall_index; res->vertices = vertices; res->area = area; res->unit_normal = unit_normal; res->is_movable = is_movable; return res; } bool GenWall::__eq__(const Wall& other) const { return ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && vertices == other.vertices && area == other.area && unit_normal == other.unit_normal && is_movable == other.is_movable; } bool GenWall::eq_nonarray_attributes(const Wall& other, const bool ignore_name) const { return ( (is_set(geometry_object)) ? (is_set(other.geometry_object) ? (geometry_object->__eq__(*other.geometry_object)) : false ) : (is_set(other.geometry_object) ? false : true ) ) && wall_index == other.wall_index && true /*vertices*/ && area == other.area && true /*unit_normal*/ && is_movable == other.is_movable; } std::string GenWall::to_str(const bool all_details, const std::string ind) const { std::stringstream ss; ss << get_object_name() << ": " << "\n" << ind + " " << "geometry_object=" << "(" << ((geometry_object != nullptr) ? geometry_object->to_str(all_details, ind + " ") : "null" ) << ")" << ", " << "\n" << ind + " " << "wall_index=" << wall_index << ", " << "vertices=" << vec_nonptr_to_str(vertices, all_details, ind + " ") << ", " << "area=" << area << ", " << "unit_normal=" << vec_nonptr_to_str(unit_normal, all_details, ind + " ") << ", " << "is_movable=" << is_movable; return ss.str(); } py::class_<Wall> define_pybinding_Wall(py::module& m) { return py::class_<Wall, std::shared_ptr<Wall>>(m, "Wall", "Constant representation of wall of a geometry object.\nChanges through changing attributes of this object are not allowed\nexcept for the attribute is_movable.\n") .def( py::init< >() ) .def("check_semantics", &Wall::check_semantics) .def("__copy__", &Wall::copy_wall) .def("__deepcopy__", &Wall::deepcopy_wall, py::arg("memo")) .def("__str__", &Wall::to_str, py::arg("all_details") = false, py::arg("ind") = std::string("")) .def("__eq__", &Wall::__eq__, py::arg("other")) .def("dump", &Wall::dump) .def_property("geometry_object", &Wall::get_geometry_object, &Wall::set_geometry_object, "Object to which this wall belongs.") .def_property("wall_index", &Wall::get_wall_index, &Wall::set_wall_index, "Index of this wall in the object to which this wall belongs.") .def_property("vertices", &Wall::get_vertices, &Wall::set_vertices, py::return_value_policy::reference, "Vertices of the triangle that represents this wall.") .def_property("area", &Wall::get_area, &Wall::set_area, "Area of the wall in um^2.") .def_property("unit_normal", &Wall::get_unit_normal, &Wall::set_unit_normal, py::return_value_policy::reference, "Normal of this wall with unit length of 1 um.\nThere is also a method Model.get_wall_unit_normal that allows to \nretrieve just the normal value without the need to prepare this \nwhole Wall object. \n") .def_property("is_movable", &Wall::get_is_movable, &Wall::set_is_movable, "If True, whis wall can be moved through Model.apply_vertex_moves,\nif False, wall moves are ignored. \nCan be set during simulation.\n") ; } } // namespace API } // namespace MCell
C++
3D
mcellteam/mcell
libmcell/generated/gen_names.h
.h
22,427
411
/****************************************************************************** * * Copyright (C) 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 API_GEN_NAMES #define API_GEN_NAMES namespace MCell { namespace API { const char* const NAME_CLASS_BASE_CHKPT_MOL = "BaseChkptMol"; const char* const NAME_CLASS_BNGL_UTILS = "bngl_utils"; const char* const NAME_CLASS_CHKPT_SURF_MOL = "ChkptSurfMol"; const char* const NAME_CLASS_CHKPT_VOL_MOL = "ChkptVolMol"; const char* const NAME_CLASS_COLOR = "Color"; const char* const NAME_CLASS_COMPLEX = "Complex"; const char* const NAME_CLASS_COMPONENT = "Component"; const char* const NAME_CLASS_COMPONENT_TYPE = "ComponentType"; const char* const NAME_CLASS_CONFIG = "Config"; const char* const NAME_CLASS_COUNT = "Count"; const char* const NAME_CLASS_COUNT_TERM = "CountTerm"; const char* const NAME_CLASS_DATA_UTILS = "data_utils"; const char* const NAME_CLASS_ELEMENTARY_MOLECULE = "ElementaryMolecule"; const char* const NAME_CLASS_ELEMENTARY_MOLECULE_TYPE = "ElementaryMoleculeType"; const char* const NAME_CLASS_GEOMETRY_UTILS = "geometry_utils"; const char* const NAME_CLASS_GEOMETRY_OBJECT = "GeometryObject"; const char* const NAME_CLASS_INITIAL_SURFACE_RELEASE = "InitialSurfaceRelease"; const char* const NAME_CLASS_INSTANTIATION = "Instantiation"; const char* const NAME_CLASS_INTROSPECTION = "Introspection"; const char* const NAME_CLASS_MODEL = "Model"; const char* const NAME_CLASS_MOLECULE = "Molecule"; const char* const NAME_CLASS_MOLECULE_RELEASE_INFO = "MoleculeReleaseInfo"; const char* const NAME_CLASS_MOL_WALL_HIT_INFO = "MolWallHitInfo"; const char* const NAME_CLASS_NOTIFICATIONS = "Notifications"; const char* const NAME_CLASS_OBSERVABLES = "Observables"; const char* const NAME_CLASS_REACTION_INFO = "ReactionInfo"; const char* const NAME_CLASS_REACTION_RULE = "ReactionRule"; const char* const NAME_CLASS_REGION = "Region"; const char* const NAME_CLASS_RELEASE_PATTERN = "ReleasePattern"; const char* const NAME_CLASS_RELEASE_SITE = "ReleaseSite"; const char* const NAME_CLASS_RNG_STATE = "RngState"; const char* const NAME_CLASS_RUN_UTILS = "run_utils"; const char* const NAME_CLASS_SPECIES = "Species"; const char* const NAME_CLASS_SUBSYSTEM = "Subsystem"; const char* const NAME_CLASS_SURFACE_CLASS = "SurfaceClass"; const char* const NAME_CLASS_SURFACE_PROPERTY = "SurfaceProperty"; const char* const NAME_CLASS_SURFACE_REGION = "SurfaceRegion"; const char* const NAME_CLASS_VIZ_OUTPUT = "VizOutput"; const char* const NAME_CLASS_WALL = "Wall"; const char* const NAME_CLASS_WALL_WALL_HIT_INFO = "WallWallHitInfo"; const char* const NAME_CLASS_WARNINGS = "Warnings"; const char* const NAME___ADD__ = "__add__"; const char* const NAME___MUL__ = "__mul__"; const char* const NAME___SUB__ = "__sub__"; const char* const NAME_AA = "aa"; const char* const NAME_ADD_COUNT = "add_count"; const char* const NAME_ADD_ELEMENTARY_MOLECULE_TYPE = "add_elementary_molecule_type"; const char* const NAME_ADD_GEOMETRY_OBJECT = "add_geometry_object"; const char* const NAME_ADD_INSTANTIATION = "add_instantiation"; const char* const NAME_ADD_OBSERVABLES = "add_observables"; const char* const NAME_ADD_REACTION_RULE = "add_reaction_rule"; const char* const NAME_ADD_RELEASE_SITE = "add_release_site"; const char* const NAME_ADD_SPECIES = "add_species"; const char* const NAME_ADD_SUBSYSTEM = "add_subsystem"; const char* const NAME_ADD_SURFACE_CLASS = "add_surface_class"; const char* const NAME_ADD_VERTEX_MOVE = "add_vertex_move"; const char* const NAME_ADD_VIZ_OUTPUT = "add_viz_output"; const char* const NAME_AFFECTED_COMPLEX_PATTERN = "affected_complex_pattern"; const char* const NAME_ALPHA = "alpha"; const char* const NAME_APPEND_TO_COUNT_OUTPUT_DATA = "append_to_count_output_data"; const char* const NAME_APPLY_VERTEX_MOVES = "apply_vertex_moves"; const char* const NAME_AREA = "area"; const char* const NAME_AS_SPECIES = "as_species"; const char* const NAME_BB = "bb"; const char* const NAME_BIRTHDAY = "birthday"; const char* const NAME_BLUE = "blue"; const char* const NAME_BNG_VERBOSITY_LEVEL = "bng_verbosity_level"; const char* const NAME_BOND = "bond"; const char* const NAME_CC = "cc"; const char* const NAME_CENTER_MOLECULES_ON_GRID = "center_molecules_on_grid"; const char* const NAME_CHECK_OVERLAPPED_WALLS = "check_overlapped_walls"; const char* const NAME_CHECKPOINTED_MOLECULES = "checkpointed_molecules"; const char* const NAME_COLLECT_WALL_WALL_HITS = "collect_wall_wall_hits"; const char* const NAME_COLOR = "color"; const char* const NAME_COMPARTMENT_NAME = "compartment_name"; const char* const NAME_COMPLEX = "complex"; const char* const NAME_COMPONENT_TYPE = "component_type"; const char* const NAME_COMPONENTS = "components"; const char* const NAME_CONCENTRATION = "concentration"; const char* const NAME_CONFIG = "config"; const char* const NAME_CONTEXT = "context"; const char* const NAME_CONTINUE_AFTER_SIGALRM = "continue_after_sigalrm"; const char* const NAME_CONTINUE_SIMULATION = "continue_simulation"; const char* const NAME_COUNT = "count"; const char* const NAME_COUNTS = "counts"; const char* const NAME_CREATE_BOX = "create_box"; const char* const NAME_CREATE_ICOSPHERE = "create_icosphere"; const char* const NAME_CUSTOM_DIR = "custom_dir"; const char* const NAME_CUSTOM_SPACE_STEP = "custom_space_step"; const char* const NAME_CUSTOM_TIME_STEP = "custom_time_step"; const char* const NAME_DEFAULT_RELEASE_REGION = "default_release_region"; const char* const NAME_DENSITY = "density"; const char* const NAME_DIFFUSION_CONSTANT_2D = "diffusion_constant_2d"; const char* const NAME_DIFFUSION_CONSTANT_3D = "diffusion_constant_3d"; const char* const NAME_DIFFUSION_TIME = "diffusion_time"; const char* const NAME_DISPLACEMENT = "displacement"; const char* const NAME_DUMP_INTERNAL_STATE = "dump_internal_state"; const char* const NAME_EDGE_DIMENSION = "edge_dimension"; const char* const NAME_ELEMENTARY_MOLECULE_TYPE = "elementary_molecule_type"; const char* const NAME_ELEMENTARY_MOLECULE_TYPES = "elementary_molecule_types"; const char* const NAME_ELEMENTARY_MOLECULES = "elementary_molecules"; const char* const NAME_END_SIMULATION = "end_simulation"; const char* const NAME_EVERY_N_TIMESTEPS = "every_n_timesteps"; const char* const NAME_EXPORT_DATA_MODEL = "export_data_model"; const char* const NAME_EXPORT_GEOMETRY = "export_geometry"; const char* const NAME_EXPORT_TO_BNGL = "export_to_bngl"; const char* const NAME_EXPORT_VIZ_DATA_MODEL = "export_viz_data_model"; const char* const NAME_EXPRESSION = "expression"; const char* const NAME_FILE = "file"; const char* const NAME_FILE_NAME = "file_name"; const char* const NAME_FIND_COUNT = "find_count"; const char* const NAME_FIND_ELEMENTARY_MOLECULE_TYPE = "find_elementary_molecule_type"; const char* const NAME_FIND_GEOMETRY_OBJECT = "find_geometry_object"; const char* const NAME_FIND_REACTION_RULE = "find_reaction_rule"; const char* const NAME_FIND_RELEASE_SITE = "find_release_site"; const char* const NAME_FIND_SPECIES = "find_species"; const char* const NAME_FIND_SURFACE_CLASS = "find_surface_class"; const char* const NAME_FIND_SURFACE_COMPARTMENT_OBJECT = "find_surface_compartment_object"; const char* const NAME_FIND_VOLUME_COMPARTMENT_OBJECT = "find_volume_compartment_object"; const char* const NAME_FLAGS = "flags"; const char* const NAME_FUNCTION = "function"; const char* const NAME_FWD_RATE = "fwd_rate"; const char* const NAME_GEOMETRY_OBJECT = "geometry_object"; const char* const NAME_GEOMETRY_OBJECTS = "geometry_objects"; const char* const NAME_GET_CURRENT_VALUE = "get_current_value"; const char* const NAME_GET_LAST_CHECKPOINT_DIR = "get_last_checkpoint_dir"; const char* const NAME_GET_MOLECULE = "get_molecule"; const char* const NAME_GET_MOLECULE_IDS = "get_molecule_ids"; const char* const NAME_GET_PAIRED_MOLECULE = "get_paired_molecule"; const char* const NAME_GET_PAIRED_MOLECULES = "get_paired_molecules"; const char* const NAME_GET_SPECIES_NAME = "get_species_name"; const char* const NAME_GET_VERTEX = "get_vertex"; const char* const NAME_GET_VERTEX_UNIT_NORMAL = "get_vertex_unit_normal"; const char* const NAME_GET_WALL = "get_wall"; const char* const NAME_GET_WALL_COLOR = "get_wall_color"; const char* const NAME_GET_WALL_UNIT_NORMAL = "get_wall_unit_normal"; const char* const NAME_GREEN = "green"; const char* const NAME_GRID_TILE_INDEX = "grid_tile_index"; const char* const NAME_HIGH_REACTION_PROBABILITY = "high_reaction_probability"; const char* const NAME_ID = "id"; const char* const NAME_ID1 = "id1"; const char* const NAME_ID2 = "id2"; const char* const NAME_INITIAL_COLOR = "initial_color"; const char* const NAME_INITIAL_ITERATION = "initial_iteration"; const char* const NAME_INITIAL_PARTITION_ORIGIN = "initial_partition_origin"; const char* const NAME_INITIAL_REACTIONS_COUNT = "initial_reactions_count"; const char* const NAME_INITIAL_RNG_STATE = "initial_rng_state"; const char* const NAME_INITIAL_SURFACE_RELEASES = "initial_surface_releases"; const char* const NAME_INITIAL_TIME = "initial_time"; const char* const NAME_INITIALIZE = "initialize"; const char* const NAME_INST = "inst"; const char* const NAME_INSTANTIATION = "instantiation"; const char* const NAME_INTERACTION_RADIUS = "interaction_radius"; const char* const NAME_INTERMEMBRANE_INTERACTION_RADIUS = "intermembrane_interaction_radius"; const char* const NAME_IS_BNGL_COMPARTMENT = "is_bngl_compartment"; const char* const NAME_IS_INTERMEMBRANE_SURFACE_REACTION = "is_intermembrane_surface_reaction"; const char* const NAME_IS_MOVABLE = "is_movable"; const char* const NAME_ITERATION = "iteration"; const char* const NAME_ITERATION_REPORT = "iteration_report"; const char* const NAME_ITERATIONS = "iterations"; const char* const NAME_LEFT_NODE = "left_node"; const char* const NAME_LOAD_BNGL = "load_bngl"; const char* const NAME_LOAD_BNGL_COMPARTMENTS_AND_SEED_SPECIES = "load_bngl_compartments_and_seed_species"; const char* const NAME_LOAD_BNGL_MOLECULE_TYPES_AND_REACTION_RULES = "load_bngl_molecule_types_and_reaction_rules"; const char* const NAME_LOAD_BNGL_OBSERVABLES = "load_bngl_observables"; const char* const NAME_LOAD_BNGL_PARAMETERS = "load_bngl_parameters"; const char* const NAME_LOAD_DAT_FILE = "load_dat_file"; const char* const NAME_LOCATION = "location"; const char* const NAME_MEMORY_LIMIT_GB = "memory_limit_gb"; const char* const NAME_MM = "mm"; const char* const NAME_MODE = "mode"; const char* const NAME_MODEL = "model"; const char* const NAME_MOLECULE_ID = "molecule_id"; const char* const NAME_MOLECULE_LIST = "molecule_list"; const char* const NAME_MOLECULE_PLACEMENT_FAILURE = "molecule_placement_failure"; const char* const NAME_MOLECULES_ORDER_RANDOM_SHUFFLE_PERIODICITY = "molecules_order_random_shuffle_periodicity"; const char* const NAME_MOLECULES_PATTERN = "molecules_pattern"; const char* const NAME_MOVE = "move"; const char* const NAME_MT = "mt"; const char* const NAME_MULTIPLIER = "multiplier"; const char* const NAME_NAME = "name"; const char* const NAME_NODE_TYPE = "node_type"; const char* const NAME_NOTIFICATIONS = "notifications"; const char* const NAME_NUMBER_OF_TRAINS = "number_of_trains"; const char* const NAME_NUMBER_TO_RELEASE = "number_to_release"; const char* const NAME_O = "o"; const char* const NAME_OBJECT = "object"; const char* const NAME_OBSERVABLES = "observables"; const char* const NAME_OBSERVABLES_OUTPUT_FORMAT = "observables_output_format"; const char* const NAME_OBSERVABLES_PATH_OR_FILE = "observables_path_or_file"; const char* const NAME_OP2 = "op2"; const char* const NAME_ORIENTATION = "orientation"; const char* const NAME_OTHER = "other"; const char* const NAME_OUTPUT_FILES_PREFIX = "output_files_prefix"; const char* const NAME_OUTPUT_FORMAT = "output_format"; const char* const NAME_PAIR_MOLECULES = "pair_molecules"; const char* const NAME_PARAMETER_OVERRIDES = "parameter_overrides"; const char* const NAME_PARTITION_DIMENSION = "partition_dimension"; const char* const NAME_PATHS = "paths"; const char* const NAME_PATTERN = "pattern"; const char* const NAME_POS = "pos"; const char* const NAME_POS2D = "pos2d"; const char* const NAME_POS3D = "pos3d"; const char* const NAME_POS3D_BEFORE_HIT = "pos3d_before_hit"; const char* const NAME_PRINT_COPYRIGHT = "print_copyright"; const char* const NAME_PRINT_FINAL_REPORT = "print_final_report"; const char* const NAME_PRODUCT_IDS = "product_ids"; const char* const NAME_PRODUCTS = "products"; const char* const NAME_PROPERTIES = "properties"; const char* const NAME_R = "r"; const char* const NAME_RADIUS = "radius"; const char* const NAME_RANDCNT = "randcnt"; const char* const NAME_RANDOMIZE_ORDER = "randomize_order"; const char* const NAME_RANDSLR = "randslr"; const char* const NAME_REACTANT_IDS = "reactant_ids"; const char* const NAME_REACTANTS = "reactants"; const char* const NAME_REACTION_CLASS_CLEANUP_PERIODICITY = "reaction_class_cleanup_periodicity"; const char* const NAME_REACTION_RULE = "reaction_rule"; const char* const NAME_REACTION_RULES = "reaction_rules"; const char* const NAME_RED = "red"; const char* const NAME_REGION = "region"; const char* const NAME_REGISTER_MOL_WALL_HIT_CALLBACK = "register_mol_wall_hit_callback"; const char* const NAME_REGISTER_REACTION_CALLBACK = "register_reaction_callback"; const char* const NAME_RELEASE_INTERVAL = "release_interval"; const char* const NAME_RELEASE_MOLECULES = "release_molecules"; const char* const NAME_RELEASE_PATTERN = "release_pattern"; const char* const NAME_RELEASE_PROBABILITY = "release_probability"; const char* const NAME_RELEASE_SITE = "release_site"; const char* const NAME_RELEASE_SITES = "release_sites"; const char* const NAME_RELEASE_TIME = "release_time"; const char* const NAME_REMOVE = "remove"; const char* const NAME_REMOVE_CWD = "remove_cwd"; const char* const NAME_REV_NAME = "rev_name"; const char* const NAME_REV_RATE = "rev_rate"; const char* const NAME_RGBA = "rgba"; const char* const NAME_RIGHT_NODE = "right_node"; const char* const NAME_RNGBLOCKS = "rngblocks"; const char* const NAME_RUN_ITERATIONS = "run_iterations"; const char* const NAME_RUN_REACTION = "run_reaction"; const char* const NAME_RXN_AND_SPECIES_REPORT = "rxn_and_species_report"; const char* const NAME_RXN_PROBABILITY_CHANGED = "rxn_probability_changed"; const char* const NAME_S = "s"; const char* const NAME_SAVE_CHECKPOINT = "save_checkpoint"; const char* const NAME_SC = "sc"; const char* const NAME_SCHEDULE_CHECKPOINT = "schedule_checkpoint"; const char* const NAME_SEED = "seed"; const char* const NAME_SET_WALL_COLOR = "set_wall_color"; const char* const NAME_SHAPE = "shape"; const char* const NAME_SIMULATION_METHOD = "simulation_method"; const char* const NAME_SIMULATION_STATS_EVERY_N_ITERATIONS = "simulation_stats_every_n_iterations"; const char* const NAME_SITE_DIAMETER = "site_diameter"; const char* const NAME_SITE_RADIUS = "site_radius"; const char* const NAME_SORT_MOLECULES = "sort_molecules"; const char* const NAME_SPECIES = "species"; const char* const NAME_SPECIES_CLEANUP_PERIODICITY = "species_cleanup_periodicity"; const char* const NAME_SPECIES_ID = "species_id"; const char* const NAME_SPECIES_LIST = "species_list"; const char* const NAME_SPECIES_PATTERN = "species_pattern"; const char* const NAME_STATE = "state"; const char* const NAME_STATES = "states"; const char* const NAME_SUBDIVISIONS = "subdivisions"; const char* const NAME_SUBPARTITION_DIMENSION = "subpartition_dimension"; const char* const NAME_SUBSYSTEM = "subsystem"; const char* const NAME_SURFACE_CLASS = "surface_class"; const char* const NAME_SURFACE_CLASSES = "surface_classes"; const char* const NAME_SURFACE_COMPARTMENT_NAME = "surface_compartment_name"; const char* const NAME_SURFACE_GRID_DENSITY = "surface_grid_density"; const char* const NAME_SURFACE_REGIONS = "surface_regions"; const char* const NAME_TARGET_ONLY = "target_only"; const char* const NAME_TIME = "time"; const char* const NAME_TIME_BEFORE_HIT = "time_before_hit"; const char* const NAME_TIME_STEP = "time_step"; const char* const NAME_TO_BNGL_STR = "to_bngl_str"; const char* const NAME_TOTAL_ITERATIONS = "total_iterations"; const char* const NAME_TRAIN_DURATION = "train_duration"; const char* const NAME_TRAIN_INTERVAL = "train_interval"; const char* const NAME_TRANSLATE = "translate"; const char* const NAME_TYPE = "type"; const char* const NAME_UNIMOL_RXN_TIME = "unimol_rxn_time"; const char* const NAME_UNIT_NORMAL = "unit_normal"; const char* const NAME_UNPAIR_MOLECULES = "unpair_molecules"; const char* const NAME_USE_BNG_UNITS = "use_bng_units"; const char* const NAME_VACANCY_SEARCH_DISTANCE = "vacancy_search_distance"; const char* const NAME_VALIDATE_VOLUMETRIC_MESH = "validate_volumetric_mesh"; const char* const NAME_VARIABLE_RATE = "variable_rate"; const char* const NAME_VERTEX_INDEX = "vertex_index"; const char* const NAME_VERTEX_LIST = "vertex_list"; const char* const NAME_VERTICES = "vertices"; const char* const NAME_VIZ_OUTPUT = "viz_output"; const char* const NAME_VIZ_OUTPUTS = "viz_outputs"; const char* const NAME_WALL1 = "wall1"; const char* const NAME_WALL2 = "wall2"; const char* const NAME_WALL_INDEX = "wall_index"; const char* const NAME_WALL_INDICES = "wall_indices"; const char* const NAME_WALL_LIST = "wall_list"; const char* const NAME_WALL_OVERLAP_REPORT = "wall_overlap_report"; const char* const NAME_WARNINGS = "warnings"; const char* const NAME_WITH_COMPARTMENT = "with_compartment"; const char* const NAME_WITH_GEOMETRY = "with_geometry"; const char* const NAME_XYZ_DIMENSIONS = "xyz_dimensions"; const char* const NAME_ENUM_B_N_G_SIMULATION_METHOD = "BNGSimulationMethod"; const char* const NAME_ENUM_COUNT_OUTPUT_FORMAT = "CountOutputFormat"; const char* const NAME_ENUM_EXPR_NODE_TYPE = "ExprNodeType"; const char* const NAME_ENUM_MOLECULE_TYPE = "MoleculeType"; const char* const NAME_ENUM_NOTIFICATION = "Notification"; const char* const NAME_ENUM_ORIENTATION = "Orientation"; const char* const NAME_ENUM_REACTION_TYPE = "ReactionType"; const char* const NAME_ENUM_REGION_NODE_TYPE = "RegionNodeType"; const char* const NAME_ENUM_SHAPE = "Shape"; const char* const NAME_ENUM_SURFACE_PROPERTY_TYPE = "SurfacePropertyType"; const char* const NAME_ENUM_VIZ_MODE = "VizMode"; const char* const NAME_ENUM_WARNING_LEVEL = "WarningLevel"; const char* const NAME_EV_ABSORPTIVE = "ABSORPTIVE"; const char* const NAME_EV_ADD = "ADD"; const char* const NAME_EV_ANY = "ANY"; const char* const NAME_EV_ASCII = "ASCII"; const char* const NAME_EV_AUTOMATIC_FROM_EXTENSION = "AUTOMATIC_FROM_EXTENSION"; const char* const NAME_EV_BRIEF = "BRIEF"; const char* const NAME_EV_CELLBLENDER = "CELLBLENDER"; const char* const NAME_EV_CELLBLENDER_V1 = "CELLBLENDER_V1"; const char* const NAME_EV_COMPARTMENT = "COMPARTMENT"; const char* const NAME_EV_CONCENTRATION_CLAMP = "CONCENTRATION_CLAMP"; const char* const NAME_EV_DAT = "DAT"; const char* const NAME_EV_DEFAULT = "DEFAULT"; const char* const NAME_EV_DIFFERENCE = "DIFFERENCE"; const char* const NAME_EV_DOWN = "DOWN"; const char* const NAME_EV_ERROR = "ERROR"; const char* const NAME_EV_FLUX_CLAMP = "FLUX_CLAMP"; const char* const NAME_EV_FULL = "FULL"; const char* const NAME_EV_GDAT = "GDAT"; const char* const NAME_EV_IGNORE = "IGNORE"; const char* const NAME_EV_INTERSECT = "INTERSECT"; const char* const NAME_EV_LEAF = "LEAF"; const char* const NAME_EV_LEAF_GEOMETRY_OBJECT = "LEAF_GEOMETRY_OBJECT"; const char* const NAME_EV_LEAF_SURFACE_REGION = "LEAF_SURFACE_REGION"; const char* const NAME_EV_LIST = "LIST"; const char* const NAME_EV_NF = "NF"; const char* const NAME_EV_NONE = "NONE"; const char* const NAME_EV_NOT_SET = "NOT_SET"; const char* const NAME_EV_ODE = "ODE"; const char* const NAME_EV_PLA = "PLA"; const char* const NAME_EV_REACTIVE = "REACTIVE"; const char* const NAME_EV_REFLECTIVE = "REFLECTIVE"; const char* const NAME_EV_REGION_EXPR = "REGION_EXPR"; const char* const NAME_EV_SPHERICAL = "SPHERICAL"; const char* const NAME_EV_SSA = "SSA"; const char* const NAME_EV_SUB = "SUB"; const char* const NAME_EV_SURFACE = "SURFACE"; const char* const NAME_EV_SURFACE_SURFACE = "SURFACE_SURFACE"; const char* const NAME_EV_TRANSPARENT = "TRANSPARENT"; const char* const NAME_EV_UNIMOL_SURFACE = "UNIMOL_SURFACE"; const char* const NAME_EV_UNIMOL_VOLUME = "UNIMOL_VOLUME"; const char* const NAME_EV_UNION = "UNION"; const char* const NAME_EV_UNSET = "UNSET"; const char* const NAME_EV_UP = "UP"; const char* const NAME_EV_VOLUME = "VOLUME"; const char* const NAME_EV_VOLUME_SURFACE = "VOLUME_SURFACE"; const char* const NAME_EV_VOLUME_VOLUME = "VOLUME_VOLUME"; const char* const NAME_EV_WARNING = "WARNING"; const char* const NAME_CV_ALL_MOLECULES = "ALL_MOLECULES"; const char* const NAME_CV_ALL_SURFACE_MOLECULES = "ALL_SURFACE_MOLECULES"; const char* const NAME_CV_ALL_VOLUME_MOLECULES = "ALL_VOLUME_MOLECULES"; const char* const NAME_CV_AllMolecules = "AllMolecules"; const char* const NAME_CV_AllSurfaceMolecules = "AllSurfaceMolecules"; const char* const NAME_CV_AllVolumeMolecules = "AllVolumeMolecules"; const char* const NAME_CV_BOND_ANY = "BOND_ANY"; const char* const NAME_CV_BOND_BOUND = "BOND_BOUND"; const char* const NAME_CV_BOND_UNBOUND = "BOND_UNBOUND"; const char* const NAME_CV_DEFAULT_CHECKPOINTS_DIR = "DEFAULT_CHECKPOINTS_DIR"; const char* const NAME_CV_DEFAULT_COUNT_BUFFER_SIZE = "DEFAULT_COUNT_BUFFER_SIZE"; const char* const NAME_CV_DEFAULT_ITERATION_DIR_PREFIX = "DEFAULT_ITERATION_DIR_PREFIX"; const char* const NAME_CV_DEFAULT_SEED_DIR_DIGITS = "DEFAULT_SEED_DIR_DIGITS"; const char* const NAME_CV_DEFAULT_SEED_DIR_PREFIX = "DEFAULT_SEED_DIR_PREFIX"; const char* const NAME_CV_FLT_UNSET = "FLT_UNSET"; const char* const NAME_CV_ID_INVALID = "ID_INVALID"; const char* const NAME_CV_INT_UNSET = "INT_UNSET"; const char* const NAME_CV_NUMBER_OF_TRAINS_UNLIMITED = "NUMBER_OF_TRAINS_UNLIMITED"; const char* const NAME_CV_PARTITION_EDGE_EXTRA_MARGIN_UM = "PARTITION_EDGE_EXTRA_MARGIN_UM"; const char* const NAME_CV_RNG_SIZE = "RNG_SIZE"; const char* const NAME_CV_STATE_UNSET = "STATE_UNSET"; const char* const NAME_CV_STATE_UNSET_INT = "STATE_UNSET_INT"; const char* const NAME_CV_TIME_INFINITY = "TIME_INFINITY"; } // namespace API } // namespace MCell #endif // API_GEN_NAMES
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_surface_class.h
.h
3,802
101
/****************************************************************************** * * Copyright (C) 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 API_GEN_SURFACE_CLASS_H #define API_GEN_SURFACE_CLASS_H #include "api/api_common.h" #include "api/surface_property.h" namespace MCell { namespace API { class SurfaceClass; class Complex; class SurfaceProperty; class PythonExportContext; #define SURFACE_CLASS_CTOR() \ SurfaceClass( \ const std::string& name_, \ const std::vector<std::shared_ptr<SurfaceProperty>> properties_ = std::vector<std::shared_ptr<SurfaceProperty>>(), \ const SurfacePropertyType type_ = SurfacePropertyType::UNSET, \ std::shared_ptr<Complex> affected_complex_pattern_ = nullptr, \ const double concentration_ = FLT_UNSET \ ) : GenSurfaceClass(type_,affected_complex_pattern_,concentration_) { \ class_name = "SurfaceClass"; \ name = name_; \ properties = properties_; \ type = type_; \ affected_complex_pattern = affected_complex_pattern_; \ concentration = concentration_; \ postprocess_in_ctor(); \ check_semantics(); \ } \ SurfaceClass(DefaultCtorArgType) : \ GenSurfaceClass(DefaultCtorArgType()) { \ set_all_attributes_as_default_or_unset(); \ set_all_custom_attributes_to_default(); \ } class GenSurfaceClass: public SurfaceProperty { public: GenSurfaceClass( const SurfacePropertyType type_ = SurfacePropertyType::UNSET, std::shared_ptr<Complex> affected_complex_pattern_ = nullptr, const double concentration_ = FLT_UNSET ) : SurfaceProperty(type_,affected_complex_pattern_,concentration_) { } GenSurfaceClass(DefaultCtorArgType) { } void postprocess_in_ctor() override {} void check_semantics() const override; void set_initialized() override; void set_all_attributes_as_default_or_unset() override; std::shared_ptr<SurfaceClass> copy_surface_class() const; std::shared_ptr<SurfaceClass> deepcopy_surface_class(py::dict = py::dict()) const; virtual bool __eq__(const SurfaceClass& other) const; virtual bool eq_nonarray_attributes(const SurfaceClass& other, const bool ignore_name = false) const; bool operator == (const SurfaceClass& other) const { return __eq__(other);} bool operator != (const SurfaceClass& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const override; virtual std::string export_to_python(std::ostream& out, PythonExportContext& ctx); virtual std::string export_vec_properties(std::ostream& out, PythonExportContext& ctx, const std::string& parent_name); // --- attributes --- std::vector<std::shared_ptr<SurfaceProperty>> properties; virtual void set_properties(const std::vector<std::shared_ptr<SurfaceProperty>> new_properties_) { if (initialized) { throw RuntimeError("Value 'properties' of object with name " + name + " (class " + class_name + ") " "cannot be set after model was initialized."); } cached_data_are_uptodate = false; properties = new_properties_; } virtual std::vector<std::shared_ptr<SurfaceProperty>>& get_properties() { cached_data_are_uptodate = false; // arrays and other data can be modified through getters return properties; } // --- methods --- }; // GenSurfaceClass class SurfaceClass; py::class_<SurfaceClass> define_pybinding_SurfaceClass(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_SURFACE_CLASS_H
Unknown
3D
mcellteam/mcell
libmcell/generated/gen_introspection.h
.h
2,503
62
/****************************************************************************** * * Copyright (C) 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 API_GEN_INTROSPECTION_H #define API_GEN_INTROSPECTION_H #include "api/api_common.h" namespace MCell { namespace API { class Introspection; class Color; class Complex; class GeometryObject; class Molecule; class Wall; class PythonExportContext; class GenIntrospection { public: GenIntrospection() { } GenIntrospection(DefaultCtorArgType) { } virtual ~GenIntrospection() {} std::shared_ptr<Introspection> copy_introspection() const; std::shared_ptr<Introspection> deepcopy_introspection(py::dict = py::dict()) const; virtual bool __eq__(const Introspection& other) const; virtual bool eq_nonarray_attributes(const Introspection& other, const bool ignore_name = false) const; bool operator == (const Introspection& other) const { return __eq__(other);} bool operator != (const Introspection& other) const { return !__eq__(other);} std::string to_str(const bool all_details=false, const std::string ind="") const ; // --- attributes --- // --- methods --- virtual std::vector<int> get_molecule_ids(std::shared_ptr<Complex> pattern = nullptr) = 0; virtual std::shared_ptr<Molecule> get_molecule(const int id) = 0; virtual std::string get_species_name(const int species_id) = 0; virtual std::vector<double> get_vertex(std::shared_ptr<GeometryObject> object, const int vertex_index) = 0; virtual std::shared_ptr<Wall> get_wall(std::shared_ptr<GeometryObject> object, const int wall_index) = 0; virtual std::vector<double> get_vertex_unit_normal(std::shared_ptr<GeometryObject> object, const int vertex_index) = 0; virtual std::vector<double> get_wall_unit_normal(std::shared_ptr<GeometryObject> object, const int wall_index) = 0; virtual std::shared_ptr<Color> get_wall_color(std::shared_ptr<GeometryObject> object, const int wall_index) = 0; virtual void set_wall_color(std::shared_ptr<GeometryObject> object, const int wall_index, std::shared_ptr<Color> color) = 0; }; // GenIntrospection class Introspection; py::class_<Introspection> define_pybinding_Introspection(py::module& m); } // namespace API } // namespace MCell #endif // API_GEN_INTROSPECTION_H
Unknown
3D
mcellteam/mcell
libmcell/definition/gen.py
.py
82,735
2,270
#!/usr/bin/env python3 """ 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. """ # TODO: change 'items' to 'attributes'? # TODO: cleanup const/nonconst handling # TODO: unify superclass vs superclasses - # w superclasses, the objects are inherited manually now and it should be made automatic # or maybe just rename it.. # TODO: print unset constants as UNSET, not diffusion_constant_2d=3.40282e+38 import sys import os import yaml import re from datetime import datetime from copy import copy from pyexpat import model VERBOSE = False # may be overridden by argument -v from constants import * import doc # --- some global data --- g_enums = set() # ------------------------ def rename_cpp_reserved_id(name): if (name == 'union'): return 'union_' else: return name def get_underscored(class_name): return re.sub(r'(?<!^)(?=[A-Z])', '_', class_name).lower() def get_gen_header_guard_name(class_name): return GEN_GUARD_PREFIX + get_underscored(class_name).upper() + GUARD_SUFFIX def get_api_header_guard_name(class_name): return API_GUARD_PREFIX + get_underscored(class_name).upper() + GUARD_SUFFIX def get_gen_class_file_name(class_name, extension): return GEN_PREFIX + get_underscored(class_name) + '.' + extension def get_gen_class_file_name_w_dir(class_name, extension): # using '/' intentionally to generate the same output on Windows and Linux/Mac return TARGET_DIRECTORY + '/' + get_gen_class_file_name(class_name, extension) def get_api_class_file_name(class_name, extension): return get_underscored(class_name) + '.' + extension def get_api_class_file_name_w_dir(class_name, extension): if class_name == "Config": # config.h is be called api_config.h due to include collisions with MSVC class_name = 'ApiConfig' return API_DIRECTORY + '/' + get_api_class_file_name(class_name, extension) def get_api_class_file_name_w_work_dir(class_name, extension): return WORK_DIRECTORY + '/' + get_api_class_file_name(class_name, extension) def get_as_shared_ptr(class_name): return SHARED_PTR + '<' + class_name + '>' def get_copy_function_name(class_name): return COPY_NAME + '_' + get_underscored(class_name) def get_deepcopy_function_name(class_name): return DEEPCOPY_NAME + '_' + get_underscored(class_name) def is_yaml_list_type(t): return t.startswith(YAML_TYPE_LIST) def is_yaml_dict_type(t): return t.startswith(YAML_TYPE_DICT) def is_yaml_function_type(t): return t.startswith(YAML_TYPE_FUNCTION) # rename inner to underlying? def get_inner_list_type(t): if is_yaml_list_type(t): return t[len(YAML_TYPE_LIST)+1:-1] else: return t def get_inner_dict_key_type(t): if is_yaml_dict_type(t): return t.replace('[', ',').replace(']', ',').split(',')[1].strip() else: return t def get_inner_dict_value_type(t): if is_yaml_dict_type(t): return t.replace('[', ',').replace(']', ',').split(',')[2].strip() else: return t def get_inner_function_type(t): # callbacks pass back only one shared_ptr argument if is_yaml_function_type(t): return t.split('<')[2].split('>')[0].strip() else: return t def get_first_inner_type(t): if is_yaml_list_type(t): return get_inner_list_type(t) elif is_yaml_dict_type(t): return get_inner_dict_key_type(t) elif is_yaml_function_type(t): return get_inner_function_type(t) else: return t # returns true also for enums def is_base_yaml_type(t): return \ t == YAML_TYPE_FLOAT or t == YAML_TYPE_STR or t == YAML_TYPE_INT or t == YAML_TYPE_UINT64 or t == YAML_TYPE_UINT32 or \ t == YAML_TYPE_BOOL or t == YAML_TYPE_VEC2 or t == YAML_TYPE_VEC3 or t == YAML_TYPE_IVEC3 or \ t == YAML_TYPE_PY_OBJECT or \ (is_yaml_function_type(t) and is_base_yaml_type(get_inner_function_type(t))) or \ (is_yaml_list_type(t) and is_base_yaml_type(get_inner_list_type(t))) or \ (is_yaml_dict_type(t) and is_base_yaml_type(get_inner_dict_key_type(t)) and is_base_yaml_type(get_inner_dict_value_type(t))) def is_yaml_ptr_type(t): if t == YAML_TYPE_PY_OBJECT: return False else: return t[-1] == '*' def yaml_type_to_cpp_type(t, w_namespace=False): assert len(t) >= 1 if t == YAML_TYPE_FLOAT: return CPP_TYPE_DOUBLE elif t == YAML_TYPE_STR: return CPP_TYPE_STR elif t == YAML_TYPE_INT: return CPP_TYPE_INT elif t == YAML_TYPE_UINT64: return CPP_TYPE_UINT64 elif t == YAML_TYPE_UINT32: return CPP_TYPE_UINT32 elif t == YAML_TYPE_BOOL: return CPP_TYPE_BOOL elif t == YAML_TYPE_VEC2: ns = '' if not w_namespace else 'MCell::' return ns + CPP_TYPE_VEC2 elif t == YAML_TYPE_VEC3: ns = '' if not w_namespace else 'MCell::' return ns + CPP_TYPE_VEC3 elif t == YAML_TYPE_IVEC3: ns = '' if not w_namespace else 'MCell::' return ns + CPP_TYPE_IVEC3 elif is_yaml_list_type(t): assert len(t) > 7 inner_type = yaml_type_to_cpp_type(get_inner_list_type(t), w_namespace) return CPP_VECTOR_TYPE + '<' + inner_type + '>' elif is_yaml_dict_type(t): key_type = yaml_type_to_cpp_type(get_inner_dict_key_type(t), w_namespace) value_type = yaml_type_to_cpp_type(get_inner_dict_value_type(t), w_namespace) return CPP_MAP_TYPE + '<' + key_type + ', ' + value_type + '>' else: ns = '' if not w_namespace else 'MCell::API::' if is_yaml_ptr_type(t): return SHARED_PTR + '<' + ns + t[0:-1] + '>' else: return ns + t # standard ttype def get_cpp_bool_string(val): if val == 'True': return 'true' elif val == 'False': return 'false' else: assert false def yaml_type_to_pybind_type(t): assert len(t) >= 1 if t == YAML_TYPE_FLOAT: return 'float_' elif t == YAML_TYPE_STR: return YAML_TYPE_STR elif t == YAML_TYPE_BOOL: return CPP_TYPE_BOOL elif t == YAML_TYPE_INT: return CPP_TYPE_INT + '_' elif t == YAML_TYPE_UINT64: return CPP_TYPE_INT + '_' elif t == YAML_TYPE_UINT32: return CPP_TYPE_INT + '_' elif t == YAML_TYPE_SPECIES: return PYBIND_TYPE_OBJECT else: assert False, "Unsupported constant type " + t def yaml_type_to_py_type(t): assert len(t) >= 1 if t == YAML_TYPE_UINT64 or t == YAML_TYPE_UINT32: return YAML_TYPE_INT # not sure what should be the name elif is_yaml_function_type(t): return "Callable, # " + t elif t == YAML_TYPE_PY_OBJECT: return "Any, # " + t elif is_yaml_list_type(t) and get_inner_list_type(t) == YAML_TYPE_UINT64: return t.replace(YAML_TYPE_UINT64, YAML_TYPE_INT) elif is_yaml_list_type(t) and get_inner_list_type(t) == YAML_TYPE_UINT32: return t.replace(YAML_TYPE_UINT32, YAML_TYPE_INT) else: return t.replace('*', '') def is_cpp_ptr_type(cpp_type): return cpp_type.startswith(SHARED_PTR) def is_cpp_ref_type(cpp_type): not_reference = \ cpp_type in CPP_NONREFERENCE_TYPES or \ is_cpp_ptr_type(cpp_type) or \ cpp_type.startswith(CPP_VECTOR_TYPE) or \ cpp_type in g_enums or \ is_yaml_function_type(cpp_type) or \ cpp_type == YAML_TYPE_PY_OBJECT return not not_reference def is_cpp_vector_type(cpp_type): return'std::vector' in cpp_type def get_type_as_ref_param(attr): assert KEY_TYPE in attr yaml_type = attr[KEY_TYPE] cpp_type = yaml_type_to_cpp_type(yaml_type) res = cpp_type if is_cpp_ref_type(cpp_type): res += '&' return res def get_default_or_unset_value(attr): assert KEY_TYPE in attr t = attr[KEY_TYPE] if KEY_DEFAULT in attr: default_value = attr[KEY_DEFAULT] if default_value != UNSET_VALUE and default_value != EMPTY_ARRAY: res = str(default_value) # might need to convert enum.value into enum::value if not is_base_yaml_type(t): res = res.replace('.', '::') elif t == YAML_TYPE_BOOL: res = get_cpp_bool_string(res) elif t == YAML_TYPE_STR: # default strings must be quoted (not the 'unset' one because the UNSET_STR is a constant) res = '"' + res + '"' return res if t == YAML_TYPE_FLOAT: return UNSET_VALUE_FLOAT elif t == YAML_TYPE_STR: return UNSET_VALUE_STR elif t == YAML_TYPE_INT: return UNSET_VALUE_INT elif t == YAML_TYPE_UINT64: return UNSET_VALUE_UINT64 elif t == YAML_TYPE_UINT32: return UNSET_VALUE_UINT32 elif t == YAML_TYPE_BOOL: assert False, "There is no unset value for bool - for " + attr[KEY_NAME] return "error" elif t == YAML_TYPE_VEC2: return UNSET_VALUE_VEC2 elif t == YAML_TYPE_VEC3: return UNSET_VALUE_VEC3 elif t == YAML_TYPE_IVEC3: return UNSET_VALUE_IVEC3 elif t == YAML_TYPE_ORIENTATION: return UNSET_VALUE_ORIENTATION elif is_yaml_list_type(t): return yaml_type_to_cpp_type(t) + '()' elif is_yaml_dict_type(t): return yaml_type_to_cpp_type(t) + '()' else: return UNSET_VALUE_PTR def get_default_or_unset_value_py(attr): assert KEY_TYPE in attr t = attr[KEY_TYPE] if KEY_DEFAULT in attr: default_value = attr[KEY_DEFAULT] if default_value == "": return "''" elif default_value != UNSET_VALUE and default_value != EMPTY_ARRAY: return str(default_value) # might need to convert enum.value into enum::value #if not is_base_yaml_type(t): # res = res.replace('.', '::') #elif t == YAML_TYPE_BOOL: # res = get_cpp_bool_string(res) return PY_NONE def has_item_w_name(items, item_name): for item in items: if item_name == item[KEY_NAME]: return True return False def is_container_class(name): return \ name == CLASS_NAME_MODEL or \ name == CLASS_NAME_SUBSYSTEM or \ name == CLASS_NAME_INSTANTIATION or \ name == CLASS_NAME_OBSERVABLES def is_container_class_no_model(name): return is_container_class(name) and not name == CLASS_NAME_MODEL def write_generated_notice(f): now = datetime.now() # date printing is disabled during the development phase to minimize changes in files #date_time = now.strftime("%m/%d/%Y, %H:%M") #f.write('// This file was generated automatically on ' + date_time + ' from ' + '\'' + input_file_name + '\'\n\n') def write_ctor_decl(f, class_def, class_name, append_backslash, indent_and_fix_rst_chars, only_inherited, with_args=True): items = class_def[KEY_ITEMS] if KEY_ITEMS in class_def else [] backshlash = '\\' if append_backslash else '' f.write(indent_and_fix_rst_chars + class_name + '( ' + backshlash + '\n') inherited_items = [ attr for attr in items if is_inherited(attr) ] if only_inherited: # override also the original items list items = inherited_items # ctor parameters if with_args: num_items = len(items) for i in range(num_items): attr = items[i] if not only_inherited and attr_not_in_ctor(attr): continue assert KEY_NAME in attr name = attr[KEY_NAME] const_spec = 'const ' if not is_yaml_ptr_type(attr[KEY_TYPE]) else '' f.write(indent_and_fix_rst_chars + ' ' + const_spec + get_type_as_ref_param(attr) + ' ' + name + '_') if KEY_DEFAULT in attr: f.write(' = ' + get_default_or_unset_value(attr)) if i != num_items - 1: f.write(',') f.write(' ' + backshlash + '\n') f.write(indent_and_fix_rst_chars + ') ') if has_superclass_other_than_base(class_def): # call superclass ctor # only one, therefore all inherited attributes are its arguments if only_inherited: # we are generating ctor for the superclass of the Gen class, e.g. for GenSpecies # and we need to initialize Complex superclass_name = class_def[KEY_SUPERCLASS] else: # we are generating ctor for the superclass, e.g. for Species and we need to initialize # GenSpecies superclass_name = GEN_CLASS_PREFIX + class_name f.write(' : ' + superclass_name + '(') num_inherited_items = len(inherited_items) for i in range(num_inherited_items): f.write(inherited_items[i][KEY_NAME] + '_') if i != num_inherited_items - 1: f.write(',') f.write(') ') def needs_default_ctor(class_def, only_inherited): if KEY_ITEMS not in class_def: return False items = class_def[KEY_ITEMS] if only_inherited: items = [ attr for attr in items if is_inherited(attr) ] if items: all_attrs_initialized = True for item in items: if not KEY_DEFAULT in item: all_attrs_initialized = False return not all_attrs_initialized else: return False def write_ctor_define(f, class_def, class_name): with_args = True if KEY_SUPERCLASS in class_def and class_def[KEY_SUPERCLASS] == BASE_INTROSPECTION_CLASS: with_args = False suffix = CTOR_SUFFIX if with_args else CTOR_NOARGS_SUFFIX f.write('#define ' + get_underscored(class_name).upper() + suffix + '() \\\n') write_ctor_decl(f, class_def, class_name, append_backslash=True, indent_and_fix_rst_chars=' ', only_inherited=False, with_args=with_args) f.write('{ \\\n') # initialization code if not is_container_class_no_model(class_name): f.write(' ' + CLASS_NAME_ATTR + ' = "' + class_name + '"; \\\n') items = class_def[KEY_ITEMS] if KEY_ITEMS in class_def else [] num_items = len(items) for i in range(num_items): if attr_not_in_ctor(items[i]): continue assert KEY_NAME in items[i] attr_name = items[i][KEY_NAME] if with_args: f.write(' ' + attr_name + ' = ' + attr_name + '_; \\\n') else: f.write(' ' + attr_name + ' = ' + get_default_or_unset_value(items[i]) + '; \\\n') if not is_container_class_no_model(class_name): f.write(' ' + CTOR_POSTPROCESS + '(); \\\n') f.write(' ' + CHECK_SEMANTICS + '(); \\\n') f.write(' } \\\n') # also generate empty ctor if needed f.write(' ' + class_name + '(' + DEFAULT_CTOR_ARG_TYPE + ')') if has_single_superclass(class_def): f.write(' : \\\n' ' ' + GEN_CLASS_PREFIX + class_name + '(' + DEFAULT_CTOR_ARG_TYPE + '()) ') f.write('{ \\\n') if has_single_superclass(class_def): f.write(' ' + SET_ALL_DEFAULT_OR_UNSET_DECL + '; \\\n') f.write(' ' + SET_ALL_CUSTOM_TO_DEFAULT_DECL + '; \\\n') f.write(' }\n\n'); def write_ctor_for_superclass(f, class_def, class_name): write_ctor_decl(f, class_def, GEN_CLASS_PREFIX + class_name, append_backslash=False, indent_and_fix_rst_chars=' ', only_inherited=True) f.write(' {\n') f.write(' }\n') def write_attr_with_get_set(f, class_def, attr): assert KEY_NAME in attr, KEY_NAME + " is not set in " + str(attr) assert KEY_TYPE in attr, KEY_TYPE + " is not set in " + str(attr) name = attr[KEY_NAME] # skip attribute 'name' if name == ATTR_NAME_NAME: return False yaml_type = attr[KEY_TYPE] cpp_type = yaml_type_to_cpp_type(yaml_type) #decl_const = 'const ' if is_cpp_ptr_type(cpp_type) else '' decl_type = cpp_type # decl f.write(' ' + decl_type + ' ' + name + ';\n') # setter arg_type_const = 'const ' if not is_cpp_ptr_type(cpp_type) else '' f.write(' virtual void set_' + name + '(' + arg_type_const + get_type_as_ref_param(attr) + ' new_' + name + '_) {\n') # TODO: allow some values to be set even after initialization if has_single_superclass(class_def): f.write(' if (initialized) {\n') f.write(' throw RuntimeError("Value \'' + name + '\' of object with name " + name + " (class " + class_name + ") "\n') f.write(' "cannot be set after model was initialized.");\n') f.write(' }\n') if has_single_superclass(class_def): f.write(' ' + CACHED_DATA_ARE_UPTODATE_ATTR + ' = false;\n'); f.write(' ' + name + ' = new_' + name + '_;\n') f.write(' }\n') # getter ret_type_ref = '' ret_type_const = 'const ' if is_cpp_ref_type(cpp_type) else '' method_const = 'const ' # vectors are always returned as a non-const reference if is_cpp_vector_type(cpp_type): ret_type_ref = '&' ret_type_const = '' method_const = '' ret_type = get_type_as_ref_param(attr) f.write(' virtual ' + ret_type_const + ret_type + ret_type_ref + ' get_' + name + '() ' + method_const +'{\n') """ # original approach to protect already initialized classes but this behavior woudl probably be more confusing if has_single_superclass(class_def) and is_cpp_vector_type(cpp_type): f.write(' if (initialized) {\n') f.write(' // any changes after initialization are ignored\n') f.write(' static ' + ret_type + ' copy = ' + name + ';\n') f.write(' return copy;\n') f.write(' }\n') """ if has_single_superclass(class_def): f.write(' ' + CACHED_DATA_ARE_UPTODATE_ATTR + ' = false; // arrays and other data can be modified through getters\n'); f.write(' return ' + name + ';\n') f.write(' }\n') return True def write_method_signature(f, method): if KEY_RETURN_TYPE in method: f.write(yaml_type_to_cpp_type(method[KEY_RETURN_TYPE]) + ' ') else: f.write('void ') assert KEY_NAME in method f.write(rename_cpp_reserved_id(method[KEY_NAME]) + '(') if KEY_PARAMS in method: params = method[KEY_PARAMS] params_cnt = len(params) for i in range(params_cnt): p = params[i] assert KEY_NAME in p assert KEY_TYPE in p t = get_type_as_ref_param(p) const_spec = 'const ' if not is_yaml_ptr_type(p[KEY_TYPE]) and p[KEY_TYPE] != YAML_TYPE_PY_OBJECT else '' f.write(const_spec + t + ' ' + p[KEY_NAME]) if KEY_DEFAULT in p: f.write(' = ' + get_default_or_unset_value(p)) if i != params_cnt - 1: f.write(', ') f.write(')') if KEY_IS_CONST in method and method[KEY_IS_CONST]: f.write(' const') def write_method_declaration(f, method): f.write(' virtual ') write_method_signature(f, method) f.write(' = 0;\n') def is_inherited(attr_or_method_def): if KEY_INHERITED in attr_or_method_def: return attr_or_method_def[KEY_INHERITED] else: return False def attr_not_in_ctor(attr_or_method_def): if KEY_NOT_AS_CTOR_ARG in attr_or_method_def: return attr_or_method_def[KEY_NOT_AS_CTOR_ARG] else: return False def has_single_superclass(class_def): if KEY_SUPERCLASS in class_def: return True else: return False def has_superclass_other_than_base(class_def): # TODO: also deal with superclasses? if has_single_superclass(class_def): return \ class_def[KEY_SUPERCLASS] != BASE_DATA_CLASS and \ class_def[KEY_SUPERCLASS] != BASE_INTROSPECTION_CLASS else: return False def write_gen_class(f, class_def, class_name, decls): gen_class_name = GEN_CLASS_PREFIX + class_name f.write('class ' + gen_class_name) if has_single_superclass(class_def): f.write(': public ' + class_def[KEY_SUPERCLASS]) elif KEY_SUPERCLASSES in class_def: scs = class_def[KEY_SUPERCLASSES] assert scs f.write(': ') for i in range(len(scs)): f.write('public ' + scs[i]) if i + 1 != len(scs): f.write(', ') elif is_container_class_no_model(class_name): f.write(': public ' + BASE_EXPORT_CLASS) f.write( ' {\n') f.write('public:\n') initialization_ctor_generated = False if has_superclass_other_than_base(class_def): write_ctor_for_superclass(f, class_def, class_name) initialization_ctor_generated = True # we need a 'default' ctor (with custom arg type) all the time, # however, there may not be a default ctor with no argument so we must define it # as well if needs_default_ctor(class_def, only_inherited=True) or not initialization_ctor_generated: f.write(' ' + GEN_CLASS_PREFIX + class_name + '() ') if has_superclass_other_than_base(class_def): superclass_name = class_def[KEY_SUPERCLASS] f.write(': ' + superclass_name + '(' + DEFAULT_CTOR_ARG_TYPE + '()) {\n') else: f.write('{\n') f.write(' }\n') f.write(' ' + GEN_CLASS_PREFIX + class_name + '(' + DEFAULT_CTOR_ARG_TYPE + ') {\n') f.write(' }\n') if not has_single_superclass(class_def): # generate virtual destructor f.write(' virtual ~' + gen_class_name + '() {}\n') if has_single_superclass(class_def): f.write(' ' + RET_CTOR_POSTPROCESS + ' ' + CTOR_POSTPROCESS + '() ' + KEYWORD_OVERRIDE + ' {}\n') f.write(' ' + RET_TYPE_CHECK_SEMANTICS + ' ' + DECL_CHECK_SEMANTICS + ' ' + KEYWORD_OVERRIDE + ';\n') f.write(' void ' + DECL_SET_INITIALIZED + ' ' + KEYWORD_OVERRIDE + ';\n') f.write(' ' + RET_TYPE_SET_ALL_DEFAULT_OR_UNSET + ' ' + SET_ALL_DEFAULT_OR_UNSET_DECL + ' ' + KEYWORD_OVERRIDE + ';\n\n') f.write(' ' + get_as_shared_ptr(class_name) + ' ' + get_copy_function_name(class_name) + '() const;\n') f.write(' ' + get_as_shared_ptr(class_name) + ' ' + get_deepcopy_function_name(class_name) + '(py::dict = py::dict()) const;\n') f.write(' virtual bool __eq__(const ' + class_name + '& other) const;\n') f.write(' virtual bool eq_nonarray_attributes(const ' + class_name + '& other, const bool ignore_name = false) const;\n') f.write(' bool operator == (const ' + class_name + '& other) const { return __eq__(other);}\n') f.write(' bool operator != (const ' + class_name + '& other) const { return !__eq__(other);}\n') override = KEYWORD_OVERRIDE if has_single_superclass(class_def) else '' f.write(' ' + RET_TYPE_TO_STR + ' ' + DECL_TO_STR_W_DEFAULT + ' ' + override + ';\n\n') if decls: f.write(decls + '\n\n') f.write(' // --- attributes ---\n') items = class_def[KEY_ITEMS] for attr in items: if not is_inherited(attr): written = write_attr_with_get_set(f, class_def, attr) if written : f.write('\n') f.write(' // --- methods ---\n') methods = class_def[KEY_METHODS] for m in methods: if not is_inherited(m): write_method_declaration(f, m) f.write('}; // ' + GEN_CLASS_PREFIX + class_name + '\n\n') def write_define_binding_decl(f, class_name, ret_type_void = False): if ret_type_void: f.write('void ') else: f.write('py::class_<' + class_name + '> ') f.write('define_pybinding_' + class_name + '(py::module& m)') def remove_ptr_mark(t): assert len(t) > 1 if t[-1] == '*': return t[0:-1] else: return t def get_all_used_nonbase_types(class_def): types = set() for items in class_def[KEY_ITEMS]: assert KEY_TYPE in items t = items[KEY_TYPE] if not is_base_yaml_type(t): types.add( t ) for method in class_def[KEY_METHODS]: if KEY_RETURN_TYPE in method: t = method[KEY_RETURN_TYPE] if not is_base_yaml_type(t): types.add( t ) if KEY_PARAMS in method: for param in method[KEY_PARAMS]: assert KEY_TYPE in param t = param[KEY_TYPE] if not is_base_yaml_type(t): types.add( t ) return types def get_all_used_compound_types_no_decorations(class_def): types = get_all_used_nonbase_types(class_def) cleaned_up_types = set() for t in types: # mus be set otherwise we get duplicates cleaned_up_types.add(remove_ptr_mark( get_first_inner_type( remove_ptr_mark(t) ) )) sorted_types_no_enums = [ t for t in cleaned_up_types if t not in g_enums ] sorted_types_no_enums.sort() return sorted_types_no_enums def write_required_includes(f, class_def): types = get_all_used_nonbase_types(class_def) inner_types = set() for t in types: # must be set otherwise we get duplicates inner_types.add( get_first_inner_type(t) ) types_no_ptrs = [ t for t in inner_types if not is_yaml_ptr_type(t) ] sorted_types_no_enums = [ t for t in types_no_ptrs if t not in g_enums ] sorted_types_no_enums.sort() for t in sorted_types_no_enums: f.write('#include "' + get_api_class_file_name_w_dir(t, EXT_H) + '"\n') if KEY_SUPERCLASSES in class_def: scs = class_def[KEY_SUPERCLASSES] for sc in scs: f.write('#include "' + get_api_class_file_name_w_dir(sc, EXT_H) + '"\n') def write_forward_decls(f, class_def, class_name): # first we need to collect all types that we will need types = get_all_used_compound_types_no_decorations(class_def) if class_name not in types and class_def[KEY_TYPE] != VALUE_SUBMODULE: f.write('class ' + class_name + ';\n') for t in types: f.write('class ' + t + ';\n') f.write('class PythonExportContext;\n') f.write('\n') def generate_class_header(class_name, class_def, decls): with open(get_gen_class_file_name_w_dir(class_name, EXT_H), 'w') as f: f.write(COPYRIGHT) write_generated_notice(f) def_type = class_def[KEY_TYPE] guard = get_gen_header_guard_name(class_name); f.write('#ifndef ' + guard + '\n') f.write('#define ' + guard + '\n\n') f.write(INCLUDE_API_COMMON_H + '\n') if def_type == VALUE_CLASS: if KEY_SUPERCLASS in class_def: if class_def[KEY_SUPERCLASS] == BASE_DATA_CLASS: f.write(INCLUDE_API_BASE_DATA_CLASS_H + '\n') elif class_def[KEY_SUPERCLASS] == BASE_INTROSPECTION_CLASS: f.write(INCLUDE_API_BASE_INTROSPECTION_CLASS_H + '\n') elif is_container_class_no_model(class_name): f.write(INCLUDE_API_BASE_EXPORT_CLASS_H + '\n') if has_superclass_other_than_base(class_def): f.write('#include "' + get_api_class_file_name_w_dir(class_def[KEY_SUPERCLASS], EXT_H) + '"\n\n') write_required_includes(f, class_def) f.write('\n' + NAMESPACES_BEGIN + '\n\n') write_forward_decls(f, class_def, class_name) if has_single_superclass(class_def) or is_container_class_no_model(class_name): write_ctor_define(f, class_def, class_name) if def_type == VALUE_CLASS: write_gen_class(f, class_def, class_name, decls) f.write('class ' + class_name + ';\n') elif def_type == VALUE_SUBMODULE: assert decls == '' f.write('namespace ' + class_name + ' {\n\n') # submodules have only functions methods = class_def[KEY_METHODS] for m in methods: write_method_signature(f, m) f.write(";\n") f.write('\n} // namespace ' + class_name + '\n\n') write_define_binding_decl(f, class_name, def_type == VALUE_SUBMODULE) f.write(';\n') f.write(NAMESPACES_END + '\n\n') f.write('#endif // ' + guard + '\n') def generate_class_template(class_name, class_def): with open(get_api_class_file_name_w_work_dir(class_name, EXT_H), 'w') as f: f.write(COPYRIGHT) write_generated_notice(f) guard = get_api_header_guard_name(class_name); f.write('#ifndef ' + guard + '\n') f.write('#define ' + guard + '\n\n') f.write('#include "' + get_gen_class_file_name_w_dir(class_name, EXT_H) + '"\n') f.write(INCLUDE_API_COMMON_H + '\n') if has_superclass_other_than_base(class_def): f.write('#include "' + get_api_class_file_name_w_dir(class_def[KEY_SUPERCLASS], EXT_H) + '"\n\n') f.write('\n' + NAMESPACES_BEGIN + '\n\n') f.write('class ' + class_name + ': public ' + GEN_CLASS_PREFIX + class_name + ' {\n') f.write('public:\n') f.write(' ' + get_underscored(class_name).upper() + CTOR_SUFFIX + '()\n\n') if has_single_superclass(class_def): f.write(' // defined in generated file\n') f.write(' ' + RET_TYPE_EXPORT_TO_PYTHON + ' ' + DECL_EXPORT_TO_PYTHON + ' ' + KEYWORD_OVERRIDE + ';\n\n') f.write('};\n\n') f.write(NAMESPACES_END + '\n\n') f.write('#endif // ' + guard + '\n') def write_is_set_check(f, name, is_list): f.write(' if (!is_set(' + name + ')) {\n') f.write(' throw ValueError("Parameter \'' + name + '\' must be set') if is_list: f.write(' and the value must not be an empty list') f.write('.");\n') f.write(' }\n') def write_check_semantics_implemetation(f, class_name, items): f.write(RET_TYPE_CHECK_SEMANTICS + ' ' + GEN_CLASS_PREFIX + class_name + '::' + DECL_CHECK_SEMANTICS + ' {\n') for attr in items: if KEY_DEFAULT not in attr: write_is_set_check(f, attr[KEY_NAME], is_yaml_list_type(attr[KEY_TYPE])) f.write('}\n\n') def write_to_str_implementation(f, class_name, items, based_on_base_superclass): f.write(RET_TYPE_TO_STR + ' ' + GEN_CLASS_PREFIX + class_name + '::' + DECL_TO_STR + ' {\n') f.write(' std::stringstream ss;\n') if based_on_base_superclass: f.write(' ss << get_object_name()') else: f.write(' ss << "' + class_name + '"') if items: f.write(' << ": " <<\n') last_print_nl = False num_attrs = len(items) for i in range(num_attrs): name = items[i][KEY_NAME] t = items[i][KEY_TYPE] print_nl = False starting_nl = '"' if last_print_nl else '"\\n" << ind + " " << "' if is_yaml_list_type(t): underlying_type = get_first_inner_type(t) if is_yaml_ptr_type(underlying_type): f.write(' ' + starting_nl + name + '=" << ' + VEC_PTR_TO_STR + '(' + name + ', all_details, ind + " ")') print_nl = True else: f.write(' "' + name + '=" << ') f.write(VEC_NONPTR_TO_STR + '(' + name + ', all_details, ind + " ")') elif not is_base_yaml_type(t) and t not in g_enums: if is_yaml_ptr_type(t): f.write(' ' + starting_nl + name + '=" << "(" << ((' + name + ' != nullptr) ? ' + name + '->to_str(all_details, ind + " ") : "null" ) << ")"') else: f.write(' ' + starting_nl + name + '=" << "(" << ' + name + '.to_str(all_details, ind + " ") << ")"') print_nl = True else: f.write(' "' + name + '=" << ') f.write(name) if i != num_attrs - 1: f.write(' << ", " <<') if print_nl: f.write(' "\\n" << ind + " " <<\n') else: f.write('\n') last_print_nl = print_nl f.write(';\n') f.write(' return ss.str();\n') f.write('}\n\n') def write_vec_export(f, return_only_name, gen_class_name, item): item_name = item[KEY_NAME]; PARENT_NAME = 'parent_name' name_w_args = \ EXPORT_VEC_PREFIX + item_name + '(' + EXPORT_TO_PYTHON_ARGS + ', const std::string& ' + PARENT_NAME + ')' decl = ' virtual ' + RET_TYPE_EXPORT_TO_PYTHON + ' ' + name_w_args + ';\n' f.write(RET_TYPE_EXPORT_TO_PYTHON + " " + gen_class_name + "::" + name_w_args + " {\n") if return_only_name: f.write(' // prints vector into \'out\' and returns name of the generated list\n') else: f.write(' // does not print the array itself to \'out\' and returns the whole list\n') f.write(' std::stringstream ss;\n') out = ' ss << ' if return_only_name: f.write(' std::string ' + EXPORTED_NAME + ';\n' + ' if (' + PARENT_NAME + ' != ""){\n' + ' ' + EXPORTED_NAME + ' = ' + PARENT_NAME + '+ "_' + item_name + '";\n' + ' }\n' + ' else {\n' + ' ' + EXPORTED_NAME + ' = "' + item_name + '";\n' + ' }\n\n') f.write(out + EXPORTED_NAME + ' << " = [\\n";\n') spacing = ' ' else: f.write(out + '"[";\n') spacing = ' ' type = item[KEY_TYPE] assert is_yaml_list_type(type) inner_type = get_inner_list_type(type) f.write( ' for (size_t i = 0; i < ' + item_name + '.size(); i++) {\n' + ' const auto& item = ' + item_name + '[i];\n' + ' if (i == 0) {\n' + ' ' + out + '"' + spacing + '";\n' + ' }\n' + ' else if (i % 16 == 0) {\n' + ' ' + out + '"\\n ";\n' + ' }\n' ) if is_yaml_list_type(inner_type): inner2_type = get_inner_list_type(inner_type) # special case for 2D arrays, they hold int or float f.write( ' ' + out + '"[";\n' + ' for (const auto& value: item) {\n' ) if inner2_type == YAML_TYPE_FLOAT: f.write(' ' + out + F_TO_STR + '(value) << ", ";\n') else: f.write(' ' + out + 'value << ", ";\n') f.write( ' }\n' + ' ' + out + '"], ";\n' ) elif not is_base_yaml_type(inner_type) and inner_type not in g_enums: # array of API objects f.write( ' if (!item->skip_python_export()) {\n' + ' std::string name = item->export_to_python(out, ctx);\n' + ' ' + out + 'name << ", ";\n' + ' }\n' ) elif inner_type == YAML_TYPE_FLOAT: f.write(' ' + out + F_TO_STR + '(item) << ", ";\n') elif inner_type == YAML_TYPE_STR: f.write(' ' + out + '"\'" << item << "\', ";\n') else: # array of simple type f.write(' ' + out + 'item << ", ";\n') f.write(' }\n') if return_only_name: f.write(out + '"\\n]\\n\\n";\n') f.write(' out << ss.str();\n') f.write(' return ' + EXPORTED_NAME + ';\n') else: f.write(out + '"]";\n') f.write(' return ss.str();\n') f.write('}\n\n') return decl def write_export_to_python_implementation(f, class_name, class_def): items = class_def[KEY_ITEMS] # declaration if KEY_SUPERCLASS in class_def and class_def[KEY_SUPERCLASS] == BASE_DATA_CLASS: override = ' ' + KEYWORD_OVERRIDE virtual = '' else: override = '' virtual = KEYWORD_VIRTUAL + ' ' gen_class_name = GEN_CLASS_PREFIX + class_name decl_main = ' ' + virtual + RET_TYPE_EXPORT_TO_PYTHON + ' ' + DECL_EXPORT_TO_PYTHON + override + ';\n' f.write(RET_TYPE_EXPORT_TO_PYTHON + " " + gen_class_name + "::" + DECL_EXPORT_TO_PYTHON + " {\n") export_vecs_to_define = [] if class_name == CLASS_NAME_MODEL: f.write('# if 0 // not to be used\n') name_underscored = get_underscored(class_name) if not is_container_class(class_name): f.write( ' if (!export_even_if_already_exported() && ' + CTX + '.already_exported(this)) {\n' + ' return ' + CTX + '.get_exported_name(this);\n' + ' }\n' ) # name generation f.write(' std::string ' + EXPORTED_NAME + ' = ') if not has_item_w_name(items, ATTR_NAME_NAME): f.write('"' + name_underscored + '_" + ' + 'std::to_string(' + CTX + '.postinc_counter("' + name_underscored + '"));\n') else: f.write('std::string("' + name_underscored + '") + "_" + ' + '(is_set(name) ? ' + 'fix_id(name) : ' + 'std::to_string(' + CTX + '.postinc_counter("' + name_underscored + '")));\n') f.write( ' if (!export_even_if_already_exported()) {\n' + ' ' + CTX + '.add_exported(this, ' + EXPORTED_NAME + ');\n' ' }\n\n' ) else: f.write(' std::string ' + EXPORTED_NAME + ' = "' + name_underscored + '";\n\n') STR_EXPORT = 'str_export' f.write(' bool ' + STR_EXPORT + ' = export_as_string_without_newlines();\n') NL = 'nl'; f.write(' std::string ' + NL + ' = "";\n') IND = 'ind'; f.write(' std::string ' + IND + ' = " ";\n') f.write(' std::stringstream ss;\n') out = ' ss << ' f.write(' if (!' + STR_EXPORT + ') {\n') f.write(' ' + NL + ' = "\\n";\n') f.write(' ' + IND + ' = " ";\n') f.write(' ' + out + EXPORTED_NAME + ' << " = ";\n') f.write(' }\n') f.write(out + '"' + M_DOT + class_name + '(" << ' + NL + ';\n') processed_items = set() # we would like to export inherited fields first sorted_items = [] for item in items: if KEY_INHERITED in item: sorted_items.append(item) for item in items: if KEY_INHERITED not in item: sorted_items.append(item) for item in sorted_items: type = item[KEY_TYPE] name = item[KEY_NAME] if name in processed_items: continue processed_items.add(name) export_condition = '' if is_yaml_list_type(type): export_condition = ' && !skip_vectors_export()' if KEY_DEFAULT in item: if is_yaml_ptr_type(type): f.write(' if (is_set(' + name + ')) {\n') else: f.write(' if (' + name + ' != ' + get_default_or_unset_value(item) + export_condition + ') {\n') f.write(' ') f.write(out + IND + ' << "' + name + ' = " << ') if is_yaml_list_type(type): f.write(EXPORT_VEC_PREFIX + name + '(out, ' + CTX + ', ' + EXPORTED_NAME + ') << "," << ' + NL + ';\n') export_vecs_to_define.append(item) elif is_yaml_ptr_type(type): f.write(name + '->export_to_python(out, ' + CTX + ') << "," << ' + NL + ';\n') elif not is_base_yaml_type(type) and type not in g_enums: f.write(name + '.export_to_python(out, ' + CTX + ') << "," << ' + NL + ';\n') elif type == YAML_TYPE_STR: f.write('"\'" << ' + name + ' << "\'" << "," << ' + NL + ';\n') elif type == YAML_TYPE_VEC3: # also other ivec*/vec2 types should be handled like this but it was not needed so far f.write('"' + M_DOT + CPP_TYPE_VEC3 + '(" << ' + F_TO_STR + '(' + name + '.x) << ", " << ' + F_TO_STR + '(' + name + '.y) << ", " << ' + F_TO_STR + '(' + name + '.z)' + '<< ")," << ' + NL + ';\n') elif type == YAML_TYPE_VEC2: # also other ivec*/vec2 types should be handled like this but it was not needed so far f.write('"' + M_DOT + CPP_TYPE_VEC2 + '(" << ' + F_TO_STR + '(' + name + '.u) << ", " << ' + F_TO_STR + '(' + name + '.v)' + '<< ")," << ' + NL + ';\n') elif type == YAML_TYPE_FLOAT: f.write(F_TO_STR + '(' + name + ') << "," << ' + NL + ';\n') else: # using operators << for enums f.write(name + ' << "," << ' + NL + ';\n') if KEY_DEFAULT in item: f.write(' }\n') f.write(out + '")" << ' + NL + ' << ' + NL + ';\n') f.write(' if (!' + STR_EXPORT + ') {\n') f.write(' out << ss.str();\n') f.write(' return ' + EXPORTED_NAME + ';\n') f.write(' }\n') f.write(' else {\n') f.write(' return ss.str();\n') f.write(' }\n') if class_name == CLASS_NAME_MODEL: f.write('#else // # if 0\n') f.write(' assert(false);\n') f.write(' return "";\n') f.write('#endif\n') f.write('}\n\n') # also define export vec methods decls_export_vec = '' for item in export_vecs_to_define: decls_export_vec += write_vec_export(f, is_container_class(class_name), gen_class_name, item) # return string that contains declaration of export methods, this will be later used in # .h file generation return decl_main + decls_export_vec def write_operator_equal_body(f, class_name, class_def, skip_arrays_and_name=False): items = class_def[KEY_ITEMS] f.write(' return\n') if not items: f.write('true ;\n') num_attrs = len(items) for i in range(num_attrs): name = items[i][KEY_NAME] t = items[i][KEY_TYPE] if is_yaml_ptr_type(t): f.write( ' (\n' ' (is_set(' + name + ')) ?\n' ' (is_set(other.' + name + ') ?\n' ' (' + name + '->__eq__(*other.' + name + ')) : \n' ' false\n' ' ) :\n' ' (is_set(other.' + name + ') ?\n' ' false :\n' ' true\n' ' )\n' ' ) ' ) elif is_yaml_list_type(t): if not skip_arrays_and_name: if is_yaml_ptr_type(get_inner_list_type(t)): f.write(' vec_ptr_eq(' + name + ', other.' + name + ')') else: f.write(' ' + name + ' == other.' + name) else: f.write(' true /*' + name + '*/') else: if skip_arrays_and_name and name == KEY_NAME: f.write(' (ignore_name || ' + name + ' == other.' + name + ')') else: f.write(' ' + name + ' == other.' + name) if i != num_attrs - 1: f.write(' &&') else: f.write(';') f.write('\n') def write_copy_implementation(f, class_name, class_def, deepcopy): if deepcopy: func_name = get_deepcopy_function_name(class_name) func_args = 'py::dict' else: func_name = get_copy_function_name(class_name) func_args = '' f.write(get_as_shared_ptr(class_name) + ' ' + GEN_CLASS_PREFIX + class_name + '::' + func_name + '(' + func_args + ') const {\n') # for some reason res(DefaultCtorArgType()) is not accepted by gcc... f.write(' ' + SHARED_PTR + '<' + class_name + '> res = ' + MAKE_SHARED + '<' + class_name + '>(' + DEFAULT_CTOR_ARG_TYPE +'());\n') items = class_def[KEY_ITEMS] if has_single_superclass(class_def): f.write(' res->' + CLASS_NAME_ATTR + ' = ' + CLASS_NAME_ATTR + ';\n') # TODO - deepcopy - for for item in items: name = item[KEY_NAME] if not deepcopy: # simply use assign operator f.write(' res->' + name + ' = ' + name + ';\n') else: # pointers must be deepcopied # also vectors containing pointers, cannot use aux functions for copying vectors # because name of the deepcpy function is different for each class t = item[KEY_TYPE] # check for 2D lists innermost_list_ptr_type = None if is_yaml_list_type(t): inner = get_inner_list_type(t) if is_yaml_ptr_type(inner): innermost_list_ptr_type = inner elif is_yaml_list_type(inner): inner2 = get_inner_list_type(inner) if is_yaml_ptr_type(inner2): assert False, "2D lists containing pointers are not supported for deepcopy yet" if innermost_list_ptr_type: base_t = remove_ptr_mark(innermost_list_ptr_type) f.write(' for (const auto& item: ' + name + ') {\n') f.write(' res->' + name + '.push_back((' + IS_SET + '(item)) ? ' + 'item->' + get_deepcopy_function_name(base_t) + '() : ' 'nullptr);\n') f.write(' }\n') elif is_yaml_dict_type(t): assert False, "Dict type is not supported for deepcopy yet" elif is_yaml_ptr_type(t): base_t = remove_ptr_mark(t) f.write(' res->' + name + ' = ' + IS_SET + '(' + name + ') ? ' + name + '->' + get_deepcopy_function_name(base_t) + '() : ' 'nullptr;\n') else: f.write(' res->' + name + ' = ' + name + ';\n') f.write('\n') f.write(' return res;\n') f.write('}\n\n') def write_operator_equal_implementation(f, class_name, class_def): # originally was operator== used, but this causes too cryptic compilation errors, # so it was better to use python-style naming, # also the __eq__ is only defined for the 'Gen' classes, so defining operator == # might have been more confusing gen_class_name = GEN_CLASS_PREFIX + class_name f.write('bool ' + gen_class_name + '::__eq__(const ' + class_name + '& other) const {\n') write_operator_equal_body(f, class_name, class_def) f.write('}\n\n') f.write('bool ' + gen_class_name + '::eq_nonarray_attributes(const ' + class_name + '& other, const bool ignore_name) const {\n') write_operator_equal_body(f, class_name, class_def, skip_arrays_and_name=True) f.write('}\n\n') def write_set_initialized_implemetation(f, class_name, items): # originally was operator== used, but this causes too cryptic compilation errors, # so it was better to use python-style naming, # also the __eq__ is aonly defined for the 'Gen' classes, so defining operator == # might have been more confusing gen_class_name = GEN_CLASS_PREFIX + class_name f.write('void ' + gen_class_name + '::' + DECL_SET_INITIALIZED + ' {\n') num_attrs = len(items) for i in range(num_attrs): name = items[i][KEY_NAME] t = items[i][KEY_TYPE] if is_yaml_ptr_type(t): f.write(' if (is_set(' + name + ')) {\n') f.write(' ' + name + '->set_initialized();\n') f.write(' }\n') elif is_yaml_list_type(t) and is_yaml_ptr_type(get_inner_list_type(t)): f.write(' vec_set_initialized(' + name + ');\n') f.write(' initialized = true;\n') f.write('}\n\n') def is_overloaded(method, class_def): name = method[KEY_NAME] count = 0 for m in class_def[KEY_METHODS]: if m[KEY_NAME] == name: count += 1 assert count >= 1 return count >= 2 def get_method_overload_cast(method): res = 'py::overload_cast<' if KEY_PARAMS in method: params = method[KEY_PARAMS] params_cnt = len(params) for i in range(params_cnt): p = params[i] assert KEY_TYPE in p t = get_type_as_ref_param(p) res += 'const ' + t if i + 1 != params_cnt: res += ', ' res += '>' return res def create_doc_str(yaml_doc, w_quotes=True): if not yaml_doc: return "" res = yaml_doc.replace('"', '\\"') res = res.replace('\n', '\\n') res = res.replace('\\:', ':') if w_quotes: return '"' + res + '"' else: return res def write_pybind11_method_bindings(f, class_name, method, class_def): assert KEY_NAME in method name = rename_cpp_reserved_id(method[KEY_NAME]) full_method_name = '&' + class_name + '::' + name if is_overloaded(method, class_def): # overloaded method must be extra decorated with argument types for pybind11 full_method_name = get_method_overload_cast(method) + '(' + full_method_name + ')' f.write(' .def("' + name + '", ' + full_method_name) params_doc = '' if KEY_PARAMS in method: params = method[KEY_PARAMS] params_cnt = len(params) for i in range(params_cnt): f.write(', ') p = params[i] assert KEY_NAME in p param_name = p[KEY_NAME] f.write('py::arg("' + param_name + '")') if KEY_DEFAULT in p: f.write(' = ' + get_default_or_unset_value(p)) params_doc += '- ' + param_name if KEY_DOC in p: params_doc += ': ' + create_doc_str(p[KEY_DOC], False) + '\\n' params_doc += '\\n' if KEY_DOC in method or params_doc: f.write(', "') if KEY_DOC in method: f.write(create_doc_str(method[KEY_DOC], False)) if params_doc: params_doc = '\\n' + params_doc f.write(params_doc + '"') f.write(')\n') def write_pybind11_bindings(f, class_name, class_def): def_type = class_def[KEY_TYPE] items = class_def[KEY_ITEMS] write_define_binding_decl(f, class_name, def_type != VALUE_CLASS) f.write(' {\n') superclass = '' if has_superclass_other_than_base(class_def): superclass = class_def[KEY_SUPERCLASS] + ', ' ctor_has_args = True if KEY_SUPERCLASS in class_def and class_def[KEY_SUPERCLASS] == BASE_INTROSPECTION_CLASS: ctor_has_args = False if def_type == VALUE_CLASS: f.write(' return py::class_<' + class_name + ', ' + superclass + \ SHARED_PTR + '<' + class_name + '>>(m, "' + class_name + '"') if KEY_DOC in class_def: f.write(', ' + create_doc_str(class_def[KEY_DOC])) f.write(')\n') f.write(' .def(\n') f.write(' py::init<\n') num_items = len(items) if ctor_has_args: if has_single_superclass(class_def) or is_container_class_no_model(class_name): # init operands for i in range(num_items): attr = items[i] if attr_not_in_ctor(attr): continue const_spec = 'const ' if not is_yaml_ptr_type(attr[KEY_TYPE]) else '' f.write(' ' + const_spec + get_type_as_ref_param(attr)) if i != num_items - 1: f.write(',\n') if num_items != 0: f.write('\n') f.write(' >()') if ctor_has_args: # init argument names and default values if has_single_superclass(class_def) or is_container_class_no_model(class_name): if num_items != 0: f.write(',') f.write('\n') for i in range(num_items): attr = items[i] if attr_not_in_ctor(attr): continue name = attr[KEY_NAME] f.write(' py::arg("' + name + '")') if KEY_DEFAULT in attr: f.write(' = ' + get_default_or_unset_value(attr)) if i != num_items - 1: f.write(',\n') f.write('\n') f.write(' )\n') # common methods if has_single_superclass(class_def): f.write(' .def("check_semantics", &' + class_name + '::check_semantics)\n') f.write(' .def("__copy__", &' + class_name + '::' + get_copy_function_name(class_name) + ')\n') f.write(' .def("__deepcopy__", &' + class_name + '::' + get_deepcopy_function_name(class_name) + ', py::arg("memo"))\n') f.write(' .def("__str__", &' + class_name + '::to_str, py::arg("all_details") = false, py::arg("ind") = std::string(""))\n') # keeping the default __repr__ implementation for better error messages #f.write(' .def("__repr__", &' + class_name + '::to_str, py::arg("ind") = std::string(""))\n') f.write(' .def("__eq__", &' + class_name + '::__eq__, py::arg("other"))\n') else: f.write(' m.def_submodule("' + class_name + '")\n') # declared methods for m in class_def[KEY_METHODS]: if not has_single_superclass(class_def) or not is_inherited(m): write_pybind11_method_bindings(f, class_name, m, class_def) if def_type == VALUE_CLASS: # dump needs to be always implemented f.write(' .def("dump", &' + class_name + '::dump)\n') # properties for i in range(num_items): if not has_single_superclass(class_def) or not is_inherited(items[i]): name = items[i][KEY_NAME] f.write(' .def_property("' + name + '", &' + class_name + '::get_' + name + ', &' + class_name + '::set_' + name) if is_yaml_list_type(items[i][KEY_TYPE]): f.write(', py::return_value_policy::reference') if KEY_DOC in items[i]: f.write(', ' + create_doc_str(items[i][KEY_DOC])) f.write(')\n') f.write(' ;\n') f.write('}\n\n') def write_used_classes_includes(f, class_def): types = get_all_used_compound_types_no_decorations(class_def) for t in types: f.write('#include "' + get_api_class_file_name_w_dir(t, EXT_H) + '"\n') def write_set_all_default_or_unset(f, class_name, class_def): f.write( RET_TYPE_SET_ALL_DEFAULT_OR_UNSET + ' ' + GEN_CLASS_PREFIX + class_name + '::' + SET_ALL_DEFAULT_OR_UNSET_DECL + ' {' + '\n' ) # we do not need to call the derived methods because all members were inherited f.write(' ' + CLASS_NAME_ATTR + ' = "' + class_name + '";\n') items = class_def[KEY_ITEMS] num_items = len(items) for i in range(num_items): assert KEY_NAME in items[i] attr_name = items[i][KEY_NAME] f.write(' ' + attr_name + ' = ' + get_default_or_unset_value(items[i]) + ';\n') f.write('}\n\n') def generate_class_implementation_and_bindings(class_name, class_def): # returns a list of methods to be declared decls = '' with open(get_gen_class_file_name_w_dir(class_name, EXT_CPP), 'w') as f: def_type = class_def[KEY_TYPE] f.write(COPYRIGHT) write_generated_notice(f) f.write('#include <sstream>\n') f.write('#include "api/pybind11_stl_include.h"\n') f.write(INCLUDE_API_PYTHON_EXPORT_UTILS_H + '\n') # includes for our class f.write('#include "' + get_gen_class_file_name(class_name, EXT_H) + '"\n') if def_type == VALUE_CLASS: f.write('#include "' + get_api_class_file_name_w_dir(class_name, EXT_H) + '"\n') # we also need includes for every type that we used write_used_classes_includes(f, class_def) f.write('\n' + NAMESPACES_BEGIN + '\n\n') if def_type == VALUE_CLASS: items = class_def[KEY_ITEMS] if has_single_superclass(class_def): write_check_semantics_implemetation(f, class_name, items) write_set_initialized_implemetation(f, class_name, items) write_set_all_default_or_unset(f, class_name, class_def) write_copy_implementation(f, class_name, class_def, False) write_copy_implementation(f, class_name, class_def, True) write_operator_equal_implementation(f, class_name, class_def) write_to_str_implementation(f, class_name, items, has_single_superclass(class_def)) write_pybind11_bindings(f, class_name, class_def) # we do not need export for introspected classes if is_container_class(class_name) or \ (KEY_SUPERCLASS in class_def and class_def[KEY_SUPERCLASS] != BASE_INTROSPECTION_CLASS): decls += write_export_to_python_implementation(f, class_name, class_def); f.write(NAMESPACES_END + '\n\n') return decls # class Model provides the same methods as Subsystem and Instantiation, # this function copies the definition for pybind11 API generation def inherit_from_superclasses(data_classes, class_name, class_def): res = class_def.copy() superclass_names = [] if has_superclass_other_than_base(class_def): superclass_names.append(class_def[KEY_SUPERCLASS]) if KEY_SUPERCLASSES in class_def: superclass_names += class_def[KEY_SUPERCLASSES] for sc_name in superclass_names: assert sc_name in data_classes superclass_def = data_classes[sc_name] assert not has_superclass_other_than_base(superclass_def), "Only one level of inheritance" # we are not checking any duplicates if KEY_METHODS in superclass_def: for method in superclass_def[KEY_METHODS]: method_copy = copy(method) method_copy[KEY_INHERITED] = True res[KEY_METHODS].append(method_copy) class_attr_names = set() if KEY_ITEMS in class_def: for attr in class_def[KEY_ITEMS]: class_attr_names.add(attr[KEY_NAME]) if KEY_ITEMS in superclass_def: for attr in superclass_def[KEY_ITEMS]: attr_copy = copy(attr) attr_copy[KEY_INHERITED] = True res[KEY_ITEMS].append(attr_copy) # do not inherit attribute if the attribute with the same name already exists if attr[KEY_NAME] in class_attr_names: attr_copy[KEY_NOT_AS_CTOR_ARG] = True return res def generate_class_files(data_classes, class_name, class_def): # we need items and methods to be present if KEY_ITEMS not in class_def: class_def[KEY_ITEMS] = [] if KEY_METHODS not in class_def: class_def[KEY_METHODS] = [] class_def_w_inheritances = inherit_from_superclasses(data_classes, class_name, class_def) decls = generate_class_implementation_and_bindings(class_name, class_def_w_inheritances) generate_class_header(class_name, class_def_w_inheritances, decls) generate_class_template(class_name, class_def_w_inheritances) def write_constant_def(f, constant_def): assert KEY_NAME in constant_def assert KEY_TYPE in constant_def assert KEY_VALUE in constant_def name = constant_def[KEY_NAME] t = constant_def[KEY_TYPE] value = constant_def[KEY_VALUE] # complex types are defined manually in globals.h if is_base_yaml_type(t): q = '"' if t == YAML_TYPE_STR else '' f.write('const ' + yaml_type_to_cpp_type(t) + ' ' + name + ' = ' + q + str(value) + q + ';\n') def write_enum_def(f, enum_def): assert KEY_NAME in enum_def assert KEY_VALUES in enum_def, "Enum must have at least one value" name = enum_def[KEY_NAME] values = enum_def[KEY_VALUES] f.write('\nenum class ' + name + ' {\n') num = len(values) for i in range(num): v = values[i] assert KEY_NAME in v assert KEY_VALUE in v assert type(v[KEY_VALUE]) == int f.write(' ' + v[KEY_NAME] + ' = ' + str(v[KEY_VALUE])) if i + 1 != num: f.write(',') f.write('\n') f.write('};\n\n') f.write('\nstatic inline std::ostream& operator << (std::ostream& out, const ' + name + ' v) {\n') f.write(' switch (v) {\n'); for i in range(num): v = values[i] # dumping in Python style '.' that will be most probably more common as API #f.write(' case ' + name + '::' + v[KEY_NAME] + ': out << "' + name + '.' + v[KEY_NAME] + ' (' + str(v[KEY_VALUE]) + ')"; break;\n') # dumping as Python code f.write(' case ' + name + '::' + v[KEY_NAME] + ': out << "' + M_DOT + name + '.' + v[KEY_NAME] + '"; break;\n') f.write(' }\n') f.write(' return out;\n') f.write('};\n\n') def generate_constants_header(constants_items, enums_items): with open(os.path.join(TARGET_DIRECTORY, GEN_CONSTANTS_H), 'w') as f: f.write(COPYRIGHT) write_generated_notice(f) guard = 'API_GEN_CONSTANTS'; f.write('#ifndef ' + guard + '\n') f.write('#define ' + guard + '\n\n') f.write('#include <string>\n') f.write('#include <climits>\n') f.write('#include <cfloat>\n') f.write('#include "api/globals.h"\n') f.write('\n' + NAMESPACES_BEGIN + '\n\n') for constant_def in constants_items: write_constant_def(f, constant_def) for enum_def in enums_items: write_enum_def(f, enum_def) f.write('\n' + DECL_DEFINE_PYBINDIND_CONSTANTS + ';\n') f.write(DECL_DEFINE_PYBINDIND_ENUMS + ';\n\n') f.write(NAMESPACES_END + '\n\n') f.write('#endif // ' + guard + '\n\n') def write_constant_binding(f, constant_def): assert KEY_NAME in constant_def assert KEY_TYPE in constant_def assert KEY_VALUE in constant_def name = constant_def[KEY_NAME] t = constant_def[KEY_TYPE] value = constant_def[KEY_VALUE] #q = '"' if t == YAML_TYPE_STR else '' pybind_type = yaml_type_to_pybind_type(t) if pybind_type == PYBIND_TYPE_OBJECT: f.write(' m.attr("' + name + '") = py::' + PYBIND_TYPE_OBJECT + '(' + PY_CAST + '(' + name + '));\n') else: f.write(' m.attr("' + name + '") = py::' + pybind_type + '(' + name + ');\n') def write_enum_binding(f, enum_def): assert KEY_NAME in enum_def assert KEY_VALUES in enum_def, "Enum must have at least one value" name = enum_def[KEY_NAME] values = enum_def[KEY_VALUES] num = len(values) f.write(' py::enum_<' + name + '>(m, "' + name + '", py::arithmetic()') # Pybind11 does nto allow help for enum members so we put all that information into # the header members_doc = '' for i in range(num): v = values[i] assert KEY_NAME in v members_doc += '- ' + v[KEY_NAME] if KEY_DOC in v: members_doc += ': ' + create_doc_str(v[KEY_DOC], False) else: members_doc += '\\n' members_doc += '\\n' if KEY_DOC in enum_def or members_doc: f.write(', "') if KEY_DOC in enum_def: f.write(create_doc_str(enum_def[KEY_DOC], False) + '\\n') f.write(members_doc + '"') f.write(')\n') for i in range(num): v = values[i] assert KEY_NAME in v f.write(' .value("' + v[KEY_NAME] + '", ' + name + '::' + v[KEY_NAME] + ')\n') f.write(' .export_values();\n') def generate_constants_implementation(constants_items, enums_items): with open(os.path.join(TARGET_DIRECTORY, GEN_CONSTANTS_CPP), 'w') as f: f.write(COPYRIGHT) write_generated_notice(f) f.write(INCLUDE_API_COMMON_H + '\n') # includes for used classes used_classes = set() for constant_def in constants_items: t = constant_def[KEY_TYPE] pybind_type = yaml_type_to_pybind_type(t) if pybind_type == PYBIND_TYPE_OBJECT: used_classes.add(t) for cls in used_classes: f.write('#include "' + get_api_class_file_name_w_dir(cls, EXT_H) + '"\n') f.write('\n' + NAMESPACES_BEGIN + '\n\n') f.write(DECL_DEFINE_PYBINDIND_CONSTANTS + ' {\n') for constant_def in constants_items: write_constant_binding(f, constant_def) f.write('}\n\n') f.write(DECL_DEFINE_PYBINDIND_ENUMS + ' {\n') for enum_def in enums_items: write_enum_binding(f, enum_def) f.write('}\n\n') f.write(NAMESPACES_END + '\n\n') def generate_constants_and_enums(constants_items, enums_items): generate_constants_header(constants_items, enums_items) generate_constants_implementation(constants_items, enums_items) def set_global_enums(data_classes): global g_enums res = set() enum_defs = data_classes[KEY_ENUMS] if KEY_ENUMS in data_classes else [] for enum in enum_defs: assert KEY_NAME in enum res.add(enum[KEY_NAME]) g_enums = res def capitalize_first(s): if s[0].islower(): return s[0].upper() + s[1:] else: return s def generate_vector_bindings(data_classes): # collect all attributes that use List list_types = set() used_types = set() for key, value in data_classes.items(): if key != KEY_CONSTANTS and key != KEY_ENUMS: # items if KEY_ITEMS in value: for item in value[KEY_ITEMS]: if is_yaml_list_type(item[KEY_TYPE]): t = item[KEY_TYPE] list_types.add(t) inner = get_inner_list_type(t) if is_yaml_list_type(inner): inner = get_inner_list_type(inner) used_types.add(inner) sorted_list_types = sorted(list_types) sorted_used_types = sorted(used_types) # generate gen_make_opaque.h with open(os.path.join(TARGET_DIRECTORY, GEN_VECTORS_MAKE_OPAQUE_H), 'w') as f: f.write(COPYRIGHT) guard = 'GEN_VECTORS_MAKE_OPAQUE_H' f.write('#ifndef ' + guard + '\n') f.write('#define ' + guard + '\n\n') f.write('#include <vector>\n') f.write('#include <memory>\n') f.write('#include "pybind11/include/pybind11/pybind11.h"\n') f.write('#include "defines.h"\n\n') f.write(NAMESPACES_BEGIN + '\n\n') for t in sorted_used_types: if is_base_yaml_type(t): continue assert is_yaml_ptr_type(t) f.write('class ' + t[:-1] + ';\n') f.write('\n' + NAMESPACES_END + '\n\n') for t in sorted_list_types: f.write(PYBIND11_MAKE_OPAQUE + '(' + yaml_type_to_cpp_type(t, True) + ');\n') f.write('\n#endif // ' + guard + '\n') # generate gen_bind_vector.cpp with open(os.path.join(TARGET_DIRECTORY, GEN_VECTORS_BIND_CPP), 'w') as f: f.write(COPYRIGHT + '\n') f.write('#include "api/pybind11_stl_include.h"\n') f.write('#include "pybind11/include/pybind11/stl_bind.h"\n') f.write('#include "pybind11/include/pybind11/numpy.h"\n\n') f.write('namespace py = pybind11;\n\n') for t in sorted_used_types: if is_base_yaml_type(t): continue assert is_yaml_ptr_type(t) f.write('#include "' + get_api_class_file_name_w_dir(t[:-1], EXT_H) + '"\n') f.write('\n') f.write(NAMESPACES_BEGIN + '\n\n') f.write('void ' + GEN_VECTORS_BIND + '{\n') ind = ' ' for t in sorted_list_types: cpp_t = yaml_type_to_cpp_type(t, True) name = 'Vector' inner = get_inner_list_type(t) if is_yaml_list_type(inner): inner2 = get_inner_list_type(inner) name += name + capitalize_first(inner2) else: name += capitalize_first(inner) if name[-1] == '*': name = name[:-1] f.write(ind + PY_BIND_VECTOR + '<' + cpp_t + '>(m,"' + name + '");\n') f.write(ind + PY_IMPLICITLY_CONVERTIBLE + '<py::list, ' + cpp_t + '>();\n') f.write(ind + PY_IMPLICITLY_CONVERTIBLE + '<py::tuple, ' + cpp_t + '>();\n') # special case for numpy conversions if name == 'VectorFloat': f.write(ind + PY_IMPLICITLY_CONVERTIBLE + '<py::array_t<double>, ' + cpp_t + '>();\n') elif name == 'VectorInt': f.write(ind + PY_IMPLICITLY_CONVERTIBLE + '<py::array_t<int>, ' + cpp_t + '>();\n') f.write('\n') f.write('}\n') f.write('\n' + NAMESPACES_END + '\n\n') def generate_data_classes(data_classes): generate_constants_and_enums( data_classes[KEY_CONSTANTS] if KEY_CONSTANTS in data_classes else [], data_classes[KEY_ENUMS] if KEY_ENUMS in data_classes else []) set_global_enums(data_classes) # std::vector/list needs special handling because we need it to be opaque # so that the user can modify the internal value generate_vector_bindings(data_classes) for key, value in data_classes.items(): if key != KEY_CONSTANTS and key != KEY_ENUMS: # set default definition type if not KEY_TYPE in value: value[KEY_TYPE] = VALUE_CLASS if VERBOSE: if value[KEY_TYPE] == VALUE_CLASS: print("Generating class " + key) elif value[KEY_TYPE] == VALUE_SUBMODULE: print("Generating submodule " + key) else: assert False, "Unknown definition type" generate_class_files(data_classes, key, value) def collect_all_names(data_classes): all_class_names = set() all_item_param_names = set() all_enum_value_names = set() all_const_value_names = set() for key, value in data_classes.items(): if key != KEY_CONSTANTS and key != KEY_ENUMS: all_class_names.add(key) # items if KEY_ITEMS in value: for item in value[KEY_ITEMS]: all_item_param_names.add(item[KEY_NAME]) # methods if KEY_METHODS in value: for method in value[KEY_METHODS]: all_item_param_names.add(method[KEY_NAME]) if KEY_PARAMS in method: for param in method[KEY_PARAMS]: all_item_param_names.add(param[KEY_NAME]) elif key == KEY_ENUMS: # enum names are in g_enums for enum in value: if KEY_VALUES in enum: for enum_item in enum[KEY_VALUES]: all_enum_value_names.add(enum_item[KEY_NAME]) elif key == KEY_CONSTANTS: for const in value: all_const_value_names.add(const[KEY_NAME]) else: print("Error: unexpected top level key " + key) sys.exit(1) all_class_names = list(all_class_names) all_class_names.sort(key=str.casefold) all_item_param_names_list = list(all_item_param_names) all_item_param_names_list.sort(key=str.casefold) all_enum_value_names_list = list(all_enum_value_names) all_enum_value_names_list.sort(key=str.casefold) all_const_value_names_list = list(all_const_value_names) all_const_value_names_list.sort(key=str.casefold) return all_class_names, all_item_param_names_list, all_enum_value_names_list, all_const_value_names_list def write_name_def(f, name, extra_prefix=''): upper_name = get_underscored(name).upper() f.write('const char* const ' + NAME_PREFIX + extra_prefix + upper_name + ' = "' + name + '";\n') def write_name_def_verbatim(f, name, extra_prefix=''): f.write('const char* const ' + NAME_PREFIX + extra_prefix + name + ' = "' + name + '";\n') # this function generates definitions for converter so that we can use constant strings def generate_names_header(data_classes): all_class_names, all_item_param_names_list, all_enum_value_names_list, all_const_value_names_list = collect_all_names(data_classes) with open(os.path.join(TARGET_DIRECTORY, GEN_NAMES_H), 'w') as f: f.write(COPYRIGHT) write_generated_notice(f) guard = 'API_GEN_NAMES'; f.write('#ifndef ' + guard + '\n') f.write('#define ' + guard + '\n\n') f.write('\n' + NAMESPACES_BEGIN + '\n\n') for name in all_class_names: write_name_def(f, name, CLASS_PREFIX) f.write('\n') for name in all_item_param_names_list: write_name_def(f, name) f.write('\n') all_enums_list = list(g_enums) all_enums_list.sort(key=str.casefold) for name in all_enums_list: write_name_def(f, name, ENUM_PREFIX) f.write('\n') for name in all_enum_value_names_list: write_name_def_verbatim(f, name, ENUM_VALUE_PREFIX) f.write('\n') for name in all_const_value_names_list: write_name_def_verbatim(f, name, CONSTANT_VALUE_PREFIX) f.write('\n') f.write(NAMESPACES_END + '\n\n') f.write('#endif // ' + guard + '\n\n') def generate_pyi_class(f, name, class_def): f.write('class ' + name + '():\n') f.write(' def __init__(\n') param_ind = ' ' f.write(param_ind + 'self,\n') # ctor if KEY_ITEMS in class_def: generated_params = set() num_items = len(class_def[KEY_ITEMS]) for i in range(0, num_items): item = class_def[KEY_ITEMS][i] name = item[KEY_NAME] if name in generated_params: continue generated_params.add(name) f.write(param_ind + name) # self-referencing classes must use string type reference # https://www.python.org/dev/peps/pep-0484/#forward-references t = yaml_type_to_py_type(item[KEY_TYPE]) q = '\'' if t == name else '' f.write(' : ' + q + t + q) if KEY_DEFAULT in item: f.write(' = ' + get_default_or_unset_value_py(item)) if i + 1 != num_items: f.write(',') f.write('\n') f.write(' ):\n') # class members if KEY_ITEMS in class_def and class_def[KEY_ITEMS]: num_items = len(class_def[KEY_ITEMS]) for i in range(0, num_items): member_name = class_def[KEY_ITEMS][i][KEY_NAME] f.write(' self.' + member_name + ' = ' + member_name + '\n') else: f.write(' pass') f.write('\n\n') if KEY_METHODS in class_def: # for now, we just simply print the first variant oif there are multiple methods with the same name printed_methods = set() for method in class_def[KEY_METHODS]: method_name = method[KEY_NAME] if method_name in printed_methods: continue printed_methods.add(method_name) f.write(' def ' + method[KEY_NAME] + '(\n') f.write(param_ind + 'self,\n') if KEY_PARAMS in method: num_params = len(method[KEY_PARAMS]) for i in range(0, num_params): param = method[KEY_PARAMS][i] f.write(param_ind + param[KEY_NAME]) t = yaml_type_to_py_type(param[KEY_TYPE]) q = '\'' if t == name else '' f.write(' : ' + q + t + q) if KEY_DEFAULT in param: f.write(' = ' + get_default_or_unset_value_py(param)) if i + 1 != num_params: f.write(',') f.write('\n') f.write(' )') if KEY_RETURN_TYPE in method: f.write(' -> \'' + yaml_type_to_py_type(method[KEY_RETURN_TYPE]) + '\'') else: f.write(' -> ' + PY_NONE) f.write(':\n') f.write(' pass\n\n') def generate_pyi_file(data_classes): with open(os.path.join(TARGET_DIRECTORY, MCELL_PYI), 'w') as f: f.write('from typing import List, Dict, Callable, Any\n') f.write('from enum import Enum\n\n') f.write('INT32_MAX = 2147483647 # do not use this constant in your code\n\n') f.write('FLT_MAX = 3.40282346638528859812e+38 # do not use this constant in your code\n\n') f.write('# "forward" declarations to make the type hints valid\n') for key, value in sorted(data_classes.items()): if key != KEY_CONSTANTS and key != KEY_ENUMS: f.write('class ' + key + '():\n pass\n') f.write('\n') species_def = '' # Vec3 f.write( 'class Vec3():\n' ' def __init__(self, x : float = 0, y : float = 0, z : float = 0):\n' ' self.x = x\n' ' self.y = y\n' ' self.z = z\n' '\n' 'class Vec2():\n' ' def __init__(self, u : float = 0, v : float = 0):\n' ' self.u = u\n' ' self.v = v\n' '\n' ) # generate enums first, then constants enums = data_classes[KEY_ENUMS] for enum in enums: f.write('class ' + enum[KEY_NAME] + '(Enum):\n') for enum_item in enum[KEY_VALUES]: f.write(' ' + enum_item[KEY_NAME] + ' = ' + str(enum_item[KEY_VALUE]) + '\n') f.write('\n') f.write('\n\n') constants = data_classes[KEY_CONSTANTS] for const in constants: if const[KEY_TYPE] == YAML_TYPE_SPECIES: # Species constants are a bit special ctor_param = get_underscored(const[KEY_VALUE]).upper() species_def += const[KEY_NAME] + ' = ' + YAML_TYPE_SPECIES + '(\'' + ctor_param + '\')\n' elif const[KEY_TYPE] == YAML_TYPE_STR: f.write(const[KEY_NAME] + ' = \'' + str(const[KEY_VALUE]) + '\'\n') else: f.write(const[KEY_NAME] + ' = ' + str(const[KEY_VALUE]) + '\n') f.write('\n\n') for key, value in sorted(data_classes.items()): if key != KEY_CONSTANTS and key != KEY_ENUMS: generate_pyi_class(f, key, value) # we need to define the Species contants after they were defined f.write(species_def) def indent_and_fix_rst_chars(text, indent): return text.replace('\n', '\n' + indent).replace('*', '\\*').replace('@', '\\@') def load_and_generate_data_classes(): # create work directory work_dir = os.path.join('..', 'work') if not os.path.exists(work_dir): os.mkdir(work_dir) data_classes = {} for cat in CATEGORIES: input_file = cat + '.yaml' with open(input_file) as file: # The FullLoader parameter handles the conversion from YAML # scalar values to Python the dictionary format loaded_data = yaml.load(file, Loader=yaml.FullLoader) if loaded_data: # set information about the original file name for key,value in loaded_data.items(): if key != KEY_CONSTANTS and key != KEY_ENUMS: value[KEY_CATEGORY] = cat data_classes.update(loaded_data) else: print("File " + input_file + " is empty (or could not be loaded as yaml), ignoring it") if VERBOSE: print("Loaded " + input_file) if VERBOSE: print(data_classes) assert type(data_classes) == dict generate_data_classes(data_classes) generate_names_header(data_classes) generate_pyi_file(data_classes) doc.generate_documentation(data_classes) if __name__ == '__main__': if len(sys.argv) == 2 and sys.argv[1] == '-v': VERBOSE = True load_and_generate_data_classes()
Python
3D
mcellteam/mcell
libmcell/definition/constants.py
.py
6,512
225
""" 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. """ # categories, defines input file names and # also ordering in documentation CATEGORY_CONSTANTS = 'constants' CATEGORIES = [ CATEGORY_CONSTANTS, 'model', 'simulation_setup', 'subsystem', 'geometry', 'instantiation', 'observables', 'callbacks', 'introspection', 'checkpointing', 'submodules', ] COPYRIGHT = \ """/****************************************************************************** * * Copyright (C) 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. * ******************************************************************************/\n """ EXAMPLES_BASE_URL = 'https://github.com/mcellteam/mcell_tests/blob/master/' TARGET_DIRECTORY = '..' + '/' + 'generated' DOC_DIRECTORY = '..' + '/' + 'documentation' + '/' + 'generated' API_DIRECTORY = 'api' WORK_DIRECTORY = '..' + '/' + 'work' KEY_ITEMS = 'items' KEY_NAME = 'name' ATTR_NAME_NAME = 'name' # attrribute with name 'name' is already defined in BaseDataClass KEY_TYPE = 'type' KEY_VALUE = 'value' KEY_VALUES = 'values' KEY_DEFAULT = 'default' KEY_DOC = 'doc' KEY_EXAMPLES = 'examples' KEY_CATEGORY = 'category' # set from input file name KEY_SUPERCLASS = 'superclass' KEY_SUPERCLASSES = 'superclasses' KEY_CONSTANTS = 'constants' KEY_ENUMS = 'enums' KEY_METHODS = 'methods' KEY_PARAMS = 'params' KEY_RETURN_TYPE = 'return_type' KEY_IS_CONST = 'is_const' KEY_INHERITED = 'inherited' # used only internally, not in input YAML KEY_NOT_AS_CTOR_ARG = 'not_as_ctor_arg' VALUE_CLASS = 'class' VALUE_SUBMODULE = 'submodule' YAML_TYPE_PY_OBJECT = 'py::object' YAML_TYPE_FLOAT = 'float' YAML_TYPE_STR = 'str' YAML_TYPE_INT = 'int' YAML_TYPE_UINT32 = 'uint32' YAML_TYPE_UINT64 = 'uint64' YAML_TYPE_BOOL = 'bool' YAML_TYPE_VEC2 = 'Vec2' YAML_TYPE_VEC3 = 'Vec3' YAML_TYPE_IVEC3 = 'IVec3' YAML_TYPE_LIST = 'List' YAML_TYPE_DICT = 'Dict' YAML_TYPE_SPECIES = 'Species' YAML_TYPE_ORIENTATION = 'Orientation' YAML_TYPE_FUNCTION = 'std::function' PYBIND_TYPE_OBJECT = 'object' PY_CAST = 'py::cast' CPP_TYPE_FLOAT = 'float' CPP_TYPE_DOUBLE = 'double' CPP_TYPE_STR = 'std::string' CPP_TYPE_INT = 'int' CPP_TYPE_UINT32 = 'uint' CPP_TYPE_UINT64 = 'uint64_t' CPP_TYPE_BOOL = 'bool' CPP_TYPE_VEC2 = 'Vec2' CPP_TYPE_VEC3 = 'Vec3' CPP_TYPE_IVEC3 = 'IVec3' CPP_VECTOR_TYPE = 'std::vector' CPP_MAP_TYPE = 'std::map' CPP_NONREFERENCE_TYPES = [CPP_TYPE_DOUBLE, CPP_TYPE_INT, CPP_TYPE_UINT64, CPP_TYPE_UINT32, CPP_TYPE_BOOL] # + CPP_VECTOR_TYPE but it must be checked with .startswith CPP_REFERENCE_TYPES = [CPP_TYPE_STR, CPP_TYPE_VEC2, CPP_TYPE_VEC3, CPP_TYPE_IVEC3, CPP_VECTOR_TYPE] UNSET_VALUE = 'unset' EMPTY_ARRAY = 'empty' UNSET_VALUE_FLOAT = 'FLT_UNSET' UNSET_VALUE_STR = 'STR_UNSET' UNSET_VALUE_INT = 'INT_UNSET' UNSET_VALUE_UINT64 = '0' # default value, not unset UNSET_VALUE_UINT32 = '0' # default value, not unset UNSET_VALUE_VEC2 = 'VEC2_UNSET' UNSET_VALUE_VEC3 = 'VEC3_UNSET' UNSET_VALUE_ORIENTATION = 'Orientation::NOT_SET' UNSET_VALUE_PTR = 'nullptr' PY_NONE = 'None' GEN_PREFIX = 'gen_' GEN_GUARD_PREFIX = 'API_GEN_' API_GUARD_PREFIX = 'API_' GUARD_SUFFIX = '_H' CTOR_SUFFIX = '_CTOR' CTOR_NOARGS_SUFFIX = '_CTOR_NOARGS' EXT_CPP = 'cpp' EXT_H = 'h' GEN_CLASS_PREFIX = 'Gen' BASE_DATA_CLASS = 'BaseDataClass' BASE_INTROSPECTION_CLASS = 'BaseIntrospectionClass' BASE_EXPORT_CLASS = 'BaseExportClass' CLASS_NAME_MODEL = 'Model' CLASS_NAME_SUBSYSTEM = 'Subsystem' CLASS_NAME_INSTANTIATION = 'Instantiation' CLASS_NAME_OBSERVABLES = 'Observables' CTOR_POSTPROCESS = 'postprocess_in_ctor' RET_CTOR_POSTPROCESS = 'void' COPY_NAME = 'copy' DEEPCOPY_NAME = 'deepcopy' DEEPCOPY_VEC = 'deepcopy_vec' DEEPCOPY_VEC_VEC = 'deepcopy_vec_vec' IS_SET = 'is_set' DEFAULT_CTOR_ARG_TYPE = 'DefaultCtorArgType' RET_TYPE_CHECK_SEMANTICS = 'void' CHECK_SEMANTICS = 'check_semantics' DECL_CHECK_SEMANTICS = CHECK_SEMANTICS + '() const' DECL_DEFINE_PYBINDIND_CONSTANTS = 'void define_pybinding_constants(py::module& m)' DECL_DEFINE_PYBINDIND_ENUMS = 'void define_pybinding_enums(py::module& m)' DECL_SET_INITIALIZED = 'set_initialized()' RET_TYPE_SET_ALL_DEFAULT_OR_UNSET = 'void' SET_ALL_DEFAULT_OR_UNSET_DECL = 'set_all_attributes_as_default_or_unset()' SET_ALL_CUSTOM_TO_DEFAULT_DECL = 'set_all_custom_attributes_to_default()' RET_TYPE_TO_STR = 'std::string' SHARED_PTR = 'std::shared_ptr' MAKE_SHARED = 'std::make_shared' DECL_TO_STR_W_DEFAULT = 'to_str(const bool all_details=false, const std::string ind="") const' DECL_TO_STR = 'to_str(const bool all_details, const std::string ind) const' RET_TYPE_EXPORT_TO_PYTHON = 'std::string' CTX = 'ctx' EXPORTED_NAME = 'exported_name' EXPORT_TO_PYTHON_ARGS = 'std::ostream& out, PythonExportContext& ' + CTX DECL_EXPORT_TO_PYTHON = 'export_to_python(' + EXPORT_TO_PYTHON_ARGS + ')' EXPORT_VEC_PREFIX = 'export_vec_' M_DOT = 'm.' KEYWORD_OVERRIDE = 'override' KEYWORD_VIRTUAL = 'virtual' CLASS_NAME_ATTR = 'class_name' CACHED_DATA_ARE_UPTODATE_ATTR = 'cached_data_are_uptodate' GEN_VECTORS_BIND = 'gen_vectors_bind(py::module& m)' GEN_CONSTANTS_H = 'gen_constants.h' GEN_CONSTANTS_CPP = 'gen_constants.cpp' GEN_VECTORS_MAKE_OPAQUE_H = 'gen_vectors_make_opaque.h' GEN_VECTORS_BIND_CPP = 'gen_vectors_bind.cpp' MCELL_PYI = 'mcell.pyi' EXT_RST = '.rst' API_RST = 'api' + EXT_RST GEN_NAMES_H = 'gen_names.h' NAME_PREFIX = 'NAME_' CLASS_PREFIX = 'CLASS_' ENUM_PREFIX = 'ENUM_' ENUM_VALUE_PREFIX = 'EV_' CONSTANT_VALUE_PREFIX = 'CV_' INCLUDE_API_MCELL_H = '#include "api/mcell.h"' INCLUDE_API_COMMON_H = '#include "api/api_common.h"' INCLUDE_API_PYTHON_EXPORT_UTILS_H = '#include "api/python_export_utils.h"' INCLUDE_API_BASE_DATA_CLASS_H = '#include "api/base_data_class.h"' INCLUDE_API_BASE_EXPORT_CLASS_H = '#include "api/base_export_class.h"' INCLUDE_API_BASE_INTROSPECTION_CLASS_H = '#include "api/base_introspection_class.h"' NAMESPACES_BEGIN = 'namespace MCell {\nnamespace API {' NAMESPACES_END = '} // namespace API\n} // namespace MCell' VEC_NONPTR_TO_STR = 'vec_nonptr_to_str' VEC_PTR_TO_STR = 'vec_ptr_to_str' F_TO_STR = 'f_to_str' PY_BIND_VECTOR = 'py::bind_vector' PY_IMPLICITLY_CONVERTIBLE = 'py::implicitly_convertible' PYBIND11_MAKE_OPAQUE = 'PYBIND11_MAKE_OPAQUE'
Python
3D
mcellteam/mcell
libmcell/definition/doc.py
.py
7,463
213
""" Copyright (C) 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. """ import sys import os import yaml from constants import * from gen import indent_and_fix_rst_chars, yaml_type_to_py_type, get_default_or_unset_value_py def cat_to_title(cat): if cat == CATEGORY_CONSTANTS: return 'Enums and Constants' else: return cat.replace('_', ' ').capitalize() def write_cat_label(f, cat): f.write('.. _api-' + cat + ':\n\n') def gen_example_links(base_links): split_links = base_links.strip().split() n = len(split_links) if n == 0: return '' res = 'Example' + ('' if n == 1 else 's') + ': ' for l in split_links: name = os.path.basename(os.path.dirname(l)) + '/' + os.path.basename(l) res += '`' + name + ' <' + EXAMPLES_BASE_URL + l + '>`_ ' return res def write_h4(f, text, name, class_name): f.write('.. _' + class_name + '__' + name + ':\n\n') f.write(text + '\n') f.write('-' * len(text) + '\n\n') def get_method_declaration(method): res = method[KEY_NAME] + ' (' if KEY_PARAMS in method: num_params = len(method[KEY_PARAMS]) for i in range(num_params): param = method[KEY_PARAMS][i] t = yaml_type_to_py_type(param[KEY_TYPE]) res += param[KEY_NAME] + ': ' + t if KEY_DEFAULT in param: res += '=' + get_default_or_unset_value_py(param) if i != num_params - 1: res += ', ' res += ')' if KEY_RETURN_TYPE in method: res += ' -> ' + yaml_type_to_py_type(method[KEY_RETURN_TYPE]) return res def generate_class_documentation(f, class_name, class_def): f.write(class_name + '\n' + '='*len(class_name) + '\n\n') if KEY_DOC in class_def: f.write(class_def[KEY_DOC].strip() + '\n\n') if KEY_EXAMPLES in class_def: f.write(gen_example_links(class_def[KEY_EXAMPLES]) + '\n\n') if KEY_ITEMS in class_def and class_def[KEY_ITEMS]: f.write('Attributes:\n' + '*'*len('Attributes:') + '\n') num_items = len(class_def[KEY_ITEMS]) for item in class_def[KEY_ITEMS]: t = yaml_type_to_py_type(item[KEY_TYPE]) header = item[KEY_NAME] + ': ' + t write_h4(f, header, item[KEY_NAME], class_name) if KEY_DOC in item and item[KEY_DOC]: f.write(' | ' + indent_and_fix_rst_chars(item[KEY_DOC].strip(), ' | ') + '\n') if KEY_DEFAULT in item: f.write(' | - default argument value in constructor: ' + get_default_or_unset_value_py(item)) f.write('\n') if KEY_EXAMPLES in item: f.write('\n | ' + gen_example_links(item[KEY_EXAMPLES]) + '\n\n') f.write('\n') if KEY_METHODS in class_def and class_def[KEY_METHODS]: f.write('\nMethods:\n' + '*'*len('nMethods:') + '\n') for method in class_def[KEY_METHODS]: method_name = method[KEY_NAME] header = get_method_declaration(method) write_h4(f, header, method_name, class_name) if KEY_DOC in method: f.write('\n | ' + indent_and_fix_rst_chars(method[KEY_DOC].strip(), ' | ') + '\n\n') if KEY_PARAMS in method: num_params = len(method[KEY_PARAMS]) for param in method[KEY_PARAMS]: t = yaml_type_to_py_type(param[KEY_TYPE]) f.write('* | ' + param[KEY_NAME] + ': ' + t) if KEY_DEFAULT in param: f.write(' = ' + get_default_or_unset_value_py(param)) if KEY_DOC in param: f.write('\n | ' + indent_and_fix_rst_chars(param[KEY_DOC].strip(), ' | ') + '\n\n') else: f.write('\n') if KEY_EXAMPLES in method: f.write(' | ' + gen_example_links(method[KEY_EXAMPLES]) + '\n\n') f.write('\n') f.write('\n') def generate_documentation(data_classes): # generate constants with open(os.path.join(DOC_DIRECTORY, CATEGORY_CONSTANTS + EXT_RST), 'w') as f: write_cat_label(f, CATEGORY_CONSTANTS) f.write( '*******************\n' + cat_to_title(CATEGORY_CONSTANTS) + '\n' + '*******************\n\n' ) # generate enums first, then constants enums = data_classes[KEY_ENUMS] for enum in enums: enum_name = enum[KEY_NAME] f.write(enum_name + '\n' + '='*len(enum_name) + '\n\n') if KEY_DOC in enum: f.write('\n | ' + indent_and_fix_rst_chars(enum[KEY_DOC].strip(), ' | ') + '\n\n') for value in enum[KEY_VALUES]: f.write('* | **' + value[KEY_NAME] + '** = ' + str(value[KEY_VALUE]) + '\n') if KEY_DOC in value: f.write(' | ' + indent_and_fix_rst_chars(value[KEY_DOC].strip(), ' | ') + '\n\n') f.write('\n') f.write('\n\n') c = 'Constants' f.write(c + '\n' + '='*len(c) + '\n\n') constants = data_classes[KEY_CONSTANTS] for const in constants: const_name = const[KEY_NAME] f.write('* | **' + const_name + '**: ' + yaml_type_to_py_type(const[KEY_TYPE]) + \ ' = ' + str(const[KEY_VALUE]) +'\n') if KEY_DOC in const: f.write(' | ' + indent_and_fix_rst_chars(const[KEY_DOC].strip(), ' | ') + '\n\n') f.write('\n\n') # then generate classes into files by category for cat in CATEGORIES: if cat == CATEGORY_CONSTANTS: continue input_file = cat + EXT_RST with open(os.path.join(DOC_DIRECTORY, input_file), 'w') as f: write_cat_label(f, cat) cat_name = cat_to_title(cat) f.write('*'*len(cat_name) + '\n' + cat_name + '\n' + '*'*len(cat_name) + '\n') for key, value in sorted(data_classes.items()): if key != KEY_CONSTANTS and key != KEY_ENUMS and value[KEY_CATEGORY] == cat: generate_class_documentation(f, key, value) # and generate api.rst file with open(os.path.join(DOC_DIRECTORY, API_RST), 'w') as f: title = 'Python API Reference' f.write( title + '\n' + '='*len(title) + '\n\n' ) f.write( '.. toctree::\n' ' :maxdepth: 2\n' ' :hidden:\n' ' :caption: Contents\n\n' ) for cat in CATEGORIES: f.write(' ' + cat + '\n') f.write('\nThis section contains automatically generated documentation on Python classes, enums, ' 'and constants provided by MCell.\n\n') for cat in CATEGORIES: f.write('- :ref:`api-' + cat + '`\n')
Python
3D
mcellteam/mcell
docs/dynamic_geometry.md
.md
12,643
262
Dynamic Geometry ========================================================================= Overview ------------------------------------------------------------------------- Before we get into how the algorithm works, here is how it is used: Mesh "snapshots" are referenced in a text file similar to how variable rate constant files are handled. The first column contains MDL filenames and the second column contains the time at which the geometry should be used. As an example, imagine we have a file called geometry_snapshots.txt that contained the following: my_geometry0.mdl 0e-6 my_geometry1.mdl 1e-6 my_geometry2.mdl 2e-6 my_geometry3.mdl 3e-6 ... Each MDL listed would contain mesh object definitions (usually one wouldn't add new meshes or remove existing ones, but this is now allowed) where the vertices and elements might be different. You would also need to re-instantiate the existing mesh objects. For example, my_geometry0.mdl might contain the following: Cube POLYGON_LIST { VERTEX_LIST { [ 0.1, 0.1, -0.1 ] ... } ELEMENT_CONNECTIONS { [ 0, 1, 2 ] ... } } INSTANTIATE Scene OBJECT { Cube OBJECT Cube{} } In this example, each subsequent file referenced in geometry_snapshots.txt (e.g. my_geometry1.mdl, my_geometry2.mdl, etc) might have a definition and instantiation of the Cube object. As mentioned before, the actual vertices and elements can be different. Finally, the file containing this list of MDLs and times (geometry_snapshots.txt in this example) would be referenced somewhere in your main MDL using a new keyword called DYNAMIC_GEOMETRY like this: DYNAMIC_GEOMETRY = "geometry_snapshots.txt" Note: For lack of a better term, we will refer to the file assigned to DYNAMIC_GEOMETRY file as the "dynamic geometry file". Do not confuse this with the MDLs that have the actual geometry/meshes and instantiations. The usage is probably best explained in the wiki: https://github.com/mcellteam/mcell/wiki/Using-Dynamic-Geometries Algorithm ------------------------------------------------------------------------- Now, we can move onto how the algorithm actually works: ### Initialization Along with all the other data structures, memory for dynamic geometry events is allocated in init_data_structures (init.c). The scheduler is created in init_dynamic_geometry (init.c). ### Parsing During parse time, we check what text file is assigned to DYNAMIC_GEOMETRY (mcell_add_dynamic_geometry_file in mcell_dyngeom.c). We then process the dynamic geometry file, adding an event to the dynamic_geometry_head (add_dynamic_geometry_events in dyngeom.c) for each line in the DG file. Also, we do a preliminary parse of all the geometry files listed in the DG file (parse_dg in dyngeom_yacc.c). We need to do this to make sure that objects we are counting in/on will exist at some point during the simulation. NOTE: This is different than the regular geometry parsing done in mcell_parse_mdl and uses a different parser. The preliminary parsing is somewhat involved and so is covered more thoroughly in a later section of this document. After the preliminary parsing is done, everything in dynamic_geometry_head is added to the scheduler (end of schedule_dynamic_geometry in init.c). ### Set Up Some Data Structures Create a data structure so we can quickly check if a molecule species can move in or out of any given surface region. (init_species_mesh_transp in dyngeom.c) ### Run Simulation Once the simulation starts, check for a scheduled geometry change every timestep (process_geometry_changes in mcell_run.c). If a geometry change is scheduled, we do the following: - Save all the molecules available in the scheduler (save_all_molecules) - For volume molecules, keep track of enclosing meshes in the order of nesting. (save_volume_molecule) - For surface molecules, keep track of the mesh it is on as well as all regions. (save_surface_molecule) - Save common properties like next uni reaction, scheduling time, birthday, etc. (save_common_molecule_properties). - Side note: Finding what mesh a molecule is inside of is explained in point 2 below. (find_enclosing_meshes) - Save a list of names of all the meshes and regions in fully qualified form prior to trashing them (create_mesh_instantiation_sb). We'll get back to this in a minute. - Now the fun part; destroy geometry, subvolumes, memory helpers, and pretty much the entire simulation (destroy_everything in mcell_redo_geom). We also zero out counts (reset_current_counts), because they'll get repopulated when we count from scratch later. Well, we leave things like molecule and reaction definitions alone, since they're not hurting anyone. - Parse the new geometry and instantiation information. (mcell_parse_mdl in mcell_redo_geom) - Re-initialize the things we just destroyed (init_partitions, init_vertices_walls, init_regions). - Save a list of the *new* mesh names (create_mesh_instantiation_sb) and compare them with the *old* names to see if anything has been added or removed (sym_diff_string_buffers). We will ignore newly added or removed meshes and regions for the purpose of placing molecules this time. New meshes will be tracked during subsequent dynamic geometry events. - Place all the molecules that we previously saved, moving molecules if necessary to keep them in/on the appropriate compartment (place_all_molecules). ### Placement of Volume Molecules To expand on the last point, here's how placement works for volume molecules (insert_volume_molecule_encl_mesh): 1. Find what subvolume the molecule should be in now based on its saved location. (find_subvolume in vol_util.c) 2. Find the current enclosing meshes. (find_enclosing_meshes in dyngeom.c) A. Pick a random vector and scale it so that it's big enough to cross the entire world. B. Ray trace from the current molecule location along the direction of the random vector. C. Start working through all our collisions a. Keep track of how many times we cross each *closed* mesh. If odd number, then we are inside it. If even, then we are outside it. (http://en.wikipedia.org/wiki/Point_in_polygon) b. If we reach the edge of the world (outermost subvolume), return each enclosing mesh name (i.e. the first) we found, assuming there is one. If there isn't one, then we are outside all objects and just return NULL. c. If we ever hit an interior subvolume, then repeat 2.B and 2.C until we hit the edge of the world. 3. Compare where the molecule was (prior to the geometry change) with where it is now relative to the meshes. This also takes into account meshes nested inside other meshes. Ultimately, we want to see if movement is possible from the starting position to the ending position. (compare_molecule_nesting) If the compartment nesting never changed and there were no molecule transparencies, then we could ignore the nesting and simply track the closest enclosing mesh. In fact, this is what was done in an earlier version of the dynamic geometries code. But that is not the case. In fact, meshes can be selectively transparent to a molecule (in-to-out, out-to-in, both, or neither), the transparent properties can change from one dynamic geometry event to the next, and entire meshes/regions can disappear. Now, a little discussion on notation for the sake of being clear and concise. When we say something like A->B->C->null, this means that mesh A is inside mesh B which is inside mesh C. Lastly, C is an outermost mesh. First, find "overlap" if any exists. (check_overlapping_meshes) For example: mesh_names_old: A->B->C->D->null mesh_names_new: C->D->null "A" was the closest enclosing mesh and then "C" became the closest enclosing mesh. That means the molecule moved from "A" to "C". The order could be reversed like this: mesh_names_old: C->D->null mesh_names_new: A->B->C->D->null This means the molecule moved from "C" to "A". We could also have a case with no overlap (aside from null) like this: mesh_names_old: C->D->null mesh_names_new: E->F->null This means the molecule moved from "C" to "E". (check_nonoverlapping_meshes) 4. See if we can legally be where we are at (check_outin_or_inout) 5. If the nesting is the same, just place the molecule where it is. 6. If the nesting is different, we need to move the molecule (place_mol_relative_to_mesh). A. Go through all the walls in the subvolume that is shared with the molecule. B. Find the distance to the closest wall. C. Check neighboring subvolumes to see if there's an even closer wall. D. Find closest wall and put the molecule either slightly in front of or behind it. By default, this is done to the nearest point (DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT = NEAREST_POINT), but it's also possible to just set it to a random point on the nearest triangle (DYNAMIC_GEOMETRY_MOLECULE_PLACEMENT = NEAREST_TRIANGLE). 7. Update subvolume, enable counting, schedule it, and do other book keeping. ### Placement of Surface Molecules Now, here's how placement works for surface molecules (insert_surface_molecule and place_surface_molecule in vol_util.c): 1. Find what subvolume the molecule is now in based on its saved location. 2. Go through every wall in the subvolume. (find_subvolume) A. Make sure the object name and region names match what we saved previously aside for newly-added/removed regions and regions that we are transparent to. (verify_wall_regions_match in grid_util.c) B. If they match, find the closest point on the wall to our molecule's location (closest_interior_point in wall_util.c). C. Of all the walls, keep the best (i.e. the closest) location. 3. Make sure there's not a better/closer location in adjacent subvolumes. 4. Then make sure there's actually a free slot on the wall's surface grid. 5. If not, check neighboring walls. 6. If everything is okay, put it on the grid. 7. Make it countable for reaction output. 8. Add it to the scheduler. Preliminary Parsing Geometry ------------------------------------------------------------------------- Before parsing, we call create_dg_parse which creates a global (BOO!) pointer to a struct called dg_parse, which stores some useful information about the object(s) we are currently parsing, symbol tables, etc. Next, we call init_top_level_objs, which create the aforementioned symbol tables. These are used to store the objects and regions. We also create two top level objects (WORLD_OBJ and WORLD_INSTANCE), add them to object symbol table, and add them to the top of the root_object and root_instance trees. The actual parsing itself begins in parse_dg where we set the root object and root instance (setup_root_obj_inst). NOTE: This is unnecessary the first time through, since it's also done in init_top_level_objs. Then we open the geometry files for parsing by calling yyparse. The first thing we will likely encounter when parsing a geometry file is a polygon_list object (dg_new_polygon_list in dyngeom_parse_extras.c). We prepare the object_name_list. This is necessary in case the object is part of a meta object (this needs tested more thoroughly), such that the fully qualified name is something like Vesicles.Left.Ves1. Then we call dg_start_object_simple (dyngeom_parse_extras.c), which adds the name to the object_name_list to form the fully qualified name and makes the new object (make_new_object). This is where the object name gets added to the DG object symbol table. Next we create an "ALL" region, which every polygon object has (dg_create_region and dg_make_new_region). We make a fully qualified region name of the form "object_name,region_name" and store the name in the DG region symbol table. We may process other regions the user created at this time. When all of this is finished, we call dg_finish_object which basically just pops the name off the object_name_list. The next major thing that the user is likely to do is instantiate the objects. As every object is created we first call dg_start_object. This is very similar to dg_start_object_simple. We add the object name to the object_name_list and store it in the DG object symbol table. Eventually, we will copy the contents of one object into another one using dg_deep_copy_object. For normal cases, this mainly entails copying the regions of the source/original object to the destination/new object (dg_copy_object_regions).
Markdown
3D
jibikbam/CNN-3D-images-Tensorflow
simpleCNN_MRI.py
.py
4,962
111
# A simple CNN to predict certain characteristics of the human subject from MRI images. # 3d convolution is used in each layer. # Reference: https://www.tensorflow.org/get_started/mnist/pros, http://blog.naver.com/kjpark79/220783765651 # Adjust needed for your dataset e.g., max pooling, convolution parameters, training_step, batch size, etc width = 256 height = 256 depth = 40 nLabel = 4 # Start TensorFlow InteractiveSession import input_3Dimage import tensorflow as tf sess = tf.InteractiveSession() # Placeholders (MNIST image:28x28pixels=784, label=10) x = tf.placeholder(tf.float32, shape=[None, width*height*depth]) # [None, 28*28] y_ = tf.placeholder(tf.float32, shape=[None, nLabel]) # [None, 10] ## Weight Initialization # Create lots of weights and biases & Initialize with a small positive number as we will use ReLU def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) ## Convolution and Pooling # Convolution here: stride=1, zero-padded -> output size = input size def conv3d(x, W): return tf.nn.conv3d(x, W, strides=[1, 1, 1, 1, 1], padding='SAME') # conv2d, [1, 1, 1, 1] # Pooling: max pooling over 2x2 blocks def max_pool_2x2(x): # tf.nn.max_pool. ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1] return tf.nn.max_pool3d(x, ksize=[1, 4, 4, 4, 1], strides=[1, 4, 4, 4, 1], padding='SAME') ## First Convolutional Layer # Conv then Max-pooling. 1st layer will have 32 features for each 5x5 patch. (1 feature -> 32 features) W_conv1 = weight_variable([5, 5, 5, 1, 32]) # shape of weight tensor = [5,5,1,32] b_conv1 = bias_variable([32]) # bias vector for each output channel. = [32] # Reshape 'x' to a 4D tensor (2nd dim=image width, 3rd dim=image height, 4th dim=nColorChannel) x_image = tf.reshape(x, [-1,width,height,depth,1]) # [-1,28,28,1] print(x_image.get_shape) # (?, 256, 256, 40, 1) # -> output image: 28x28 x1 # x_image * weight tensor + bias -> apply ReLU -> apply max-pool h_conv1 = tf.nn.relu(conv3d(x_image, W_conv1) + b_conv1) # conv2d, ReLU(x_image * weight + bias) print(h_conv1.get_shape) # (?, 256, 256, 40, 32) # -> output image: 28x28 x32 h_pool1 = max_pool_2x2(h_conv1) # apply max-pool print(h_pool1.get_shape) # (?, 128, 128, 20, 32) # -> output image: 14x14 x32 ## Second Convolutional Layer # Conv then Max-pooling. 2nd layer will have 64 features for each 5x5 patch. (32 features -> 64 features) W_conv2 = weight_variable([5, 5, 5, 32, 64]) # [5, 5, 32, 64] b_conv2 = bias_variable([64]) # [64] h_conv2 = tf.nn.relu(conv3d(h_pool1, W_conv2) + b_conv2) # conv2d, .ReLU(x_image * weight + bias) print(h_conv2.get_shape) # (?, 128, 128, 20, 64) # -> output image: 14x14 x64 h_pool2 = max_pool_2x2(h_conv2) # apply max-pool print(h_pool2.get_shape) # (?, 64, 64, 10, 64) # -> output image: 7x7 x64 ## Densely Connected Layer (or fully-connected layer) # fully-connected layer with 1024 neurons to process on the entire image W_fc1 = weight_variable([16*16*3*64, 1024]) # [7*7*64, 1024] b_fc1 = bias_variable([1024]) # [1024]] h_pool2_flat = tf.reshape(h_pool2, [-1, 16*16*3*64]) # -> output image: [-1, 7*7*64] = 3136 print(h_pool2_flat.get_shape) # (?, 2621440) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # ReLU(h_pool2_flat x weight + bias) print(h_fc1.get_shape) # (?, 1024) # -> output: 1024 ## Dropout (to reduce overfitting; useful when training very large neural network) # We will turn on dropout during training & turn off during testing keep_prob = tf.placeholder(tf.float32) h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) print(h_fc1_drop.get_shape) # -> output: 1024 ## Readout Layer W_fc2 = weight_variable([1024, nLabel]) # [1024, 10] b_fc2 = bias_variable([nLabel]) # [10] y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2 print(y_conv.get_shape) # -> output: 10 ## Train and Evaluate the Model # set up for optimization (optimizer:ADAM) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) train_step = tf.train.AdamOptimizer(1e-3).minimize(cross_entropy) # 1e-4 correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.global_variables_initializer()) # Include keep_prob in feed_dict to control dropout rate. for i in range(100): batch = get_data_MRI(sess,'train',20) # Logging every 100th iteration in the training process. if i%5 == 0: train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0}) print("step %d, training accuracy %g"%(i, train_accuracy)) train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5}) # Evaulate our accuracy on the test data testset = get_data_MRI(sess,'test',30) print("test accuracy %g"%accuracy.eval(feed_dict={x: testset[0], y_: teseset[1], keep_prob: 1.0}))
Python
3D
jibikbam/CNN-3D-images-Tensorflow
input_3Dimage.py
.py
2,281
75
# A script to load images and make batch. # Dependency: 'nibabel' to load MRI (NIFTI) images # Reference: http://blog.naver.com/kjpark79/220783765651 import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import random import nibabel as nib FLAGS = tf.app.flags.FLAGS FLAGS.width = 256 FLAGS.height = 256 FLAGS.depth = 40 # 3 batch_index = 0 filenames = [] # user selection FLAGS.data_dir = '/home/ikbeom/Desktop/DL/MNIST_simpleCNN/data' FLAGS.num_class = 4 def get_filenames(data_set): i global filenames labels = [] with open(FLAGS.data_dir + '/labels.txt') as f: for line in f: inner_list = [elt.strip() for elt in line.split(',')] labels += inner_list for i, label in enumerate(labels): list = os.listdir(FLAGS.data_dir + '/' + data_set + '/' + label) for filename in list: filenames.append([label + '/' + filename, i]) random.shuffle(filenames) def get_data_MRI(sess, data_set, batch_size): global batch_index, filenames if len(filenames) == 0: get_filenames(data_set) max = len(filenames) begin = batch_index end = batch_index + batch_size if end >= max: end = max batch_index = 0 x_data = np.array([], np.float32) y_data = np.zeros((batch_size, FLAGS.num_class)) # zero-filled list for 'one hot encoding' index = 0 for i in range(begin, end): imagePath = FLAGS.data_dir + '/' + data_set + '/' + filenames[i][0] FA_org = nib.load(imagePath) FA_data = FA_org.get_data() # 256x256x40; numpy.ndarray # TensorShape([Dimension(256), Dimension(256), Dimension(40)]) resized_image = tf.image.resize_images(images=FA_data, size=(FLAGS.width,FLAGS.height), method=1) image = sess.run(resized_image) # (256,256,40) x_data = np.append(x_data, np.asarray(image, dtype='float32')) # (image.data, dtype='float32') y_data[index][filenames[i][1]] = 1 # assign 1 to corresponding column (one hot encoding) index += 1 batch_index += batch_size # update index for the next batch x_data_ = x_data.reshape(batch_size, FLAGS.height * FLAGS.width * FLAGS.depth) return x_data_, y_data
Python
3D
PattanaikL/ts_gen
use_trained_model.ipynb
.ipynb
27,888
460
{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "### This notebook walks you through how to use the pretrained model to generate your own transition state guesses. If using your own model and data, replace the model and data paths with your own" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Import the necessary packages" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "from rdkit import Chem, Geometry\n", "from rdkit.Chem.Draw import IPythonConsole \n", "\n", "import tensorflow as tf\n", "from model.G2C import G2C\n", "\n", "import numpy as np\n", "import py3Dmol" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Read in the test data with rdkit. You can optionally change this to use your own file type (instead of sdf), as long as rdkit can read in the data without sanitization or hydrogen removal. Note that the reactants and prodcuts defined in the sdf **MUST** preserve atom ordering between them! Define the saved model path" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "model_path = 'log/2layers_256hs_3its/best_model.ckpt'\n", "reactant_file = 'data/test_reactants.sdf'\n", "product_file = 'data/test_products.sdf'\n", "\n", "test_data = [Chem.ForwardSDMolSupplier(reactant_file, removeHs=False, sanitize=False),\n", " Chem.ForwardSDMolSupplier(product_file, removeHs=False, sanitize=False)]\n", "test_data = [(x,y) for (x,y) in zip(test_data[0], test_data[1]) if (x,y)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Batch preparation code. You can use larger batch sizes if you have many predictions to speed up the predictions" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "BATCH_SIZE = 1\n", "MAX_SIZE = max([x.GetNumAtoms() for x,y in test_data])\n", "elements = \"HCNO\"; num_elements = len(elements)\n", "\n", "def prepare_batch(batch_mols):\n", "\n", " # Initialization\n", " size = len(batch_mols)\n", " V = np.zeros((size, MAX_SIZE, num_elements+1), dtype=np.float32)\n", " E = np.zeros((size, MAX_SIZE, MAX_SIZE, 3), dtype=np.float32)\n", " sizes = np.zeros(size, dtype=np.int32)\n", " coordinates = np.zeros((size, MAX_SIZE, 3), dtype=np.float32)\n", "\n", " # Build atom features\n", " for bx in range(size):\n", " reactant, product = batch_mols[bx]\n", " N_atoms = reactant.GetNumAtoms()\n", " sizes[bx] = int(N_atoms)\n", "\n", " # Topological distances matrix\n", " MAX_D = 10.\n", " D = (Chem.GetDistanceMatrix(reactant) + Chem.GetDistanceMatrix(product)) / 2\n", " D[D > MAX_D] = 10.\n", "\n", " D_3D_rbf = np.exp(-((Chem.Get3DDistanceMatrix(reactant) + Chem.Get3DDistanceMatrix(product)) / 2)) # squared\n", "\n", " for i in range(N_atoms):\n", " # Edge features\n", " for j in range(N_atoms):\n", " E[bx, i, j, 2] = D_3D_rbf[i][j]\n", " if D[i][j] == 1.: # if stays bonded\n", " if reactant.GetBondBetweenAtoms(i, j).GetIsAromatic():\n", " E[bx, i, j, 0] = 1.\n", " E[bx, i, j, 1] = 1.\n", "\n", " # Recover coordinates\n", " # for k, mol_typ in enumerate([reactant, ts, product]):\n", " pos = reactant.GetConformer().GetAtomPosition(i)\n", " np.asarray([pos.x, pos.y, pos.z])\n", " coordinates[bx, i, :] = np.asarray([pos.x, pos.y, pos.z])\n", "\n", " # Node features\n", " atom = reactant.GetAtomWithIdx(i)\n", " e_ix = elements.index(atom.GetSymbol())\n", " V[bx, i, e_ix] = 1.\n", " V[bx, i, num_elements] = atom.GetAtomicNum() / 10.\n", "\n", " batch_dict = {\n", " \"nodes\": V,\n", " \"edges\": E,\n", " \"sizes\": sizes,\n", " \"coordinates\": coordinates\n", " }\n", " return batch_dict, batch_mols\n", "\n", "\n", "def sample_batch():\n", " batches = (len(test_data) - 1) // BATCH_SIZE + 1\n", " for i in range(batches):\n", " batch_mols = test_data[i*BATCH_SIZE:(i+1)*BATCH_SIZE]\n", " yield prepare_batch(batch_mols)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Initialize the model. The hyperparameters should match those of the previously trained model (pls ignore all the deprecation warnings :) )" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING: Logging before flag parsing goes to stderr.\n", "W1007 09:57:50.280781 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:29: The name tf.variable_scope is deprecated. Please use tf.compat.v1.variable_scope instead.\n", "\n", "W1007 09:57:50.304795 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:33: The name tf.placeholder is deprecated. Please use tf.compat.v1.placeholder instead.\n", "\n", "W1007 09:57:50.343178 140199825712512 deprecation.py:323] From model/GNN.py:87: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "Use keras.layers.dense instead.\n", "W1007 09:57:50.354985 140199825712512 deprecation.py:506] From /home/lagnajit/anaconda3/envs/ts_gen/lib/python2.7/site-packages/tensorflow/python/ops/init_ops.py:1251: calling __init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "Call initializer instance with the dtype argument instead of passing it to the constructor\n", "W1007 09:57:50.886174 140199825712512 deprecation_wrapper.py:119] From model/GNN.py:28: The name tf.summary.image is deprecated. Please use tf.compat.v1.summary.image instead.\n", "\n", "W1007 09:57:51.931003 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:84: The name tf.get_variable is deprecated. Please use tf.compat.v1.get_variable instead.\n", "\n", "W1007 09:57:51.958873 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:102: The name tf.add_check_numerics_ops is deprecated. Please use tf.compat.v1.add_check_numerics_ops instead.\n", "\n", "W1007 09:57:52.260715 140199825712512 deprecation.py:323] From model/G2C.py:151: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "Use `tf.cast` instead.\n", "W1007 09:57:52.263387 140199825712512 deprecation.py:506] From model/G2C.py:153: calling reduce_sum_v1 (from tensorflow.python.ops.math_ops) with keep_dims is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "keep_dims is deprecated, use keepdims instead\n", "W1007 09:57:52.293221 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:183: The name tf.random_normal is deprecated. Please use tf.random.normal instead.\n", "\n", "W1007 09:57:52.556955 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:256: The name tf.debugging.is_finite is deprecated. Please use tf.math.is_finite instead.\n", "\n", "W1007 09:57:52.580108 140199825712512 deprecation.py:323] From model/G2C.py:260: Print (from tensorflow.python.ops.logging_ops) is deprecated and will be removed after 2018-08-20.\n", "Instructions for updating:\n", "Use tf.print instead of tf.Print. Note that tf.print returns a no-output operator that directly prints the output. Outside of defuns or eager mode, this operator will not be executed unless it is directly specified in session.run or used as a control dependency for other operators. This is only a concern in graph mode. Below is an example of how to ensure tf.print executes in graph mode:\n", "```python\n", " sess = tf.compat.v1.Session()\n", " with sess.as_default():\n", " tensor = tf.range(10)\n", " print_op = tf.print(tensor)\n", " with tf.control_dependencies([print_op]):\n", " out = tf.add(tensor, tensor)\n", " sess.run(out)\n", " ```\n", "Additionally, to use tf.print in python 2.7, users must make sure to import\n", "the following:\n", "\n", " `from __future__ import print_function`\n", "\n", "W1007 09:57:52.654720 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:120: The name tf.summary.scalar is deprecated. Please use tf.compat.v1.summary.scalar instead.\n", "\n", "W1007 09:57:52.679590 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:128: The name tf.summary.histogram is deprecated. Please use tf.compat.v1.summary.histogram instead.\n", "\n", "W1007 09:57:52.695075 140199825712512 deprecation_wrapper.py:119] From model/G2C.py:137: The name tf.train.AdamOptimizer is deprecated. Please use tf.compat.v1.train.AdamOptimizer instead.\n", "\n", "W1007 09:57:52.986613 140199825712512 deprecation.py:323] From /home/lagnajit/anaconda3/envs/ts_gen/lib/python2.7/site-packages/tensorflow/python/ops/math_grad.py:1205: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "Use tf.where in 2.0, which has the same broadcast rule as np.where\n" ] } ], "source": [ "model = G2C(\n", " max_size=MAX_SIZE, node_features=num_elements+1, edge_features=3, layers=2, hidden_size=256, iterations=3\n", ")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Load the trained model and predict transition state geometries!" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "W1007 09:57:57.568586 140199825712512 deprecation.py:323] From /home/lagnajit/anaconda3/envs/ts_gen/lib/python2.7/site-packages/tensorflow/python/training/saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n", "Instructions for updating:\n", "Use standard file APIs to check for files with this prefix.\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "Model loading...\n", "Model restored\n" ] } ], "source": [ "# Launch session\n", "config = tf.ConfigProto(\n", " allow_soft_placement=True,\n", " log_device_placement=False\n", ")\n", "with tf.Session(config=config) as sess:\n", " \n", " # Initialization\n", " print(\"Model loading...\")\n", " saver = tf.train.Saver()\n", " saver.restore(sess, model_path)\n", " print(\"Model restored\")\n", " \n", " # Generator for test data\n", " get_test_data = sample_batch()\n", "\n", " X = np.empty([len(test_data), MAX_SIZE, 3])\n", " \n", " for step, data in enumerate(get_test_data):\n", "\n", " batch_dict_test, batch_mols_test = data\n", " feed_dict = {\n", " model.placeholders[key]: batch_dict_test[key] for key in batch_dict_test\n", " }\n", " X[step*BATCH_SIZE:(step+1)*BATCH_SIZE, :, :] = sess.run([model.tensors[\"X\"]], feed_dict=feed_dict)[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Convert geometries into rdkit mol objects and save the geometries as an sdf" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [], "source": [ "ts_mols = []\n", "for bx in range(X.shape[0]):\n", " \n", " # Make copy of reactant\n", " mol_target = test_data[bx][0]\n", " mol = Chem.Mol(mol_target)\n", "\n", " for i in range(mol.GetNumAtoms()):\n", " x = X[bx, i, :].tolist()\n", " mol.GetConformer().SetAtomPosition(\n", " i, Geometry.Point3D(x[0], x[1], x[2])\n", " )\n", " ts_mols.append(mol)\n", "\n", "\n", "model_ts_file = 'data/model_ts.sdf'\n", "ts_writer = Chem.SDWriter(model_ts_file)\n", "for i in range(len(ts_mols)):\n", " ts_writer.write(ts_mols[i])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Visualize the results. Change n to see different combinations of reactants, transition states, and products. Note that, for the TS, rdkit will add bonds based on the reactant. We'll clean this to only include common bonds between reactants and products" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def clean_ts(mols):\n", " \n", " r_mol, ts_mol, p_mol = mols\n", " r_bonds = [(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()) for bond in r_mol.GetBonds()]\n", " r_bonds = [tuple(sorted(b)) for b in r_bonds]\n", " p_bonds = [(bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()) for bond in p_mol.GetBonds()]\n", " p_bonds = [tuple(sorted(b)) for b in p_bonds]\n", " common_bonds = list(set(r_bonds) & set(p_bonds))\n", " \n", " emol = Chem.EditableMol(ts_mol)\n", " for bond in ts_mol.GetBonds():\n", " bond_idxs = tuple(sorted((bond.GetBeginAtomIdx(), bond.GetEndAtomIdx())))\n", " if bond_idxs not in common_bonds:\n", " emol.RemoveBond(bond_idxs[0], bond_idxs[1])\n", " emol.AddBond(bond_idxs[0], bond_idxs[1])\n", " return r_mol, emol.GetMol(), p_mol\n", "\n", "\n", "def show_mol(mol, view, grid):\n", " mb = Chem.MolToMolBlock(mol)\n", " view.removeAllModels(viewer=grid)\n", " view.addModel(mb,'sdf', viewer=grid)\n", " view.setStyle({'model':0},{'stick': {}}, viewer=grid)\n", " view.zoomTo(viewer=grid)\n", " return view" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "application/3dmoljs_load.v0": "<div id=\"3dmolviewer_160207913664\" style=\"position: relative; width: 960px; height: 500px\">\n <p id=\"3dmolwarning_160207913664\" style=\"background-color:#ffcccc;color:black\">You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension: <br>\n <tt>jupyter labextension install jupyterlab_3dmol</tt></p>\n </div>\n<script>\n\nvar loadScriptAsync = function(uri){\n return new Promise((resolve, reject) => {\n var tag = document.createElement('script');\n tag.src = uri;\n tag.async = true;\n tag.onload = () => {\n resolve();\n };\n var firstScriptTag = document.getElementsByTagName('script')[0];\n firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n});\n};\n\nif(typeof $3Dmolpromise === 'undefined') {\n$3Dmolpromise = null;\n $3Dmolpromise = loadScriptAsync('https://3dmol.csb.pitt.edu/build/3Dmol.js');\n}\n\nvar viewer_160207913664 = null;\nvar warn = document.getElementById(\"3dmolwarning_160207913664\");\nif(warn) {\n warn.parentNode.removeChild(warn);\n}\n$3Dmolpromise.then(function() {\nvar viewergrid_160207913664 = null;\nviewergrid_160207913664 = $3Dmol.createViewerGrid($(\"#3dmolviewer_160207913664\"),{rows: 1, cols: 3, control_all: false},{backgroundColor:\"white\"});\nviewer_160207913664 = viewergrid_160207913664[0][0];\n\tviewergrid_160207913664[0][0].removeAllModels();\n\tviewergrid_160207913664[0][0].addModel(\"[C:1]([O:2][C:3]([C:4](=[O:5])[H:11])([H:9])[H:10])([H:6])([H:7])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 0 0 0 0 0 0999 V2000\\n -1.3284 0.7074 0.2890 C 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.9007 -0.4391 -0.4086 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3528 -0.8952 0.0115 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.4927 -0.0534 -0.5283 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 2.6074 -0.0833 -0.0898 O 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.4378 0.5000 1.3607 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.6317 1.5467 0.1666 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -2.2956 0.9940 -0.1198 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4822 -1.9058 -0.3877 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4361 -0.9551 1.1046 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.2231 0.5837 -1.3982 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 2 1 1 0\\n 3 10 1 0\\n 4 5 2 0\\n 4 3 1 0\\n 7 1 1 0\\n 8 1 1 0\\n 9 3 1 0\\n 11 4 1 0\\nM END\\n\",\"sdf\");\n\tviewergrid_160207913664[0][0].setStyle({\"model\": 0},{\"stick\": {}});\n\tviewergrid_160207913664[0][0].zoomTo();\n\tviewergrid_160207913664[0][1].removeAllModels();\n\tviewergrid_160207913664[0][1].addModel(\"[C:1]([O:2][C:3]([C:4](=[O:5])[H:11])([H:9])[H:10])([H:6])([H:7])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 0 0 0 0 0 0999 V2000\\n -0.5259 1.0619 -0.2321 C 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.9769 -0.2074 0.8580 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3142 -0.7604 0.6965 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.6649 -0.2509 -0.7434 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.8830 -0.0655 -1.0728 O 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.0563 1.7456 0.4723 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.4645 0.0505 0.1715 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.2156 1.4714 -0.8689 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.2872 -1.8603 0.8293 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.9988 -0.2997 1.4230 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.0911 -0.8851 -1.5334 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 3 10 1 0\\n 4 5 2 0\\n 4 3 1 0\\n 8 1 1 0\\n 9 3 1 0\\n 11 4 1 0\\n 1 2 0 0\\n 1 7 0 0\\nM END\\n\",\"sdf\");\n\tviewergrid_160207913664[0][1].setStyle({\"model\": 0},{\"stick\": {}});\n\tviewergrid_160207913664[0][1].zoomTo();\n\tviewergrid_160207913664[0][2].removeAllModels();\n\tviewergrid_160207913664[0][2].addModel(\"[C+:1]([C@:4]([C:3]([O:2][H:7])([H:9])[H:10])([O-:5])[H:11])([H:6])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 1 0 0 0 0 0999 V2000\\n -0.6059 0.7528 0.3789 C 0 0 0 0 0 3 0 0 0 0 0 0\\n -1.0821 -0.5691 -0.2495 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3733 -1.0663 -0.1912 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.9039 0.4200 0.0062 C 0 0 2 0 0 0 0 0 0 0 0 0\\n 1.8239 0.6494 0.8561 O 0 0 0 0 0 1 0 0 0 0 0 0\\n -0.8044 0.6368 1.4419 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.3151 -0.4054 -1.1713 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.1576 1.5791 -0.0683 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.5838 -1.6582 -1.0815 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4257 -1.6489 0.7257 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.0368 0.8210 -1.0435 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 3 4 1 0\\n 3 10 1 0\\n 4 11 1 6\\n 4 1 1 0\\n 4 5 1 0\\n 7 2 1 0\\n 8 1 1 0\\n 9 3 1 0\\nM RAD 2 1 2 5 2\\nM END\\n\",\"sdf\");\n\tviewergrid_160207913664[0][2].setStyle({\"model\": 0},{\"stick\": {}});\n\tviewergrid_160207913664[0][2].zoomTo();\n\tviewergrid_160207913664[0][0].render();\n\tviewergrid_160207913664[0][1].render();\n\tviewergrid_160207913664[0][2].render();\nviewergrid_160207913664[0][2].render();\nviewergrid_160207913664[0][1].render();\nviewergrid_160207913664[0][0].render();\n});\n</script>", "text/html": [ "<div id=\"3dmolviewer_160207913664\" style=\"position: relative; width: 960px; height: 500px\">\n", " <p id=\"3dmolwarning_160207913664\" style=\"background-color:#ffcccc;color:black\">You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension: <br>\n", " <tt>jupyter labextension install jupyterlab_3dmol</tt></p>\n", " </div>\n", "<script>\n", "\n", "var loadScriptAsync = function(uri){\n", " return new Promise((resolve, reject) => {\n", " var tag = document.createElement('script');\n", " tag.src = uri;\n", " tag.async = true;\n", " tag.onload = () => {\n", " resolve();\n", " };\n", " var firstScriptTag = document.getElementsByTagName('script')[0];\n", " firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);\n", "});\n", "};\n", "\n", "if(typeof $3Dmolpromise === 'undefined') {\n", "$3Dmolpromise = null;\n", " $3Dmolpromise = loadScriptAsync('https://3dmol.csb.pitt.edu/build/3Dmol.js');\n", "}\n", "\n", "var viewer_160207913664 = null;\n", "var warn = document.getElementById(\"3dmolwarning_160207913664\");\n", "if(warn) {\n", " warn.parentNode.removeChild(warn);\n", "}\n", "$3Dmolpromise.then(function() {\n", "var viewergrid_160207913664 = null;\n", "viewergrid_160207913664 = $3Dmol.createViewerGrid($(\"#3dmolviewer_160207913664\"),{rows: 1, cols: 3, control_all: false},{backgroundColor:\"white\"});\n", "viewer_160207913664 = viewergrid_160207913664[0][0];\n", "\tviewergrid_160207913664[0][0].removeAllModels();\n", "\tviewergrid_160207913664[0][0].addModel(\"[C:1]([O:2][C:3]([C:4](=[O:5])[H:11])([H:9])[H:10])([H:6])([H:7])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 0 0 0 0 0 0999 V2000\\n -1.3284 0.7074 0.2890 C 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.9007 -0.4391 -0.4086 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3528 -0.8952 0.0115 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.4927 -0.0534 -0.5283 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 2.6074 -0.0833 -0.0898 O 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.4378 0.5000 1.3607 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.6317 1.5467 0.1666 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -2.2956 0.9940 -0.1198 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4822 -1.9058 -0.3877 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4361 -0.9551 1.1046 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.2231 0.5837 -1.3982 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 2 1 1 0\\n 3 10 1 0\\n 4 5 2 0\\n 4 3 1 0\\n 7 1 1 0\\n 8 1 1 0\\n 9 3 1 0\\n 11 4 1 0\\nM END\\n\",\"sdf\");\n", "\tviewergrid_160207913664[0][0].setStyle({\"model\": 0},{\"stick\": {}});\n", "\tviewergrid_160207913664[0][0].zoomTo();\n", "\tviewergrid_160207913664[0][1].removeAllModels();\n", "\tviewergrid_160207913664[0][1].addModel(\"[C:1]([O:2][C:3]([C:4](=[O:5])[H:11])([H:9])[H:10])([H:6])([H:7])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 0 0 0 0 0 0999 V2000\\n -0.5259 1.0619 -0.2321 C 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.9769 -0.2074 0.8580 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3142 -0.7604 0.6965 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.6649 -0.2509 -0.7434 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.8830 -0.0655 -1.0728 O 0 0 0 0 0 0 0 0 0 0 0 0\\n -0.0563 1.7456 0.4723 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.4645 0.0505 0.1715 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.2156 1.4714 -0.8689 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.2872 -1.8603 0.8293 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.9988 -0.2997 1.4230 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.0911 -0.8851 -1.5334 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 3 10 1 0\\n 4 5 2 0\\n 4 3 1 0\\n 8 1 1 0\\n 9 3 1 0\\n 11 4 1 0\\n 1 2 0 0\\n 1 7 0 0\\nM END\\n\",\"sdf\");\n", "\tviewergrid_160207913664[0][1].setStyle({\"model\": 0},{\"stick\": {}});\n", "\tviewergrid_160207913664[0][1].zoomTo();\n", "\tviewergrid_160207913664[0][2].removeAllModels();\n", "\tviewergrid_160207913664[0][2].addModel(\"[C+:1]([C@:4]([C:3]([O:2][H:7])([H:9])[H:10])([O-:5])[H:11])([H:6])[H:8]\\n RDKit 3D\\n\\n 11 10 0 0 1 0 0 0 0 0999 V2000\\n -0.6059 0.7528 0.3789 C 0 0 0 0 0 3 0 0 0 0 0 0\\n -1.0821 -0.5691 -0.2495 O 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.3733 -1.0663 -0.1912 C 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.9039 0.4200 0.0062 C 0 0 2 0 0 0 0 0 0 0 0 0\\n 1.8239 0.6494 0.8561 O 0 0 0 0 0 1 0 0 0 0 0 0\\n -0.8044 0.6368 1.4419 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.3151 -0.4054 -1.1713 H 0 0 0 0 0 0 0 0 0 0 0 0\\n -1.1576 1.5791 -0.0683 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.5838 -1.6582 -1.0815 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 0.4257 -1.6489 0.7257 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1.0368 0.8210 -1.0435 H 0 0 0 0 0 0 0 0 0 0 0 0\\n 1 6 1 0\\n 2 3 1 0\\n 3 4 1 0\\n 3 10 1 0\\n 4 11 1 6\\n 4 1 1 0\\n 4 5 1 0\\n 7 2 1 0\\n 8 1 1 0\\n 9 3 1 0\\nM RAD 2 1 2 5 2\\nM END\\n\",\"sdf\");\n", "\tviewergrid_160207913664[0][2].setStyle({\"model\": 0},{\"stick\": {}});\n", "\tviewergrid_160207913664[0][2].zoomTo();\n", "\tviewergrid_160207913664[0][0].render();\n", "\tviewergrid_160207913664[0][1].render();\n", "\tviewergrid_160207913664[0][2].render();\n", "viewergrid_160207913664[0][2].render();\n", "viewergrid_160207913664[0][1].render();\n", "viewergrid_160207913664[0][0].render();\n", "});\n", "</script>" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "text/plain": [ "<py3Dmol.view at 0x7f828136f2d0>" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n=1\n", "mols = [test_data[n][0], ts_mols[n], test_data[n][1]]\n", "view_mols = clean_ts(mols)\n", "\n", "view = py3Dmol.view(width=960, height=500, linked=False, viewergrid=(1,3))\n", "for i in range(3):\n", " show_mol(view_mols[i], view, grid=(0, i))\n", "view.render()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.16" } }, "nbformat": 4, "nbformat_minor": 2 }
Unknown
3D
PattanaikL/ts_gen
train.py
.py
11,168
317
from __future__ import print_function import os, sys, time, random import tensorflow as tf from tensorflow.python.client import timeline import numpy as np sys.path.insert(0, "model/") from util import render_pymol from G2C import G2C # rdkit from rdkit import Chem, Geometry from optparse import OptionParser parser = OptionParser() parser.add_option("--restore", dest="restore", default=None) parser.add_option("--layers", dest="layers", default=2) parser.add_option("--hidden_size", dest="hidden_size", default=128) parser.add_option("--iterations", dest="iterations", default=3) parser.add_option("--epochs", dest="epochs", default=200) parser.add_option("--batch_size", dest="batch_size", default=8) parser.add_option("--gpu", dest="gpu", default=0) parser.add_option("--r_file", dest="r_file", default=None) parser.add_option("--p_file", dest="p_file", default=None) parser.add_option("--ts_file", dest="ts_file", default=None) args, _ = parser.parse_args() layers = int(args.layers) hidden_size = int(args.hidden_size) iterations = int(args.iterations) gpu = str(args.gpu) os.environ["CUDA_VISIBLE_DEVICES"] = gpu reactantFile = str(args.r_file) tsFile = str(args.p_file) productFile = str(args.ts_file) QUEUE = True BATCH_SIZE = int(args.batch_size) EPOCHS = int(args.epochs) best_val_loss = 9e99 # Load dataset print("Loading datset") start = time.time() data = [Chem.SDMolSupplier(reactantFile, removeHs=False, sanitize=False), Chem.SDMolSupplier(tsFile, removeHs=False, sanitize=False), Chem.SDMolSupplier(productFile, removeHs=False, sanitize=False)] data = [(x,y,z) for (x,y,z) in zip(data[0],data[1],data[2]) if (x,y,z)] elapsed = time.time() - start print(" ... loaded {} molecules in {:.2f}s".format(len(data), elapsed)) # Dataset specific dimensions elements = "HCNO" num_elements = len(elements) max_size = max([x.GetNumAtoms() for x,y,z in data]) print(max_size) # Splitting N_data = len(data) idx = np.arange(N_data) np.random.shuffle(idx) idx = idx.tolist() N_test = int(round(N_data / 10)) N_valid = N_test N_train = N_data - N_valid - N_test data_test = [data[i] for i in idx[:N_test]] data_valid = [data[i] for i in idx[N_test:N_test + N_valid]] data_train = [data[i] for i in idx[N_test + N_valid:]] # Build basepath for experiment base_folder = time.strftime("log/%y%b%d_%I%M%p/", time.localtime()) if not os.path.exists(base_folder): os.makedirs(base_folder) train_ts_file = base_folder + 'train_ts.sdf' train_reactant_file = base_folder + 'train_reactants.sdf' train_products_file = base_folder + 'train_products.sdf' train_ts_writer = Chem.SDWriter(train_ts_file) train_reactant_writer = Chem.SDWriter(train_reactant_file) train_product_writer = Chem.SDWriter(train_products_file) for i in range(len(data_train)): train_ts_writer.write(data_train[i][0]) train_reactant_writer.write(data_train[i][1]) train_product_writer.write(data_train[i][2]) def prepare_batch(batch_mols): # Initialization size = len(batch_mols) V = np.zeros((size, max_size, num_elements + 1), dtype=np.float32) E = np.zeros((size, max_size, max_size, 3), dtype=np.float32) sizes = np.zeros(size, dtype=np.int32) coordinates = np.zeros((size, max_size, 3), dtype=np.float32) # Build atom features for bx in range(size): reactant, ts, product = batch_mols[bx] N_atoms = reactant.GetNumAtoms() sizes[bx] = int(N_atoms) # Topological distances matrix MAX_D = 10. D = (Chem.GetDistanceMatrix(reactant) + Chem.GetDistanceMatrix(product)) / 2 D[D > MAX_D] = 10. D_3D_rbf = np.exp(-((Chem.Get3DDistanceMatrix(reactant) + Chem.Get3DDistanceMatrix(product)) / 2)) # squared for i in range(N_atoms): # Edge features for j in range(N_atoms): E[bx, i, j, 2] = D_3D_rbf[i][j] if D[i][j] == 1.: # if stays bonded if reactant.GetBondBetweenAtoms(i, j).GetIsAromatic(): E[bx, i, j, 0] = 1. E[bx, i, j, 1] = 1. # Recover coordinates; adapted for all # for k, mol_typ in enumerate([reactant, ts, product]): pos = ts.GetConformer().GetAtomPosition(i) np.asarray([pos.x, pos.y, pos.z]) coordinates[bx, i, :] = np.asarray([pos.x, pos.y, pos.z]) # Node features atom = reactant.GetAtomWithIdx(i) e_ix = elements.index(atom.GetSymbol()) V[bx, i, e_ix] = 1. V[bx, i, num_elements] = atom.GetAtomicNum() / 10. # V[bx, i, num_elements + 1] = atom.GetExplicitValence() / 10. # print(np.sum(np.square(V)),np.sum(np.square(E)), sizes) batch_dict = { "nodes": tf.constant(V), "edges": tf.constant(E), "sizes": tf.constant(sizes), "coordinates": tf.constant(coordinates) } return batch_dict ########################################################################################## with tf.variable_scope("Dataset"): dtypes = [tf.float32, tf.float32, tf.int32, tf.float32] names = ['nodes', 'edges', 'sizes', 'coordinates'] shapes = [[BATCH_SIZE, max_size, num_elements + 1], [BATCH_SIZE, max_size, max_size, 3], [BATCH_SIZE], [BATCH_SIZE, max_size, 3]] number_of_threads_train_n = 3 ds_train = tf.data.Dataset.from_tensor_slices(prepare_batch(data_train)).cache().batch(BATCH_SIZE).prefetch(buffer_size=tf.data.experimental.AUTOTUNE) ds_valid = tf.data.Dataset.from_tensor_slices(prepare_batch(data_valid)).cache().batch(BATCH_SIZE).prefetch(buffer_size=tf.data.experimental.AUTOTUNE) iterator = tf.data.Iterator.from_structure(ds_train.output_types, ds_train.output_shapes) next_element = iterator.get_next() training_init_op = iterator.make_initializer(ds_train) validation_init_op = iterator.make_initializer(ds_valid) ########################################################################################## # Build model print("Building model") start = time.time() dgnn = G2C( max_size=max_size, node_features=num_elements + 1, edge_features=3, layers=layers, hidden_size=hidden_size, iterations=iterations, input_data=next_element ) elapsed = time.time() - start print(" ... model built in {:.2f}s".format(elapsed)) total_parameters = 0 for variable in tf.trainable_variables(): shape = variable.get_shape() variable_parameters = 1 for dim in shape: variable_parameters *= dim.value total_parameters += variable_parameters print('Total trainable variables: {}'.format(total_parameters)) # Launch session config = tf.ConfigProto( allow_soft_placement=True, log_device_placement=False, ) config.gpu_options.allow_growth = True with tf.Session(config=config) as sess: # Initialization print("Initializing") start = time.time() init = tf.global_variables_initializer() sess.run(init) elapsed = time.time() - start print(" ...init in " + str(elapsed) + "s\n") # Build batch summaries and TensorBoard writer summary_op = tf.summary.merge_all() print("Setting up saver") start = time.time() summary_writer = tf.summary.FileWriter(base_folder, sess.graph) # Variable saving saver = tf.train.Saver() if args.restore is not None: saver.restore(sess, args.restore) elapsed = time.time() - start print(" set up in " + str(elapsed) + " s\n") counter = 0 for epoch in range(EPOCHS): sess.run(training_init_op) batches_trained = 0 epoch_start = time.time() try: while True: batch_start = time.time() _, _, summ = sess.run( [dgnn.train_op, dgnn.debug_op, summary_op]) summary_writer.add_summary(summ, counter) batches_trained += 1 counter += 1 print('Training: ', batches_trained, time.time()-batch_start) # if batches_trained % 10 == 0: # print(batches_trained) except tf.errors.OutOfRangeError as e: pass sess.run(validation_init_op) X = np.empty([len(data_valid), max_size, 3]) valid_loss_all = np.empty([len(data_valid), max_size, max_size]) D_mask = np.empty([len(data_valid), max_size, max_size]) batches_validated = 0 try: while True: batch_start = time.time() _, X[batches_validated * BATCH_SIZE:(batches_validated + 1) * BATCH_SIZE, :, :], \ valid_loss_all[batches_validated * BATCH_SIZE:(batches_validated + 1) * BATCH_SIZE, :, :], \ D_mask[batches_validated * BATCH_SIZE:(batches_validated + 1) * BATCH_SIZE, :, :] = sess.run( [dgnn.debug_op, dgnn.tensors["X"], dgnn.loss_distance_all, dgnn.masks["D"]]) batches_validated += 1 print('Validation: ', batches_validated, time.time()-batch_start) except tf.errors.OutOfRangeError as e: pass other_calcs_start = time.time() losses = [np.sum(valid_loss_all[i] * D_mask[i]) / np.sum(D_mask[i]) for i in range(X.shape[0])] val_loss = np.mean(np.asarray(losses)) # Make copy of molecule (early checks) if epoch < 5: bx = 0 mol_target = data_valid[bx][1] # transition state geom mol = Chem.Mol(mol_target) for i in range(mol.GetNumAtoms()): x = X[bx, i, :].tolist() mol.GetConformer().SetAtomPosition( i, Geometry.Point3D(x[0], x[1], x[2]) ) render_pymol(mol, base_folder + "step{}_model.png".format(epoch), width=600, height=400) render_pymol(mol_target, base_folder + "step{}_target.png".format(epoch), width=600, height=400) # save_path = saver.save(sess, base_folder + "step{}_model.ckpt".format(epoch)) if val_loss < best_val_loss: best_val_loss = val_loss save_path = saver.save(sess, base_folder + "best_model.ckpt") save_path_last = saver.save(sess, base_folder + "last_model.ckpt") # print('Other Calcs: ', time.time()-other_calcs_start) print("Validation Loss: {}".format(val_loss)) # print("Time to train and validate epoch: {} s".format(time.time()-epoch_start)) print("Best Validation Loss: {}".format(best_val_loss)) print("Hyperparameters:") print("Batch size: {}".format(BATCH_SIZE)) print("Layers: {}".format(layers)) print("Hidden size: {}".format(hidden_size)) print("Iterations: {}".format(iterations)) # Save test data test_ts_file = base_folder + 'test_ts.sdf' test_reactant_file = base_folder + 'test_reactants.sdf' test_products_file = base_folder + 'test_products.sdf' test_ts_writer = Chem.SDWriter(test_ts_file) test_reactant_writer = Chem.SDWriter(test_reactant_file) test_product_writer = Chem.SDWriter(test_products_file) for i in range(len(data_test)): test_reactant_writer.write(data_test[i][0]) test_ts_writer.write(data_test[i][1]) test_product_writer.write(data_test[i][2])
Python
3D
PattanaikL/ts_gen
model/GNN.py
.py
3,817
92
from __future__ import print_function import tensorflow as tf import numpy as np def GNN(V_init, E_init, sizes, iterations=3, edge_layers = 2, edge_hidden = 100, node_layers = 2, node_hidden = 100, act=tf.nn.relu): """ Graph neural network with node & edge updates """ V, E = V_init, E_init # Get dimensions N_v = int(V.get_shape()[1]) C_v = int(V.get_shape()[2]) C_e = int(E.get_shape()[3]) with tf.variable_scope("GraphNeuralNet"): with tf.variable_scope("Masks"): mask = tf.sequence_mask( sizes, maxlen=N_v, dtype=tf.float32, name="Mask1D" ) mask_V = tf.expand_dims(mask, 2) mask_E = tf.expand_dims(mask_V,1) * tf.expand_dims(mask_V,2) # Initialize hidden state with tf.variable_scope("NodeInit"): V = mask_V * MLP(V, node_layers, node_hidden) with tf.variable_scope("EdgeInit"): E = mask_E * MLP(E, edge_layers, edge_hidden) tf.summary.image("Edge", E[:,:,:,:3]) for i in range(iterations): # with tf.variable_scope("Iteration{}".format(i)): # reuse = None with tf.name_scope("Iteration{}".format(i)): reuse = True if i > 0 else None with tf.variable_scope("EdgeUpdate", reuse=reuse): # Update edges given {V,E} f = PairFeatures( V, E, edge_hidden, reuse=reuse, name="EdgeFeatures", activation=act ) dE = MLP( f, edge_layers, edge_hidden, name="EdgeMLP", activation=act, reuse=reuse # changed ) # dE = tf.layers.dropout(dE, dropout, training=bool(dropout)) E = E + mask_E * dE with tf.variable_scope("NodeUpdate", reuse=reuse): # Update nodes given {V,E'} # f = PairFeatures( # V, E, node_hidden, reuse=reuse, name="NodeFeatures", activation=act # ) tf.summary.image("EdgeOut", E[:,:,:,:3]) dV = MLP( E, node_layers, node_hidden, name = "NodeMessages", activation=act, reuse=reuse ) dV = tf.reduce_sum(dV, 2) dV = MLP( dV, node_layers, node_hidden, name = "NodeMLP", activation=act, reuse=reuse # changed ) # dV = tf.layers.dropout(dV, dropout, training=bool(dropout)) V = V + mask_V * dV return V, E, mask_V, mask_E def PairFeatures(V, E, out_dim, reuse=None, name="PairFeatures", activation=tf.nn.relu): """ Build pair features from V,E """ with tf.variable_scope(name, reuse=reuse): f_ij = tf.layers.dense( E, out_dim, use_bias=True, name="f_ij", reuse=reuse ) f_i = tf.expand_dims(tf.layers.dense( V, out_dim, use_bias=False, name="f_i", reuse=reuse ), 1) f_j = tf.expand_dims(tf.layers.dense( V, out_dim, use_bias=False, name="f_j", reuse=reuse ), 2) f = activation(f_ij + f_i + f_j) return f def MLP(input_h, num_layers, out_dim, name="MLP", activation=tf.nn.relu, reuse=None): """ Build a multilayer perceptron """ with tf.variable_scope(name, reuse=reuse): h = input_h for i in range(num_layers): h = tf.layers.dense( h, out_dim, use_bias=True, activation=activation, name="mlp{}".format(i), reuse = reuse ) h = tf.layers.dense( h, out_dim, use_bias=True, name="mlp_out", reuse=reuse ) return h
Python
3D
PattanaikL/ts_gen
model/G2C.py
.py
13,479
343
from __future__ import print_function import os, time import numpy as np import tensorflow as tf import GNN class G2C: def __init__(self, num_gpus=1, max_size=29, build_backprop=True, node_features=7, edge_features=3, layers=2, hidden_size=128, iterations=3, input_data=None): """ Initialize a Graph-to-coordinates network """ # tf.set_random_seed(42) self.dims = { "max": max_size, "nodes": node_features, "edges": edge_features } self.hyperparams = { "node_layers": layers, "node_hidden": hidden_size, "edge_layers": layers, "edge_hidden": hidden_size, "iterations": iterations } with tf.variable_scope("Inputs"): if not input_data: # Placeholders placeholders = {} placeholders["nodes"] = tf.placeholder( tf.float32, [None, self.dims["max"], self.dims["nodes"]], name="Nodes" ) placeholders["edges"] = tf.placeholder( tf.float32, [None, self.dims["max"], self.dims["max"], self.dims["edges"]], name="Edges" ) placeholders["sizes"] = tf.placeholder( tf.int32, [None], name="Sizes" ) placeholders["coordinates"] = tf.placeholder( tf.float32, [None, self.dims["max"], 3], name="Coordinates" ) self.placeholders = placeholders else: self.placeholders = input_data # Build graph neural network V, E, mask_V, mask_E = GNN.GNN( self.placeholders["nodes"], self.placeholders["edges"], self.placeholders["sizes"], iterations=self.hyperparams["iterations"], node_layers=self.hyperparams["node_layers"], node_hidden=self.hyperparams["node_hidden"], edge_layers=self.hyperparams["edge_layers"], edge_hidden=self.hyperparams["edge_hidden"] ) self.tensors = {"V": V, "E": E} mask_D = tf.squeeze(mask_E, 3) self.masks = { "V": mask_V, "E": mask_E, "D": mask_D} tf.summary.image("EdgeOut", E[:,:,:,:3]) # Build featurization with tf.variable_scope("DistancePredictions"): E = GNN.MLP( E, self.hyperparams["edge_layers"], self.hyperparams["edge_hidden"] ) self.tensors["embedding"] = tf.reduce_sum(E, axis=[1,2]) # Make unc. distance and weight predictions E_out = tf.layers.dense(E, 2, use_bias=True, name="edge_out") # Symmetrize E_out = E_out + tf.transpose(E_out, [0,2,1,3]) # permuting on i,j # Distance matrix prediction D_init = tf.get_variable( "D_init", (), initializer=tf.constant_initializer([4.]) ) # Enforce positivity D = tf.nn.softplus(D_init + E_out[:,:,:,0]) # Enforce self-distance = 0 D = self.masks["D"] * tf.linalg.set_diag( D, tf.zeros_like(tf.squeeze(self.masks["V"],2)) ) self.tensors["D_init"] = D tf.summary.image("DistancePred", tf.expand_dims(D,3)) # Weights prediction # W = tf.nn.sigmoid(E_out[:,:,:,1]) W = tf.nn.softplus(E_out[:,:,:,1]) self.tensors["W"] = W tf.summary.image("W", tf.expand_dims(W,3)) self.debug_op = tf.add_check_numerics_ops() with tf.variable_scope("Reconstruct"): # B = self.distance_to_gram(D, self.masks["D"]) # tf.summary.image("B", tf.expand_dims(B,3)) # X = self.low_rank_approx(B) # X = self.low_rank_approx_weighted(B, W) # X = self.low_rank_approx_weighted(B, W) # Minimize the objective with unrolled gradient descent X = self.dist_nlsq(D, W, self.masks["D"]) self.tensors["X"] = X with tf.variable_scope("Loss"): # RMSD Loss self.loss, self.tensors["X"] = self.rmsd(X, self.placeholders["coordinates"], self.masks["V"] ) tf.summary.scalar("LossRMSD", self.loss) # Difference of distances D_model = self.masks["D"] * self.distances(X) D_target = self.masks["D"] * self.distances(self.placeholders["coordinates"]) tf.summary.image("DistModel", tf.expand_dims(D_model,3)) tf.summary.image("DistTarget", tf.expand_dims(D_target,3)) tf.summary.histogram("DistModel", D_model) tf.summary.histogram("DistTarget", D_target) self.loss_distance_all = self.masks["D"] * tf.abs(D_model - D_target) self.loss_distance = tf.reduce_sum(self.loss_distance_all) / tf.reduce_sum(self.masks["D"]) tf.summary.scalar("LossDistance", self.loss_distance) # self.debug_op = tf.add_check_numerics_ops() with tf.variable_scope("Optimization"): opt = tf.train.AdamOptimizer(learning_rate=0.0001) gvs = opt.compute_gradients(self.loss_distance) # gvs is list of (gradient, variable) pairs gvs_clipped, global_norm = self.clip_gradients(gvs) self.train_op = tf.cond( tf.debugging.is_finite(global_norm), # if global norm is finite lambda: opt.apply_gradients(gvs_clipped), # apply gradients lambda: tf.no_op() # otherwise do nothing ) # self.debug_op = tf.add_check_numerics_ops() return def distance_to_gram(self, D, mask): """ Convert distance to gram matrix """ N_f32 = tf.to_float(self.placeholders["sizes"]) D = tf.square(D) D_row = tf.reduce_sum(D, 1, keep_dims=True) \ / tf.reshape(N_f32, [-1,1,1]) D_col = tf.reduce_sum(D, 2, keep_dims=True) \ / tf.reshape(N_f32, [-1,1,1]) D_mean = tf.reduce_sum(D, [1,2], keep_dims=True) \ / tf.reshape(tf.square(N_f32), [-1,1,1]) B = mask * -0.5 * (D - D_row - D_col + D_mean) return B def low_rank_approx(self, A, k=3): with tf.variable_scope("LowRank"): A = self.dither(A) # Recover X S, U, V = tf.svd( A, full_matrices=True, compute_uv=True, name="SVD" ) X = tf.sqrt(tf.expand_dims(S[:,:k],1) + 1E-3) * U[:,:,:k] # Debug SV collisions # tf.summary.image("A", tf.expand_dims(A,3)) # S_gap = tf.reduce_min(tf.abs(S[:,1:] - S[:,:-1])) # tf.summary.scalar("S_gap", S_gap) return X def low_rank_approx_power(self, A, k=3, num_steps=10): # Low rank approximation with tf.variable_scope("LowRank"): A_lr = A u_set = [] for kx in range(k): # Initialize Eigenvector u = tf.expand_dims(tf.random_normal(tf.shape(A)[:-1]),-1) # Power iteration for j in range(num_steps): u = tf.nn.l2_normalize(u, 1, epsilon=1e-3) u = tf.matmul(A_lr, u) # Rescale by sqrt(eigenvalue) eig_sq = tf.reduce_sum(tf.square(u), 1, keep_dims=True) u = u / tf.pow(eig_sq + 1E-2, 0.25) u_set.append(u) A_lr = A_lr - tf.matmul(u, u, transpose_b=True) X = tf.concat(axis=2, values=u_set) return X def low_rank_approx_weighted(self, A, W, k=3, num_iter=10): with tf.variable_scope("WeightedLowRank"): WA = W * A W_comp = (1. - W) A_i = tf.zeros_like(A) for i in range(num_iter): # Low-rank approximation # X = self.low_rank_approx_power(A, k=3) k_i = max(3 + (self.dims["max"] - 3) * (num_iter - i-1) / num_iter, 3) print(k_i) X = self.low_rank_approx(A, k=k_i) # Rebuild matrix if i < num_iter - 1: X = X + tf.random_normal(tf.shape(X)) / (i + 1) A_i = tf.matmul(X, X, transpose_b = True) return X def dither(self, A, symmetrize=True, radius=1E-2): with tf.variable_scope("Dither"): A = A * self.masks["D"] A = A + 1E-2 * tf.random_normal(tf.shape(A)) perturb = tf.random_shuffle(tf.range(tf.to_float(tf.shape(A)[1]))) A = A + 1E-2 * tf.expand_dims(tf.matrix_diag(perturb), 0) if symmetrize: A = 0.5 * (A + tf.transpose(A,[0,2,1])) return A def dist_nlsq(self, D, W, mask): """ Solve a nonlinear distance geometry problem by nonlinear least squares Objective is Sum_ij w_ij (D_ij - |x_i - x_j|)^2 """ T = 100 # eps = tf.exp(tf.get_variable( # "eps", (), initializer=tf.constant_initializer([np.log(0.1)]) # )) # tf.summary.scalar("eps", eps) # # Max speed # alpha = tf.exp(tf.get_variable( # "alpha", (), # initializer=tf.constant_initializer([np.log(5.0)]) # )) # tf.summary.scalar("alpha", alpha) eps = 0.1 alpha = 5.0 alpha_base = 0.1 def gradfun(X): """ Grad function """ D_X = self.distances(X) # Energy calculation U = tf.reduce_sum(mask * W * tf.square(D - D_X), [1,2]) \ / tf.reduce_sum(mask, [1,2]) U = tf.reduce_sum(U) # Gradient calculation g = tf.gradients(U, X)[0] # DEBUG: g = tf.cond( tf.debugging.is_finite(tf.reduce_sum(g)), lambda: g, lambda: tf.Print( g, [tf.reduce_sum(tf.square(X)), tf.reduce_sum(tf.square(g)), tf.reduce_sum(D), tf.reduce_sum(U)], message="Error with Gradient" ) ) return g def stepfun(t, x_t): """ Step function """ g = gradfun(x_t) dx = -eps * g # Speed clipping (How fast in Angstroms) speed = tf.sqrt( tf.reduce_sum(tf.square(dx), 2, keep_dims=True) + 1E-3 ) # Alpha sets max speed (soft trust region) alpha_t = alpha_base + (alpha - alpha_base) * tf.to_float((T - t) / T) scale = alpha_t * tf.tanh(speed / alpha_t) / speed dx *= scale x_new = x_t + dx # DEBUG: x_new = tf.cond( tf.debugging.is_finite(tf.reduce_sum(x_new)), lambda: x_new, lambda: tf.Print( x_new, [t, tf.reduce_sum(x_new), tf.reduce_sum(g)], message="Error with Coordinates" ) ) return t + 1, x_new # Initialization B = self.distance_to_gram(D, mask) x_init = self.low_rank_approx_power(B) # Prepare simulation x_init += tf.random_normal([tf.shape(D)[0], self.dims["max"], 3]) state_init = [0, x_init] # Optimization loop _, x_final = tf.while_loop( lambda t, x: t < T, stepfun, state_init, swap_memory=False ) return x_final def rmsd(self, X1, X2, mask_V): """ RMSD between two structures """ with tf.variable_scope("RMSD"): X1 = X1 - tf.reduce_sum(mask_V * X1,axis=1,keep_dims=True) \ / tf.reduce_sum(mask_V, axis=1,keep_dims=True) X2 = X2 - tf.reduce_sum(mask_V * X2,axis=1,keep_dims=True) \ / tf.reduce_sum(mask_V, axis=1,keep_dims=True) X1 *= mask_V X2 *= mask_V eps = 1E-2 X1_perturb = X1 + eps * tf.random_normal(tf.shape(X1)) X2_perturb = X2 + eps * tf.random_normal(tf.shape(X1)) A = tf.matmul(X2_perturb, X1_perturb, transpose_a=True) S,U,V = tf.svd(A, full_matrices=True, compute_uv=True, name="SVD") X1_align = tf.matmul(U, tf.matmul(V, X1, transpose_b = True)) X1_align = tf.transpose(X1_align, [0,2,1]) MSD = tf.reduce_sum(mask_V * tf.square(X1_align - X2), [1,2]) \ / tf.reduce_sum(mask_V, [1, 2]) RMSD = tf.reduce_mean(tf.sqrt(MSD + 1E-3)) return RMSD, X1_align def clip_gradients(self, gvs): """ Clip the gradients """ with tf.name_scope("Clip"): grads, gvars = list(zip(*gvs)[0]), list(zip(*gvs)[1]) clipped_grads, global_norm = tf.clip_by_global_norm(grads, 10) tf.summary.scalar('gradient_norm', global_norm) clipped_gvs = zip(clipped_grads, gvars) return clipped_gvs, global_norm def distances(self, X): """ Compute Euclidean distances from X """ with tf.variable_scope("SquaredDistances"): Dsq = tf.square(tf.expand_dims(X, 1) - tf.expand_dims(X, 2)) D = tf.sqrt(tf.reduce_sum(Dsq, 3) + 1E-2) return D
Python
3D
PattanaikL/ts_gen
model/__init__.py
.py
2
2
Python
3D
PattanaikL/ts_gen
model/util.py
.py
835
31
from rdkit import Chem import pymol import tempfile, os import numpy as np def render_pymol(mol, img_file, width=300, height=200): """ Render rdkit molecule with a pymol ball & stick representation """ target = "all" pymol.cmd.delete(target) pymol.cmd.set("max_threads", 4) pymol.cmd.viewport(width, height) pymol.cmd.bg_color(color="white") # Save the file fd, temp_path = tempfile.mkstemp(suffix=".pdb") Chem.MolToPDBFile(mol, temp_path) pymol.cmd.load(temp_path) os.close(fd) # Representation pymol.cmd.color("gray40", target) pymol.util.cnc() pymol.cmd.show_as("spheres", target) pymol.cmd.show("licorice", target) pymol.cmd.set("sphere_scale", 0.25) pymol.cmd.orient() pymol.cmd.zoom(target, complete=1) pymol.cmd.png(img_file, ray=1) return
Python
3D
marcdcfischer/PUNet
src/__init__.py
.py
0
0
null
Python
3D
marcdcfischer/PUNet
src/main.py
.py
5,411
90
import argparse from argparse import ArgumentParser import pytorch_lightning as pl from typing import Type import pathlib as plb from src.utils import aws from src.data.loader_monai import BasicDataModule from src.modules.instruction_model import InstructionModel as Model from src.modules.instruction_model_simple import InstructionModelSimple as ModelSimple from src.modules.architectures.momentum_model import MomentumModel as Architecture from src.modules.architectures.momentum_model_simple import MomentumModelSimple as ArchitectureSimple from src.utils import initialization, callbacks def main(hparams: argparse.Namespace, cls_dm: Type[pl.LightningDataModule], cls_model: Type[pl.LightningModule]): path_root = plb.Path(__file__).resolve().parent.parent if hparams.mode == 'fit': pl.seed_everything(1234, workers=True) dm, model, trainer = initialization.setup_training(hparams, cls_dm=cls_dm, cls_model=cls_model, path_root=path_root) trainer.fit(model, datamodule=dm) elif hparams.mode == 'validate': pl.seed_everything(2345, workers=True) dm, model, trainer = initialization.setup_training(hparams, cls_dm=cls_dm, cls_model=cls_model, path_root=path_root) trainer.validate(model, datamodule=dm) elif hparams.mode == 'test': pl.seed_everything(3456, workers=True) dm, model, trainer = initialization.setup_testing(hparams, cls_dm=cls_dm, cls_model=cls_model, path_root=path_root) trainer.test(model, datamodule=dm) elif hparams.mode == 'predict': pl.seed_everything(4567, workers=True) dm, model, trainer = initialization.setup_testing(hparams, cls_dm=cls_dm, cls_model=cls_model, path_root=path_root) trainer.predict(model, datamodule=dm) else: raise ValueError(f'The mode {hparams.mode} is not available.') # Exemplary execution # See shell/common/cfgs.sh for variants # Training: --gpus 1 --batch_size 8 --architecture wip --dataset tcia_btcv # Downstream: --gpus 1 --batch_size 8 --architecture wip --dataset tcia_btcv --adaptation_variant prompting --no_overwrite --cold_start --selective_freezing --downstream --label_indices_base 1 --label_indices_downstream_active 2 --max_epochs 100 # Test: --gpus 1 --mode test --architecture wip --dataset tcia_btcv --no_overwrite --cold_start if __name__ == '__main__': parser = ArgumentParser() parser.add_argument('--s3_bucket', nargs='?', const='', default='', type=str) parser.add_argument('--ckpt', default=None, type=str) parser.add_argument('--ckpt_run_name', default=None, type=str) # e.g. med_rep_learning_XXX parser.add_argument('--cold_start', action='store_true') # Ignores the optimizer state dict parser.add_argument('--no_overwrite', action='store_true') # Keep (most) hparameters of saved checkpoint parser.add_argument('--plot', default=True, type=bool) parser.add_argument('--online_logger', default='wandb', type=str) parser.add_argument('--online_entity', default='my_entity', type=str) # EDIT ME (if needed) parser.add_argument('--online_project', default='my_project', type=str) # EDIT ME (if needed) parser.add_argument('--online_on', action='store_true') parser.add_argument('--tags', nargs='*', type=str) parser.add_argument('--tmp_dir', default='/tmp', type=str) parser.add_argument('--export_dir', default='/mnt/SSD_SATA_03/data_med/prompting/output', type=str) # EDIT ME parser.add_argument('--mode', default='fit', type=str, choices=['fit', 'validate', 'test', 'predict']) # Lightning modes parser.add_argument('--architecture', default='wip', type=str, choices=['wip', 'wip_simple', 'unet', 'unetr', 'swin_unetr']) parser.add_argument('--architecture_wip', default='deep', type=str, choices=['deep']) # variants of wip architecture parser.add_argument('--check_val_every_n_epoch_', default=10, type=int) parser.add_argument('--check_val_every_n_epoch_downstream', default=5, type=int) parser.add_argument('--plot_interval_train', default=50, type=int) parser.add_argument('--plot_interval_val', default=50, type=int) # should be 1 or a multiple of check_val_every_n_epoch for regular plots parser.add_argument('--plot_interval_test', default=1, type=int) # Parameter parsing parser = pl.Trainer.add_argparse_args(parser) hparams_tmp = parser.parse_known_args()[0] cls_dm = BasicDataModule if hparams_tmp.architecture.lower() == 'wip': cls_model = Model cls_architecture = Architecture elif hparams_tmp.architecture.lower() == 'wip_simple' or hparams_tmp.architecture.lower() in ['unet', 'unetr', 'swin_unetr']: cls_model = ModelSimple cls_architecture = ArchitectureSimple else: raise NotImplementedError(f'{hparams_tmp.architecture} is not a valid architecture.') parser = cls_dm.add_data_specific_args(parser) parser = cls_model.add_model_specific_args(parser) parser = cls_architecture.add_model_specific_args(parser) parser = aws.add_aws_specific_args(parser) parser = callbacks.add_callback_specific_args(parser) hparams = parser.parse_args() # fetch and set ckpt if run_name is given (and no ckpt path is passed) if hparams.ckpt is None and hparams.ckpt_run_name and not hparams.ckpt_run_name.isspace(): hparams.ckpt = aws.fetch_ckpt(hparams) main(hparams, cls_dm, cls_model)
Python
3D
marcdcfischer/PUNet
src/modules/__init__.py
.py
0
0
null
Python