diff --git a/.github/workflows/update-docs.yml b/.github/workflows/update-docs.yml index 14ace447..600d9815 100644 --- a/.github/workflows/update-docs.yml +++ b/.github/workflows/update-docs.yml @@ -2,7 +2,7 @@ name: Publish SpatialPy Docs on: push: - branches: [main] + branches: [develop] jobs: publish: @@ -12,7 +12,7 @@ jobs: - name: Initialize environment uses: actions/checkout@v2 with: - ref: main + ref: develop fetch-depth: 0 - name: Install Python @@ -27,10 +27,15 @@ jobs: python3 -m pip install numpy python3 -m pip install -r requirements.txt + - name: Refresh Repository + working-directory: . + run: | + git pull origin develop + - name: Update the Docs working-directory: docs run: | - make build-docs + make html - name: Commit Changes working-directory: docs @@ -43,4 +48,4 @@ jobs: uses: ad-m/github-push-action@master with: github_token: ${{ secrets.GITHUB_TOKEN }} - branch: main + branch: develop diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo index 09dbd4ca..8287e0c2 100644 --- a/docs/build/html/.buildinfo +++ b/docs/build/html/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: aa9a9a3c9380df45ffa4c7a40b7ba182 +config: e12fa66f30479b44f49efa882ed90e3f tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/.doctrees/classes/spatialpy.core.doctree b/docs/build/html/.doctrees/classes/spatialpy.core.doctree index 1a3ecd46..dae0065f 100644 Binary files a/docs/build/html/.doctrees/classes/spatialpy.core.doctree and b/docs/build/html/.doctrees/classes/spatialpy.core.doctree differ diff --git a/docs/build/html/.doctrees/environment.pickle b/docs/build/html/.doctrees/environment.pickle index 88404175..403ef47b 100644 Binary files a/docs/build/html/.doctrees/environment.pickle and b/docs/build/html/.doctrees/environment.pickle differ diff --git a/docs/build/html/.doctrees/index.doctree b/docs/build/html/.doctrees/index.doctree index 6c28fd08..43787c12 100644 Binary files a/docs/build/html/.doctrees/index.doctree and b/docs/build/html/.doctrees/index.doctree differ diff --git a/docs/build/html/_modules/index.html b/docs/build/html/_modules/index.html index e5e29dba..156c6762 100644 --- a/docs/build/html/_modules/index.html +++ b/docs/build/html/_modules/index.html @@ -5,7 +5,7 @@
-
import tempfile
[docs]def cleanup_tempfiles():
- '''
+ '''
Cleanup all tempfiles in spatialpy core, build, and results.
'''
cleanup_core_files()
@@ -124,10 +126,10 @@ Source code for spatialpy.core.cleanup
cleanup_result_files(result_dir=os.path.join(tempdir, file_obj))
[docs]def cleanup_core_files():
- '''
+ '''
Cleanup all tempfiles in spatialpy core.
'''
- from spatialpy.core import log # pylint: disable=import-outside-toplevel
+ from spatialpy.core import log # pylint: disable=import-outside-toplevel
tempdir = tempfile.gettempdir()
core_dir = os.path.join(tempdir, "spatialpy_core")
@@ -136,13 +138,13 @@ Source code for spatialpy.core.cleanup
log.info("Spatialpy core directory was removed")
[docs]def cleanup_build_files(build_dir=None):
- '''
+ '''
Cleanup all spatialpy_build directories.
:param build_dir: Path to the build directory to be removed. (optional)
:type build_dir: string
'''
- from spatialpy.core import log # pylint: disable=import-outside-toplevel
+ from spatialpy.core import log # pylint: disable=import-outside-toplevel
if build_dir is not None:
shutil.rmtree(build_dir)
@@ -158,13 +160,13 @@ Source code for spatialpy.core.cleanup
log.info("{} build directories were removed", count)
[docs]def cleanup_result_files(result_dir=None):
- '''
+ '''
Cleanup all spatialpy_result directories.
:param result_dir: Path to the result directory to be removed. (optional)
:type result_dir: string
'''
- from spatialpy.core import log # pylint: disable=import-outside-toplevel
+ from spatialpy.core import log # pylint: disable=import-outside-toplevel
if result_dir is not None:
shutil.rmtree(result_dir)
@@ -197,8 +199,8 @@ Source code for spatialpy.core.cleanup
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/datafunction.html b/docs/build/html/_modules/spatialpy/core/datafunction.html
index b9a186c6..ee481528 100644
--- a/docs/build/html/_modules/spatialpy/core/datafunction.html
+++ b/docs/build/html/_modules/spatialpy/core/datafunction.html
@@ -5,14 +5,16 @@
- spatialpy.core.datafunction — SpatialPy 1.1.0 documentation
+ spatialpy.core.datafunction — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -106,10 +108,10 @@ Source code for spatialpy.core.datafunction
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-from spatialpy.core.spatialpyerror import DataFunctionError
+from spatialpy.core.spatialpyerror import DataFunctionError
[docs]class DataFunction():
- """
+ """
Abstract class used to constuct the data function.
:param name: Name of the Data Function.
@@ -118,14 +120,14 @@ Source code for spatialpy.core.datafunction
:raises DataFunctionError: If a name is not provided.
"""
- def __init__(self, name=None):
+ def __init__(self, name=None):
if name is not None:
self.name = name
if self.name is None:
raise DataFunctionError("DataFunction must have a 'name'")
[docs] def map(self, point):
- """
+ """
This method must be overridden by the DataFunction subclass.
NOTE: The spatial location is evaulated at t=0 and is not \
@@ -137,7 +139,7 @@ Source code for spatialpy.core.datafunction
:returns: Value of function at this spatial location.
:rtype: float
"""
- raise DataFunctionError(f"{self.name}: DataFunction.map() must be implemented.")
+ raise DataFunctionError(f"{self.name}: DataFunction.map() must be implemented.")
@@ -157,8 +159,8 @@ Source code for spatialpy.core.datafunction
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/domain.html b/docs/build/html/_modules/spatialpy/core/domain.html
index e44c825f..27ba4e38 100644
--- a/docs/build/html/_modules/spatialpy/core/domain.html
+++ b/docs/build/html/_modules/spatialpy/core/domain.html
@@ -5,14 +5,16 @@
- spatialpy.core.domain — SpatialPy 1.1.0 documentation
+ spatialpy.core.domain — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
import copy
import string
-from itertools import combinations
-from collections import OrderedDict
+from itertools import combinations
+from collections import OrderedDict
import numpy
-from plotly.offline import init_notebook_mode, iplot
-from scipy.spatial import KDTree
+from plotly.offline import init_notebook_mode, iplot
+from scipy.spatial import KDTree
-from spatialpy.core.geometry import (
+from spatialpy.core.geometry import (
CombinatoryGeometry, Geometry, GeometryAll
)
-from spatialpy.core.lattice import (
+from spatialpy.core.lattice import (
Lattice, CartesianLattice, SphericalLattice, CylindricalLattice,
XMLMeshLattice, MeshIOLattice, StochSSLattice
)
-from spatialpy.core.transformation import Transformation
-from spatialpy.core.visualization import Visualization
-from spatialpy.core.spatialpyerror import DomainError
+from spatialpy.core.transformation import Transformation
+from spatialpy.core.visualization import Visualization
+from spatialpy.core.spatialpyerror import DomainError
[docs]class Domain():
- """
+ """
Domain class for SpatialPy. A domain defines points and attributes of a regional space for simulation.
:param numpoints: Total number of spatial domain points
@@ -155,7 +157,7 @@ Source code for spatialpy.core.domain
:param gravity: Acceleration of gravity for the system.
:type gravity: float[3]
"""
- def __init__(self, numpoints, xlim, ylim, zlim, rho0=1.0, c0=10, P0=None, gravity=None, actions=None):
+ def __init__(self, numpoints, xlim, ylim, zlim, rho0=1.0, c0=10, P0=None, gravity=None, actions=None):
if actions is None:
actions = []
@@ -192,12 +194,12 @@ Source code for spatialpy.core.domain
self.ylim = ylim
self.zlim = zlim
- def __str__(self):
+ def __str__(self):
pad = " "
- domain_strs = ["Domain Attributes", "", f"{pad}On Boundary: {self.on_boundary}",
- f"{pad}Domain Size: {self.domain_size}", f"{pad}RHO_0: {self.rho0}", f"{pad}C_0: {self.c0}",
- f"{pad}P_0: {self.P0}", f"{pad}Gravity: {self.gravity}", f"{pad}X Limit: {self.xlim}",
- f"{pad}Y Limit: {self.ylim}", f"{pad}Z Limit: {self.zlim}"]
+ domain_strs = ["Domain Attributes", "", f"{pad}On Boundary: {self.on_boundary}",
+ f"{pad}Domain Size: {self.domain_size}", f"{pad}RHO_0: {self.rho0}", f"{pad}C_0: {self.c0}",
+ f"{pad}P_0: {self.P0}", f"{pad}Gravity: {self.gravity}", f"{pad}X Limit: {self.xlim}",
+ f"{pad}Y Limit: {self.ylim}", f"{pad}Z Limit: {self.zlim}"]
print("\n".join(domain_strs))
@@ -222,7 +224,7 @@ Source code for spatialpy.core.domain
self.c[ndx] = float(c)
self.fixed[ndx] = bool(fixed)
except ValueError as err:
- raise DomainError(f"Failed to set all properties. Reaseon given: {err}") from err
+ raise DomainError(f"Failed to set all properties. Reaseon given: {err}") from err
def _ipython_display_(self, use_matplotlib=False):
self.plot_types(width="auto", height="auto", use_matplotlib=use_matplotlib)
@@ -240,7 +242,7 @@ Source code for spatialpy.core.domain
[docs] def add_fill_action(self, lattice=None, geometry=None, cartesian=None, spherical=None,
cylindrical=None, enable=True, apply_action=False, **props):
- r"""
+ r"""
Create an action that can add particles to the domain.
:param lattice: Lattice classed used when applying fill actions.
@@ -294,7 +296,7 @@ Source code for spatialpy.core.domain
return action
[docs] def add_point(self, point, vol=1, mass=1, type_id="UnAssigned", nu=0, fixed=False, rho=None, c=10):
- """
+ """
Add a single point particle to the domain space.
:param point: Spatial coordinate vertices of point to be added
@@ -328,10 +330,11 @@ Source code for spatialpy.core.domain
if isinstance(type_id, int) and type_id <= 0:
raise DomainError("Type_id must be a non-zero positive integer or a string.")
- for char in type_id:
- if (char in string.punctuation and char != "_") or char == " ":
- raise DomainError(f"Type_id cannot contain '{char}'")
- type_id = f"type_{type_id}"
+ if isinstance(type_id, str):
+ for char in type_id:
+ if (char in string.punctuation and char != "_") or char == " ":
+ raise DomainError(f"Type_id cannot contain '{char}'")
+ type_id = f"type_{type_id}"
if rho is None:
rho = mass / vol
@@ -347,7 +350,7 @@ Source code for spatialpy.core.domain
self.vertices = numpy.append(self.vertices, [point], axis=0)
[docs] def add_remove_action(self, geometry=None, enable=True, apply_action=False):
- """
+ """
Create an action that can remove particles from the domain.
:param geometry: Geometry classed used when applying set actions. Defaults to spatialpy.GeometryAll.
@@ -372,7 +375,7 @@ Source code for spatialpy.core.domain
return action
[docs] def add_set_action(self, geometry=None, enable=True, apply_action=False, **props):
- r"""
+ r"""
Create an action that can set particle properties for particles in the domain.
:param geometry: Geometry classed used when applying set actions. Defaults to spatialpy.GeometryAll.
@@ -404,7 +407,7 @@ Source code for spatialpy.core.domain
return action
[docs] def apply_actions(self, start=0, end=None, preserve_actions=False):
- """
+ """
Apply domain actions in order from start to end.
:param start: Starting index for actions (inclusive).
@@ -433,7 +436,7 @@ Source code for spatialpy.core.domain
elif action['type'] == "remove":
self.apply_remove_action(action)
else:
- raise DomainError(f"Action of type {action['type']} is not currently supported.")
+ raise DomainError(f"Action of type {action['type']} is not currently supported.")
if preserve_actions or not action['enable']:
start += 1
@@ -443,7 +446,7 @@ Source code for spatialpy.core.domain
return p_count
[docs] def apply_fill_action(self, action):
- """
+ """
Add particles within a region defined by the actions lattice and geometry to the domain.
Particles will have attributes defined in the actions props.
@@ -463,7 +466,7 @@ Source code for spatialpy.core.domain
return action['lattice'].apply(self, action['geometry'], **action['props'])
[docs] def apply_remove_action(self, action):
- """
+ """
Remove particles within a domain region defined by the actions geometry.
:param action: Remove action containing a geometry.
@@ -480,19 +483,22 @@ Source code for spatialpy.core.domain
# remove the particles that fall within the defined region
on_boundary = self.find_boundary_points(update=True)
- for v_ndx in range(self.get_num_voxels()):
- if action['geometry'].inside(self.coordinates()[v_ndx, :], on_boundary[v_ndx]):
- self.type_id = numpy.delete(self.type_id, v_ndx, 0)
- self.vol = numpy.delete(self.vol, v_ndx)
- self.mass = numpy.delete(self.mass, v_ndx)
- self.rho = numpy.delete(self.rho, v_ndx)
- self.nu = numpy.delete(self.nu, v_ndx)
- self.c = numpy.delete(self.c, v_ndx)
- self.fixed = numpy.delete(self.fixed, v_ndx)
- self.on_boundary = numpy.delete(self.on_boundary, v_ndx)
+ geometry = action['geometry']
+ indices = [v_ndx for v_ndx, vertex in enumerate(self.vertices) if geometry.inside(vertex, on_boundary[v_ndx])]
+ indices.reverse()
+ for v_ndx in indices:
+ self.vertices = numpy.delete(self.vertices, v_ndx, 0)
+ self.type_id = numpy.delete(self.type_id, v_ndx, 0)
+ self.vol = numpy.delete(self.vol, v_ndx)
+ self.mass = numpy.delete(self.mass, v_ndx)
+ self.rho = numpy.delete(self.rho, v_ndx)
+ self.nu = numpy.delete(self.nu, v_ndx)
+ self.c = numpy.delete(self.c, v_ndx)
+ self.fixed = numpy.delete(self.fixed, v_ndx)
+ self.on_boundary = numpy.delete(self.on_boundary, v_ndx)
[docs] def apply_set_action(self, action):
- """
+ """
Set properties of particles within a domain region defined by the actions geometry.
Particles will have attributes defined in the actions props.
@@ -513,10 +519,11 @@ Source code for spatialpy.core.domain
if "type_id" in action['props']:
if isinstance(action['props']['type_id'], int) and action['props']['type_id'] <= 0:
raise DomainError("Type_id must be a non-zero positive integer or a string.")
- for char in action['props']['type_id']:
- if (char in string.punctuation and char != "_") or char == " ":
- raise DomainError(f"Type_id cannot contain '{char}'")
- action['props']['type_id'] = f"type_{action['props']['type_id']}"
+ if isinstance(action['props']['type_id'], str):
+ for char in action['props']['type_id']:
+ if (char in string.punctuation and char != "_") or char == " ":
+ raise DomainError(f"Type_id cannot contain '{char}'")
+ action['props']['type_id'] = f"type_{action['props']['type_id']}"
# apply the properties to all points that fall within the defined region
on_boundary = self.find_boundary_points(update=True)
@@ -525,7 +532,7 @@ Source code for spatialpy.core.domain
self.__set_particle_properties(v_ndx, **action['props'])
[docs] def calculate_vol(self):
- """
+ """
Calculate the total volume of the domain.
"""
self.vol = numpy.zeros((self.vertices.shape[0]), dtype=float)
@@ -546,7 +553,7 @@ Source code for spatialpy.core.domain
self.vol[v4] += t_vol / 4
[docs] def closest_vertex(self, point):
- """
+ """
Find the nearest vertex of a given point in the domain.
:param point: Target source point
@@ -564,8 +571,8 @@ Source code for spatialpy.core.domain
min_vtx = i
return min_vtx
-[docs] def compile_prep(self):
- """
+[docs] def compile_prep(self, allow_all_types=False):
+ """
Generate the domains list of type ids and check for invalid type_ids and rho values
in preperation of compiling the simulation files.
@@ -573,8 +580,9 @@ Source code for spatialpy.core.domain
"""
self.apply_actions()
- if self.type_id.tolist().count("type_UnAssigned") > 0:
- raise DomainError("Particles must be assigned a type_id.")
+ if not allow_all_types:
+ if self.type_id.tolist().count("type_UnAssigned") > 0:
+ raise DomainError("Particles must be assigned a type_id.")
if numpy.count_nonzero(self.rho) < len(self.rho):
raise DomainError("Rho must be a positive value.")
@@ -583,7 +591,7 @@ Source code for spatialpy.core.domain
self.listOfTypeIDs = list(self.typeNdxMapping.values())
[docs] def coordinates(self):
- """
+ """
Get coordinates within domain.
:returns: Spatial coordinate vertices of points.
@@ -594,7 +602,7 @@ Source code for spatialpy.core.domain
[docs] @classmethod
def create_2D_domain(cls, xlim, ylim, numx, numy, type_id=1, mass=1.0, nu=1.0, rho=None,
c=0, fixed=False, enable=True, apply_action=True, **kwargs):
- r"""
+ r"""
Create a filled 2D domain
:param xlim: highest and lowest coordinate in the x dimension
@@ -660,7 +668,7 @@ Source code for spatialpy.core.domain
[docs] @classmethod
def create_3D_domain(cls, xlim, ylim, zlim, numx, numy, numz, type_id=1, mass=1.0, nu=1.0,
rho=None, c=0, fixed=False, enable=True, apply_action=True, **kwargs):
- r"""
+ r"""
Create a filled 3D domain
:param xlim: highest and lowest coordinate in the x dimension
@@ -732,7 +740,7 @@ Source code for spatialpy.core.domain
return obj
[docs] def distance_between_2_vertices(self, start, end):
- """
+ """
Get distance between 2 domain vertices.
:param start: Starting point
@@ -748,7 +756,7 @@ Source code for spatialpy.core.domain
[docs] def fill_with_particles(self, geometry_ivar, deltax, deltay=None, deltaz=None, xmin=None, xmax=None,
ymin=None, ymax=None, zmin=None, zmax=None, enable=True, apply_action=True, **kwargs):
- r"""
+ r"""
Fill a region defined by a cartesian lattice and geometric shape with particles.
:param geometry_ivar: an instance of a :py:class:`spatialpy.core.geometry.Geometry` subclass. \
@@ -802,7 +810,7 @@ Source code for spatialpy.core.domain
)
[docs] def find_boundary_points(self, update=False):
- """
+ """
Find all vertices that exist on boundary.
:returns: A numpy array indexed by vertices, True for boundary points, else false.
@@ -836,7 +844,7 @@ Source code for spatialpy.core.domain
return self.on_boundary
[docs] def find_h(self):
- """
+ """
Find h value of system. This value is based off of \
the particle which has the greatest distance to \
its nearest neighbor.
@@ -856,7 +864,7 @@ Source code for spatialpy.core.domain
return h
[docs] def get_bounding_box(self):
- """
+ """
Get the bounding box of the entire domain.
:returns: Limits of the bounding box.
@@ -870,7 +878,7 @@ Source code for spatialpy.core.domain
return xlim, ylim, zlim
[docs] def get_domain_size(self, update=False):
- """
+ """
Estimate of domain size at each vertex as the average of the
diameters of the circumradius of the tetrahedrons that vertex
is a part of.
@@ -910,7 +918,7 @@ Source code for spatialpy.core.domain
return self.domain_size
[docs] def get_num_voxels(self):
- """
+ """
Get number of voxels in domain.
:returns: Number of voxels in the domain.
@@ -919,7 +927,7 @@ Source code for spatialpy.core.domain
return self.vertices.shape[0]
[docs] def get_type_def(self, type_id):
- """
+ """
Get the C++ type definition for the given type.
:param type_id: The type_id within the domain.
@@ -930,15 +938,15 @@ Source code for spatialpy.core.domain
:raises DomainError: If the type is not defined within the domain.
"""
- type_id = f"type_{type_id}"
+ type_id = f"type_{type_id}"
if type_id not in self.typeNdxMapping:
- errmsg = f"Type_id {type_id} could not be found. "
+ errmsg = f"Type_id {type_id} could not be found. "
errmsg += "Use Domain.set_properties to set the type_id for particles."
raise DomainError(errmsg)
return type_id
[docs] def get_vol(self):
- """
+ """
Get the total volume of the domain.
:returns: Total volume of the system.
@@ -950,7 +958,7 @@ Source code for spatialpy.core.domain
[docs] @classmethod
def import_meshio_object(cls, mesh_obj, subdomain_file=None, type_ids=None, enable=True, apply_action=True):
- """
+ """
Import a python meshio mesh object.
:param mesh_obj: MeshIO object to import
@@ -985,7 +993,7 @@ Source code for spatialpy.core.domain
[docs] def plot_types(self, width=None, height=None, colormap=None, size=None, title=None,
included_types_list=None, use_matplotlib=False, return_plotly_figure=False):
- '''
+ '''
Plots the domain using plotly. Can only be viewed in a Jupyter Notebook.
:param width: Width in pixels of output plot box or for matplotlib inches of output plot box. \
@@ -1023,7 +1031,7 @@ Source code for spatialpy.core.domain
if len(self.vertices) == 0:
raise DomainError("The domain does not contain particles.")
- from spatialpy.core.result import _plotly_iterate # pylint: disable=import-outside-toplevel
+ from spatialpy.core.result import _plotly_iterate # pylint: disable=import-outside-toplevel
if not use_matplotlib:
if width in (None, "auto"):
@@ -1125,12 +1133,12 @@ Source code for spatialpy.core.domain
if return_plotly_figure:
return fig
- init_notebook_mode(connected=True)
+ init_notebook_mode()
iplot(fig)
return
[docs] def preview_actions(self, start=0, end=None, **kwargs):
- r"""
+ r"""
Preview effects of actions to the domain.
:param start: Starting index for actions (inclusive).
@@ -1148,7 +1156,7 @@ Source code for spatialpy.core.domain
[docs] @classmethod
def read_msh_file(cls, filename, subdomain_file=None, type_ids=None, enable=True, apply_action=True):
- """
+ """
Read a Gmsh style .msh file
:param filename: Filename of gmsh file
@@ -1183,7 +1191,7 @@ Source code for spatialpy.core.domain
[docs] @classmethod
def read_stochss_domain(cls, filename, enable=True, apply_action=True):
- """
+ """
Read a StochSS Domain (.domn) file or pull a StochSS Domain from a StochSS Spatial Model (.smdl) file.
:param filename: Name of file to read.
@@ -1205,7 +1213,7 @@ Source code for spatialpy.core.domain
return obj
[docs] def read_stochss_subdomain_file(self, filename, type_ids=None):
- """
+ """
Read a .txt file that conains the StochSS v1.x spatial subdomain descriptions.
:param filename: StochSS v1.x subdomain description filename.
@@ -1221,19 +1229,19 @@ Source code for spatialpy.core.domain
try:
(ndx, type_id) = line.rstrip().split(',')
- type_id = f"type_{type_id if type_ids is None else type_ids[type_id]}"
+ type_id = f"type_{type_id if type_ids is None else type_ids[type_id]}"
for char in type_id:
if (char in string.punctuation and char != "_") or char == " ":
- raise DomainError(f"Type_id cannot contain '{char}'")
+ raise DomainError(f"Type_id cannot contain '{char}'")
self.type_id[int(ndx)] = type_id
except ValueError as err:
- raise DomainError(f"Could not read in subdomain file, error on line {lnum}: {line}") from err
+ raise DomainError(f"Could not read in subdomain file, error on line {lnum}: {line}") from err
[docs] @classmethod
def read_xml_mesh(cls, filename, subdomain_file=None, type_ids=None, enable=True, apply_action=True):
- """
+ """
Read a FEniCS/dolfin style XML mesh file
:param filename: Name of file to read.
@@ -1268,7 +1276,7 @@ Source code for spatialpy.core.domain
[docs] def set_properties(self, geometry_ivar, type_id, vol=None, mass=None, nu=None,
rho=None, c=None, fixed=False, enable=True, apply_action=True):
- """
+ """
Add a type definition to the domain. By default, all regions are set to type 0.
:param geometry_ivar: an instance of a :py:class:`spatialpy.core.geometry.Geometry` subclass. \
@@ -1310,7 +1318,7 @@ Source code for spatialpy.core.domain
self.add_set_action(geometry=geometry_ivar, enable=enable, apply_action=apply_action, **props)
[docs] def validate_action(self, action, coverage):
- """
+ """
Validate a domain action.
:param action: Domain action to be validated.
@@ -1330,12 +1338,12 @@ Source code for spatialpy.core.domain
if not (isinstance(action['geometry'], (Geometry, CombinatoryGeometry, Transformation)) or \
g_type in ("Geometry", "CombinatoryGeometry", "Transformation")):
raise DomainError(
- f"A {action['type']} action's geometry must be of type 'Geometry' or 'Transformation' not {g_type}"
+ f"A {action['type']} action's geometry must be of type 'Geometry' or 'Transformation' not {g_type}"
)
if coverage == "fill":
if action['type'] != "fill":
- raise DomainError(f"The action's type must be 'fill' not '{action['type']}'.")
+ raise DomainError(f"The action's type must be 'fill' not '{action['type']}'.")
if action['lattice'] is None:
raise DomainError("Fill actions must have a lattice.")
@@ -1343,23 +1351,23 @@ Source code for spatialpy.core.domain
if not (isinstance(action['lattice'], (Lattice, Transformation)) or \
l_type in ("Lattice", "Transformation")):
raise DomainError(
- f"A fill action's lattice must be of type 'Lattice' or 'Transformation' not {l_type}"
+ f"A fill action's lattice must be of type 'Lattice' or 'Transformation' not {l_type}"
)
if coverage == "set":
if action['type'] != "set":
- raise DomainError(f"The action's type must be 'set' not '{action['type']}'.")
+ raise DomainError(f"The action's type must be 'set' not '{action['type']}'.")
if action['props'] is None or action['props'] == {}:
raise DomainError("Set actions must have a props.")
if coverage == "remove":
if action['type'] != "remove":
- raise DomainError(f"The action's type must be 'remove' not '{action['type']}'.")
+ raise DomainError(f"The action's type must be 'remove' not '{action['type']}'.")
if coverage in ("fill", "set"):
if action['props'] is not None and not isinstance(action['props'], dict):
- raise DomainError(f"An action's kwargs must be of type dict not {type(action['props'])}")
+ raise DomainError(f"An action's kwargs must be of type dict not {type(action['props'])}")
@@ -1379,8 +1387,8 @@ Source code for spatialpy.core.domain
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/geometry.html b/docs/build/html/_modules/spatialpy/core/geometry.html
index 41c07792..1a2882b9 100644
--- a/docs/build/html/_modules/spatialpy/core/geometry.html
+++ b/docs/build/html/_modules/spatialpy/core/geometry.html
@@ -5,14 +5,16 @@
- spatialpy.core.geometry — SpatialPy 1.1.0 documentation
+ spatialpy.core.geometry — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -108,10 +110,10 @@ Source code for spatialpy.core.geometry
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy
-from spatialpy.core.spatialpyerror import GeometryError
+from spatialpy.core.spatialpyerror import GeometryError
[docs]class CombinatoryGeometry:
- """
+ """
Combinatory Geometry class uses one or more Geometry class for inclusion or exclusion of
multiple geometric shapes.
@@ -123,14 +125,14 @@ Source code for spatialpy.core.geometry
'geo2', and 'geo3' are found in the formula.
:type geo_namespace: dict
"""
- def __init__(self, formula, geo_namespace):
+ def __init__(self, formula, geo_namespace):
self.formula = formula
self.geo_namespace = geo_namespace
self.validate()
[docs] def inside(self, point, on_boundary):
- """
+ """
:param point: X, Y, Z coodinates for the particle.
:type point: float[3]
@@ -146,13 +148,13 @@ Source code for spatialpy.core.geometry
for name, geometry in self.geo_namespace.items():
val = geometry.inside(point, on_boundary)
if not isinstance(val, (bool, numpy.bool_)):
- errmsg = f"{name} is not a valid Geometry obj. Reason given: inside() method must return a bool"
+ errmsg = f"{name} is not a valid Geometry obj. Reason given: inside() method must return a bool"
raise GeometryError(errmsg)
namespace[name] = val
return eval(self.formula, {}, namespace)
[docs] def validate(self):
- """
+ """
Validate the combinatory geometry object.
"""
keys = list(self.geo_namespace.keys())
@@ -164,18 +166,18 @@ Source code for spatialpy.core.geometry
for item in keys:
formula = formula.replace(item, "")
if formula.strip() != "":
- errmsg = f"formula may only contain boolean operators or geometries in geo_namespace not {formula.split(' ')}"
+ errmsg = f"formula may only contain boolean operators or geometries in geo_namespace not {formula.split(' ')}"
raise GeometryError(errmsg)
[docs]class Geometry:
- """
+ """
Geometry class provides a method for tagging parts of the spatial domain as separate parts.
"""
- def __init__(self):
+ def __init__(self):
pass
[docs] def inside(self, point, on_boundary):
- """
+ """
:param point: X, Y, Z coodinates for the particle.
:type point: float[3]
@@ -188,11 +190,11 @@ Source code for spatialpy.core.geometry
raise GeometryError("Subclasses of spatialpy.Geometry must implement the inside() method")
[docs]class GeometryAll(Geometry):
- """
+ """
Mark all particles.
"""
[docs] def inside(self, point, on_boundary):
- """
+ """
:param point: X, Y, Z coodinates for the particle.
:type point: float[3]
@@ -205,12 +207,12 @@ Source code for spatialpy.core.geometry
return True
[docs]class GeometryExterior(Geometry):
- """
+ """
Mark particles that are on the edge of the domain.
only works for domains that define triangles and tetrahedrons.
"""
[docs] def inside(self, point, on_boundary):
- """
+ """
:param point: X, Y, Z coodinates for the particle.
:type point: float[3]
@@ -223,12 +225,12 @@ Source code for spatialpy.core.geometry
return on_boundary
[docs]class GeometryInterior(Geometry):
- """
+ """
Mark particles that are not on the edge of the domain.
Only works for domains that define triangles and tetrahedrons.
"""
[docs] def inside(self, point, on_boundary):
- """
+ """
:param point: X, Y, Z coodinates for the particle.
:type point: float[3]
@@ -258,8 +260,8 @@ Source code for spatialpy.core.geometry
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/initialcondition.html b/docs/build/html/_modules/spatialpy/core/initialcondition.html
index 723037fe..abdfbb3c 100644
--- a/docs/build/html/_modules/spatialpy/core/initialcondition.html
+++ b/docs/build/html/_modules/spatialpy/core/initialcondition.html
@@ -5,14 +5,16 @@
- spatialpy.core.initialcondition — SpatialPy 1.1.0 documentation
+ spatialpy.core.initialcondition — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -108,16 +110,16 @@ Source code for spatialpy.core.initialcondition
<
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import numpy
-from spatialpy.core.spatialpyerror import InitialConditionError
+from spatialpy.core.spatialpyerror import InitialConditionError
[docs]class InitialCondition():
- """
+ """
Class used to defined initial conditions in SpatialPy.
SubClasses must implement the 'apply(model)' method, which
direction modifies the model.u0[species, voxel] matrix.
"""
[docs] def apply(self, model):
- """
+ """
Set the initial condition of the species to the count.
:param model: Model contianing the target species.
@@ -126,7 +128,7 @@ Source code for spatialpy.core.initialcondition
<
raise InitialConditionError("spatialpy.InitialCondition subclasses must implement apply()")
[docs]class PlaceInitialCondition(InitialCondition):
- """
+ """
Class used to defined the place initial condition in SpatialPy.
:param species: The species to set the initial condition.
@@ -138,17 +140,17 @@ Source code for spatialpy.core.initialcondition
<
:param location: X, Y, Z coordinates to place the initial condition.
:type location: float[3]
"""
- def __init__(self, species, count, location):
+ def __init__(self, species, count, location):
self.species = species
self.count = count
self.location = location
- def __str__(self):
- print_string = f"{self.species.name}: {str(self.count)}, at: {str(self.location)}"
+ def __str__(self):
+ print_string = f"{self.species.name}: {str(self.count)}, at: {str(self.location)}"
return print_string
[docs] def apply(self, model):
- """
+ """
Set the initial condition of the species to the count at the location.
:param model: Model contianing the target species.
@@ -156,7 +158,7 @@ Source code for spatialpy.core.initialcondition
<
"""
if isinstance(self.species, str):
if self.species not in model.listOfSpecies:
- raise InitialConditionError(f"Species {self.species} does not exist in the model.")
+ raise InitialConditionError(f"Species {self.species} does not exist in the model.")
self.species = model.listOfSpecies[self.species]
spec_name = self.species.name
spec_ndx = None
@@ -168,7 +170,7 @@ Source code for spatialpy.core.initialcondition
<
model.u0[spec_ndx, vtx] += self.count
[docs]class UniformInitialCondition(InitialCondition):
- """
+ """
Class used to defined the uniform initial condition in SpatialPy.
:param species: The species to set the initial condition.
@@ -180,7 +182,7 @@ Source code for spatialpy.core.initialcondition
<
:param types: Types of the particles to place the initial condition.
:type types: list
"""
- def __init__(self, species, count, types=None):
+ def __init__(self, species, count, types=None):
self.species = species
self.count = count
if types is None:
@@ -188,14 +190,14 @@ Source code for spatialpy.core.initialcondition
<
else:
self.types = []
for type_id in types:
- self.types.append(f"type_{type_id}")
+ self.types.append(f"type_{type_id}")
- def __str__(self):
- print_string = f"{self.species.name}: {str(self.count)}, Uniformly distrbuted in: {str(self.types)}"
+ def __str__(self):
+ print_string = f"{self.species.name}: {str(self.count)}, Uniformly distrbuted in: {str(self.types)}"
return print_string
[docs] def apply(self, model):
- """
+ """
Set 'count' of 'species' in over the list of types (all types if None).
:param model: Model contianing the target species.
@@ -203,7 +205,7 @@ Source code for spatialpy.core.initialcondition
<
"""
if isinstance(self.species, str):
if self.species not in model.listOfSpecies:
- raise InitialConditionError(f"Species {self.species} does not exist in the model.")
+ raise InitialConditionError(f"Species {self.species} does not exist in the model.")
self.species = model.listOfSpecies[self.species]
spec_name = self.species.name
spec_ndx = None
@@ -224,7 +226,7 @@ Source code for spatialpy.core.initialcondition
<
[docs]class ScatterInitialCondition(InitialCondition):
- """
+ """
Class used to defined the scatter initial condition in SpatialPy.
:param species: The species to set the initial condition.
@@ -236,7 +238,7 @@ Source code for spatialpy.core.initialcondition
<
:param types: Types of the particles to place the initial condition.
:type types: list
"""
- def __init__(self, species, count, types=None):
+ def __init__(self, species, count, types=None):
self.species = species
self.count = count
if types is None:
@@ -244,14 +246,14 @@ Source code for spatialpy.core.initialcondition
<
else:
self.types = []
for type_id in types:
- self.types.append(f"type_{type_id}")
+ self.types.append(f"type_{type_id}")
- def __str__(self):
- print_string = f"{self.species.name}: {str(self.count)}, Scatter over: {str(self.types)}"
+ def __str__(self):
+ print_string = f"{self.species.name}: {str(self.count)}, Scatter over: {str(self.types)}"
return print_string
[docs] def apply(self, model):
- """
+ """
Scatter 'count' of 'species' randomly over the list of types (all types if None).
:param model: Model contianing the target species.
@@ -259,7 +261,7 @@ Source code for spatialpy.core.initialcondition
<
"""
if isinstance(self.species, str):
if self.species not in model.listOfSpecies:
- raise InitialConditionError(f"Species {self.species} does not exist in the model.")
+ raise InitialConditionError(f"Species {self.species} does not exist in the model.")
self.species = model.listOfSpecies[self.species]
spec_name = self.species.name
spec_ndx = None
@@ -282,7 +284,7 @@ Source code for spatialpy.core.initialcondition
<
nvox = len(allowed_voxels)
if nvox==0:
message = "ScatterInitialCondition has zero voxels to scatter in. "
- message += f"Species={self.species.name} count={self.count} types={self.types}"
+ message += f"Species={self.species.name} count={self.count} types={self.types}"
raise InitialConditionError(message)
for _ in range(self.count):
v_ndx = numpy.random.randint(0, nvox)
@@ -307,8 +309,8 @@ Source code for spatialpy.core.initialcondition
<
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/lattice.html b/docs/build/html/_modules/spatialpy/core/lattice.html
index 45a52b56..b5654470 100644
--- a/docs/build/html/_modules/spatialpy/core/lattice.html
+++ b/docs/build/html/_modules/spatialpy/core/lattice.html
@@ -5,14 +5,16 @@
- spatialpy.core.lattice — SpatialPy 1.1.0 documentation
+ spatialpy.core.lattice — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -107,16 +109,17 @@ Source code for spatialpy.core.lattice
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
-import numpy
+import string
import xml.etree.ElementTree as ET
-from spatialpy.core.geometry import Geometry, CombinatoryGeometry
-from spatialpy.core.spatialpyerror import LatticeError
+import numpy
+from spatialpy.core.geometry import Geometry, CombinatoryGeometry
+from spatialpy.core.spatialpyerror import LatticeError
[docs]class Lattice:
- """
+ """
Lattice class provides a method for creating parts of the spatial domain.
:param center: The center point of the lattice (optional, defaults to [0, 0, 0]).
@@ -125,7 +128,7 @@ Source code for spatialpy.core.lattice
:raises LatticeError: if center is not and list, doesn't contain 3 values,
or any value is not a float.
"""
- def __init__(self, center=None, skip_validate=False):
+ def __init__(self, center=None, skip_validate=False):
if center is None:
center = [0] * 3
elif isinstance(center, (list, tuple)):
@@ -147,7 +150,7 @@ Source code for spatialpy.core.lattice
domain.zlim = zlim
[docs] def apply(self, domain, geometry, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the lattice restricted by the geometry.
:param domain: Domain particles are to be added to.
@@ -165,7 +168,7 @@ Source code for spatialpy.core.lattice
raise LatticeError("Subclasses of spatialpy.Lattice must implement the apply() method")
[docs] def validate(self):
- """
+ """
Validates the center point.
"""
if not isinstance(self.center, list):
@@ -174,7 +177,7 @@ Source code for spatialpy.core.lattice
raise LatticeError("center must be of length 3.")
[docs]class CartesianLattice(Lattice):
- """
+ """
Cartesian lattice class provides a method for creating parts of the spatial
domain within a cartesian coordinate system.
@@ -195,7 +198,7 @@ Source code for spatialpy.core.lattice
:param zmin: Minimum z value of the lattice (optional, defaults to xmin).
:type zmin: float
-
+
:param zmax: Maximum z value of the lattice (optional, defaults to xmax).
:type zmax: float
@@ -211,7 +214,7 @@ Source code for spatialpy.core.lattice
:raises LatticeError: if center is not and list, doesn't contain 3 values,
or any value is not a float.
"""
- def __init__(self, xmin, xmax, deltax, center=None, ymin=None,
+ def __init__(self, xmin, xmax, deltax, center=None, ymin=None,
ymax=None, zmin=None, zmax=None, deltay=None, deltaz=None):
super().__init__(center, skip_validate=True)
@@ -250,13 +253,14 @@ Source code for spatialpy.core.lattice
count += 1
return count
- def __generate_z(self, domain, geometry, transform, x, y, count, kwargs):
+ def __generate_z(self, domain, geometry, transform, x, y, count, z_digits, kwargs):
for z in numpy.arange(self.zmin, self.zmax + self.deltaz, self.deltaz):
+ z = round(z, z_digits)
count = self.__add_point(domain, geometry, transform, [x, y, z], count, kwargs)
return count
[docs] def apply(self, domain, geometry, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the cartesian lattice restricted by the geometry.
:param domain: Domain particles are to be added to.
@@ -271,7 +275,7 @@ Source code for spatialpy.core.lattice
:param \**kwargs: Additional keyword arguments passed to :py:meth:`Domain.add_point`.
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if not (isinstance(geometry, (Geometry, CombinatoryGeometry)) or \
@@ -282,14 +286,31 @@ Source code for spatialpy.core.lattice
if transform is not None and not callable(transform):
raise LatticeError("transform must be a function.")
+ x_digits = max(
+ len(str(self.deltax).split(".")[1]) if "." in str(self.deltax) else 0,
+ len(str(self.xmin).split(".")[1]) if "." in str(self.xmin) else 0,
+ len(str(self.xmax).split(".")[1]) if "." in str(self.xmax) else 0
+ )
+ y_digits = max(
+ len(str(self.deltay).split(".")[1]) if "." in str(self.deltay) else 0,
+ len(str(self.ymin).split(".")[1]) if "." in str(self.ymin) else 0,
+ len(str(self.ymax).split(".")[1]) if "." in str(self.ymax) else 0
+ )
+ z_digits = max(
+ len(str(self.deltaz).split(".")[1]) if "." in str(self.deltaz) else 0,
+ len(str(self.zmin).split(".")[1]) if "." in str(self.zmin) else 0,
+ len(str(self.zmax).split(".")[1]) if "." in str(self.zmax) else 0
+ )
count = 0
for x in numpy.arange(self.xmin, self.xmax + self.deltax, self.deltax):
+ x = round(x, x_digits)
for y in numpy.arange(self.ymin, self.ymax + self.deltay, self.deltay):
+ y = round(y, y_digits)
if self.deltaz == 0:
z = self.center[2]
count = self.__add_point(domain, geometry, transform, [x, y, z], count, kwargs)
else:
- count = self.__generate_z(domain, geometry, transform, x, y, count, kwargs)
+ count = self.__generate_z(domain, geometry, transform, x, y, count, z_digits, kwargs)
self._update_limits(domain)
if 'vol' not in kwargs:
offset = len(domain.vertices) - count
@@ -304,7 +325,7 @@ Source code for spatialpy.core.lattice
return count
[docs] def validate(self):
- """
+ """
Validate the cartesian lattice dependencies.
"""
super().validate()
@@ -341,7 +362,7 @@ Source code for spatialpy.core.lattice
raise LatticeError("deltaz must be greater than 0.")
[docs]class SphericalLattice(Lattice):
- """
+ """
Spherical lattice class provides a method for creating parts of the spatial
domain within a spherical coordinate system.
@@ -360,7 +381,7 @@ Source code for spatialpy.core.lattice
:raises LatticeError: if center is not and list, doesn't contain 3 values,
or any value is not a float.
"""
- def __init__(self, radius, deltas, center=None, deltar=None):
+ def __init__(self, radius, deltas, center=None, deltar=None):
super().__init__(center, skip_validate=True)
self.radius = radius
@@ -374,7 +395,7 @@ Source code for spatialpy.core.lattice
self.validate()
[docs] def apply(self, domain, geometry, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the spherical lattice restricted by the geometry.
:param domain: Domain particles are to be added to.
@@ -389,7 +410,7 @@ Source code for spatialpy.core.lattice
:param \**kwargs: Additional keyword arguments passed to :py:meth:`Domain.add_point`.
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if not (isinstance(geometry, (Geometry, CombinatoryGeometry)) or \
@@ -400,38 +421,54 @@ Source code for spatialpy.core.lattice
if transform is not None and not callable(transform):
raise LatticeError("transform must be a function.")
+ digits = max(
+ len(str(self.deltar).split(".")[1]) if "." in str(self.deltar) else 0,
+ len(str(self.radius).split(".")[1]) if "." in str(self.radius) else 0
+ )
count = 0
radius = self.radius
- while radius >= 0:
+ while radius > 0:
# Calculate the approximate number of particle with the radius
approx_rc = int(round((4 * radius ** 2) / ((self.deltas / 2) ** 2)))
- # Set constants for the radius
- p_area = 4 * numpy.pi * radius ** 2 / approx_rc
- d_a = numpy.sqrt(p_area)
- m_phi = int(round(numpy.pi * radius / d_a))
- d_phi = numpy.pi / m_phi
- d_theta = p_area / d_phi
-
- for mphi in range(m_phi):
- phi = numpy.pi * (mphi + 0.5) / m_phi
- m_theta = int(round(2 * numpy.pi * numpy.sin(phi) / d_phi))
-
- for mtheta in range(m_theta):
- theta = 2 * numpy.pi * mtheta / m_theta
- x = radius * numpy.cos(theta) * numpy.sin(phi)
- y = radius * numpy.sin(theta) * numpy.sin(phi)
- z = radius * numpy.cos(phi)
- if geometry.inside((x, y, z), False):
- if transform is None:
- point = [x, y, z]
- else:
- point = transform([x, y, z])
- if not isinstance(point, numpy.ndarray):
- point = numpy.array(point)
- domain.add_point(point + self.center, **kwargs)
- count += 1
- radius -= self.deltar
+ if approx_rc == 0:
+ from spatialpy.core import log # pylint: disable=import-outside-toplevel
+ msg = f"Approximation of particles for the layer at radius {radius} is 0. "
+ msg += "Consider increasing the radius or increasing the radial spacing (deltas)"
+ log.warning(msg)
+ else:
+ # Set constants for the radius
+ p_area = 4 * numpy.pi * radius ** 2 / approx_rc
+ d_a = numpy.sqrt(p_area)
+ m_phi = int(round(numpy.pi * radius / d_a))
+ d_phi = numpy.pi / m_phi
+ d_theta = p_area / d_phi
+
+ for mphi in range(m_phi):
+ phi = numpy.pi * (mphi + 0.5) / m_phi
+ m_theta = int(round(2 * numpy.pi * numpy.sin(phi) / d_phi))
+
+ for mtheta in range(m_theta):
+ theta = 2 * numpy.pi * mtheta / m_theta
+ x = radius * numpy.cos(theta) * numpy.sin(phi)
+ y = radius * numpy.sin(theta) * numpy.sin(phi)
+ z = radius * numpy.cos(phi)
+ if geometry.inside((x, y, z), False):
+ if transform is None:
+ point = [x, y, z]
+ else:
+ point = transform([x, y, z])
+ if not isinstance(point, numpy.ndarray):
+ point = numpy.array(point)
+ domain.add_point(point + self.center, **kwargs)
+ count += 1
+ radius = round(radius - self.deltar, digits)
+ if radius == 0 and geometry.inside((0, 0, 0), False):
+ point = [0, 0, 0] if transform is None else transform([0, 0, 0])
+ if not isinstance(point, numpy.ndarray):
+ point = numpy.array(point)
+ domain.add_point(point + self.center, **kwargs)
+ count += 1
self._update_limits(domain)
if 'vol' not in kwargs:
offset = len(domain.vertices) - count
@@ -443,7 +480,7 @@ Source code for spatialpy.core.lattice
return count
[docs] def validate(self):
- """
+ """
Validate the spherical lattice dependencies.
"""
super().validate()
@@ -462,7 +499,7 @@ Source code for spatialpy.core.lattice
raise LatticeError("deltar must be greater than 0.")
[docs]class CylindricalLattice(Lattice):
- """
+ """
Cylindrical lattice class provides a method for creating parts of the spatial
domain within a cylindrical coordinate system.
@@ -484,7 +521,7 @@ Source code for spatialpy.core.lattice
:raises LatticeError: if center is not and list, doesn't contain 3 values,
or any value is not a float.
"""
- def __init__(self, radius, length, deltas, center=None, deltar=None):
+ def __init__(self, radius, length, deltas, center=None, deltar=None):
super().__init__(center, skip_validate=True)
self.radius = radius
@@ -499,7 +536,7 @@ Source code for spatialpy.core.lattice
self.validate()
[docs] def apply(self, domain, geometry, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the cylindrical lattice restricted by the geometry.
:param domain: Domain particles are to be added to.
@@ -514,7 +551,7 @@ Source code for spatialpy.core.lattice
:param \**kwargs: Additional keyword arguments passed to :py:meth:`Domain.add_point`.
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if not (isinstance(geometry, (Geometry, CombinatoryGeometry)) or \
@@ -525,38 +562,57 @@ Source code for spatialpy.core.lattice
if transform is not None and not callable(transform):
raise LatticeError("transform must be a function.")
+ digits = max(
+ len(str(self.deltar).split(".")[1]) if "." in str(self.deltar) else 0,
+ len(str(self.radius).split(".")[1]) if "." in str(self.radius) else 0
+ )
count = 0
h_len = self.length / 2
xmin = -h_len
xmax = h_len
radius = self.radius
- while radius >= 0:
+ while radius > 0:
# Calculate the approximate number of particle with the radius
approx_rc = int(round((2 * radius * self.length) / ((self.deltas / 2) ** 2)))
- p_area = 2 * numpy.pi * radius * self.length / approx_rc
- d_a = numpy.sqrt(p_area)
- m_theta = int(round(2 * numpy.pi * radius / d_a))
- d_theta = 2 * numpy.pi / m_theta
-
+ if approx_rc == 0:
+ from spatialpy.core import log # pylint: disable=import-outside-toplevel
+ msg = f"Approximation of particles for the layer at radius {radius} is 0. "
+ msg += "Consider increasing the radius or increasing the radial spacing (deltas)"
+ log.warning(msg)
+ else:
+ p_area = 2 * numpy.pi * radius * self.length / approx_rc
+ d_a = numpy.sqrt(p_area)
+ m_theta = int(round(2 * numpy.pi * radius / d_a))
+ d_theta = 2 * numpy.pi / m_theta
+
+ x = xmin
+ while x <= xmax:
+ for mtheta in range(m_theta):
+ theta = 2 * numpy.pi * (mtheta + 0.5) / m_theta
+ y = radius * numpy.cos(theta)
+ z = radius * numpy.sin(theta)
+ if geometry.inside((x, y, z), False):
+ if transform is None:
+ point = [x, y, z]
+ else:
+ point = transform([x, y, z])
+ if not isinstance(point, numpy.ndarray):
+ point = numpy.array(point)
+ domain.add_point(point + self.center, **kwargs)
+ count += 1
+ x += self.deltas
+ radius = round(radius - self.deltar, digits)
+ if radius == 0:
x = xmin
while x <= xmax:
-
- for mtheta in range(m_theta):
- theta = 2 * numpy.pi * (mtheta + 0.5) / m_theta
- y = radius * numpy.cos(theta)
- z = radius * numpy.sin(theta)
- if geometry.inside((x, y, z), False):
- if transform is None:
- point = [x, y, z]
- else:
- point = transform([x, y, z])
- if not isinstance(point, numpy.ndarray):
- point = numpy.array(point)
- domain.add_point(point + self.center, **kwargs)
- count += 1
+ if geometry.inside((x, 0, 0), False):
+ point = [x, 0, 0] if transform is None else transform([x, 0, 0])
+ if not isinstance(point, numpy.ndarray):
+ point = numpy.array(point)
+ domain.add_point(point + self.center, **kwargs)
+ count += 1
x += self.deltas
- radius -= self.deltar
self._update_limits(domain)
if 'vol' not in kwargs:
offset = len(domain.vertices) - count
@@ -568,7 +624,7 @@ Source code for spatialpy.core.lattice
return count
[docs] def validate(self):
- """
+ """
Validate the cylindrical lattice dependencies.
"""
super().validate()
@@ -591,10 +647,10 @@ Source code for spatialpy.core.lattice
raise LatticeError("deltar must be greater than 0.")
[docs]class XMLMeshLattice(Lattice):
- """
+ """
XML mesh lattice class provides a method for creating parts of the spatial
domain with a mesh defined by a FEniCS/dolfin style XML mesh file.
-
+
:param center: The center point of the lattice.
:type center: float[3] | float(3)
@@ -607,7 +663,7 @@ Source code for spatialpy.core.lattice
:param type_ids: Mapping of type indices to type names (optional).
:type type_ids: dict{str:str}
"""
- def __init__(self, filename, center=None, subdomain_file=None, type_ids=None):
+ def __init__(self, filename, center=None, subdomain_file=None, type_ids=None):
super().__init__(center, skip_validate=True)
self.filename = filename
@@ -625,14 +681,14 @@ Source code for spatialpy.core.lattice
if self.type_ids is not None:
type_id = self.type_ids[type_id]
- type_ids[int(ndx)] = f"type_{type_id}"
+ type_ids[int(ndx)] = type_id
except ValueError as err:
- errmsg = f"Could not read in subdomain file, error on line {lnum}: {line}"
+ errmsg = f"Could not read in subdomain file, error on line {lnum}: {line}"
raise LatticeError(errmsg) from err
return type_ids
[docs] def apply(self, domain, *args, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the xml mesh lattice un-restricted by a geometry.
:param domain: Domain particles are to be added to.
@@ -643,7 +699,7 @@ Source code for spatialpy.core.lattice
:param \**kwargs: Additional keyword arguments passed to :py:meth:`Domain.add_point`.
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if transform is not None and not callable(transform):
@@ -656,7 +712,7 @@ Source code for spatialpy.core.lattice
root = ET.parse(self.filename).getroot()
if not root.tag == 'dolfin':
- raise LatticeError(f"{self.filename} is not a FEniCS/dolfin xml mesh.")
+ raise LatticeError(f"{self.filename} is not a FEniCS/dolfin xml mesh.")
mesh = root[0]
if mesh.tag != 'mesh' or mesh.attrib['celltype'] != 'tetrahedron' or mesh.attrib['dim'] != '3':
@@ -680,7 +736,7 @@ Source code for spatialpy.core.lattice
point = [x, y, z]
else:
point = transform([x, y, z])
- if type_ids is not None and i in type_ids.keys():
+ if type_ids is not None and i in type_ids:
kwargs['type_id'] = type_ids[i]
if not isinstance(point, numpy.ndarray):
point = numpy.array(point)
@@ -707,7 +763,7 @@ Source code for spatialpy.core.lattice
return count
[docs] def validate(self):
- """
+ """
Validate the XML mesh lattice dependencies.
"""
super().validate()
@@ -724,13 +780,13 @@ Source code for spatialpy.core.lattice
raise LatticeError("Values in type_ids must be of type str.")
for char in name:
if (char in string.punctuation and char != "_") or char == " ":
- raise LatticeError(f"Values in type_ids cannot contain '{char}'")
+ raise LatticeError(f"Values in type_ids cannot contain '{char}'")
[docs]class MeshIOLattice(Lattice):
- """
+ """
meshio lattice class provides a method for creating parts of the spatial
domain with a mesh defined by a Gmsh style .msh mesh file.
-
+
:param center: The center point of the lattice.
:type center: float[3] | float(3)
@@ -743,7 +799,7 @@ Source code for spatialpy.core.lattice
:param type_ids: Mapping of type indices to type names (optional).
:type type_ids: dict{str:str}
"""
- def __init__(self, filename=None, center=None, mesh=None, subdomain_file=None, type_ids=None):
+ def __init__(self, filename=None, center=None, mesh=None, subdomain_file=None, type_ids=None):
super().__init__(center, skip_validate=True)
self.filename = filename
@@ -762,14 +818,14 @@ Source code for spatialpy.core.lattice
if self.type_ids is not None:
type_id = self.type_ids[type_id]
- type_ids[int(ndx)] = f"type_{type_id}"
+ type_ids[int(ndx)] = type_id
except ValueError as err:
- errmsg = f"Could not read in subdomain file, error on line {lnum}: {line}"
+ errmsg = f"Could not read in subdomain file, error on line {lnum}: {line}"
raise LatticeError(errmsg) from err
return type_ids
[docs] def apply(self, domain, *args, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the mesh IO lattice un-restricted by a geometry.
:param domain: Domain particles are to be added to.
@@ -780,7 +836,7 @@ Source code for spatialpy.core.lattice
:param \**kwargs: Additional keyword arguments passed to :py:meth:`Domain.add_point`.
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if transform is not None and not callable(transform):
@@ -795,7 +851,7 @@ Source code for spatialpy.core.lattice
mesh = meshio.read(self.filename)
else:
mesh = self.mesh
-
+
if self.subdomain_file is not None:
type_ids = self.__get_types()
else:
@@ -812,7 +868,7 @@ Source code for spatialpy.core.lattice
point = [x, y, z]
else:
point = transform([x, y, z])
- if type_ids is not None and i in type_ids.keys():
+ if type_ids is not None and i in type_ids:
kwargs['type_id'] = type_ids[i]
if not isinstance(point, numpy.ndarray):
point = numpy.array(point)
@@ -828,7 +884,7 @@ Source code for spatialpy.core.lattice
for triangle in triangles[0].data:
triangle = triangle + num_points
domain.triangles = numpy.append(domain.triangles, [triangle], axis=0)
-
+
#tetrahedrons
tetras = list(filter(lambda cell: cell.type == "tetra", mesh.cells))
if tetras:
@@ -842,7 +898,7 @@ Source code for spatialpy.core.lattice
return count
[docs] def validate(self):
- """
+ """
Validate the meshio lattice dependencies.
"""
super().validate()
@@ -861,20 +917,20 @@ Source code for spatialpy.core.lattice
raise LatticeError("Values in type_ids must be of type str.")
for char in name:
if (char in string.punctuation and char != "_") or char == " ":
- raise LatticeError(f"Values in type_ids cannot contain '{char}'")
+ raise LatticeError(f"Values in type_ids cannot contain '{char}'")
[docs]class StochSSLattice(Lattice):
- """
+ """
stochss lattice class provides a method for creating parts of the spatial domain
with a domain defined by a stochss style .domn domain file or .smdl model file.
-
+
:param center: The center point of the lattice.
:type center: float[3] | float(3)
:param filename: Name of file to read.
:type filename: str
"""
- def __init__(self, filename, center=None):
+ def __init__(self, filename, center=None):
super().__init__(center, skip_validate=True)
self.filename = filename
@@ -882,7 +938,7 @@ Source code for spatialpy.core.lattice
self.validate()
[docs] def apply(self, domain, *args, transform=None, **kwargs):
- """
+ """
Fill a domain with particles within the stochss lattice un-restricted by a geometry.
:param domain: Domain particles are to be added to.
@@ -891,7 +947,7 @@ Source code for spatialpy.core.lattice
:param transform: Transformation function applied to each particle.
:type transform: function
"""
- from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
+ from spatialpy.core.domain import Domain # pylint: disable=import-outside-toplevel
if not (isinstance(domain, Domain) or type(domain).__name__ == 'Domain'):
raise LatticeError("domain must be of type spatialpy.Domain.")
if transform is not None and not callable(transform):
@@ -907,7 +963,7 @@ Source code for spatialpy.core.lattice
domain.c0 = s_domain['c_0']
domain.P0 = s_domain['p_0']
domain.gravity = s_domain['gravity']
-
+
type_ids = {}
for s_type in s_domain['types']:
type_ids[s_type['typeID']] = s_type['name'].replace('-', '')
@@ -942,7 +998,7 @@ Source code for spatialpy.core.lattice
raise LatticeError("The file is not a StochSS Domain (.domn) or a StochSS Spatial Model (.smdl).") from err
[docs] def validate(self):
- """
+ """
Validate the stochss lattice dependencies.
"""
super().validate()
@@ -968,8 +1024,8 @@ Source code for spatialpy.core.lattice
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/model.html b/docs/build/html/_modules/spatialpy/core/model.html
index 46852900..85054149 100644
--- a/docs/build/html/_modules/spatialpy/core/model.html
+++ b/docs/build/html/_modules/spatialpy/core/model.html
@@ -5,14 +5,16 @@
- spatialpy.core.model — SpatialPy 1.1.0 documentation
+ spatialpy.core.model — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -110,30 +112,30 @@ Source code for spatialpy.core.model
#This module defines a model that simulates a discrete, stoachastic, mixed biochemical reaction network in python.
import math
-from typing import Set, Type
-from collections import OrderedDict
+from typing import Set, Type
+from collections import OrderedDict
import numpy
import scipy
-from spatialpy.core.domain import Domain
-from spatialpy.core.species import Species
-from spatialpy.core.initialcondition import (
+from spatialpy.core.domain import Domain
+from spatialpy.core.species import Species
+from spatialpy.core.initialcondition import (
InitialCondition,
PlaceInitialCondition,
ScatterInitialCondition,
UniformInitialCondition
)
-from spatialpy.core.parameter import Parameter
-from spatialpy.core.reaction import Reaction
-from spatialpy.core.boundarycondition import BoundaryCondition
-from spatialpy.core.datafunction import DataFunction
-from spatialpy.core.timespan import TimeSpan
-from spatialpy.solvers.build_expression import BuildExpression
-from spatialpy.core.spatialpyerror import ModelError
+from spatialpy.core.parameter import Parameter
+from spatialpy.core.reaction import Reaction
+from spatialpy.core.boundarycondition import BoundaryCondition
+from spatialpy.core.datafunction import DataFunction
+from spatialpy.core.timespan import TimeSpan
+from spatialpy.solvers.build_expression import BuildExpression
+from spatialpy.core.spatialpyerror import ModelError
[docs]def export_StochSS(spatialpy_model, filename=None, return_stochss_model=False):
- """
+ """
SpatialPy model to StochSS converter
:param spatialpy_model: SpatialPy model to be converted to StochSS
@@ -149,14 +151,14 @@ Source code for spatialpy.core.model
:rtype: string
"""
try:
- from spatialpy.stochss.stochss_export import export # pylint: disable=import-outside-toplevel
+ from spatialpy.stochss.stochss_export import export # pylint: disable=import-outside-toplevel
except ImportError as err:
raise ImportError('StochSS export conversion not imported successfully') from err
return export(spatialpy_model, path=filename, return_stochss_model=return_stochss_model)
[docs]class Model():
- """
+ """
Representation of a spatial biochemical model.
:param name: Name of the model
@@ -165,7 +167,7 @@ Source code for spatialpy.core.model
reserved_names = ['vol', 't']
special_characters = ['[', ']', '+', '-', '*', '/', '.', '^']
- def __init__(self, name="spatialpy"):
+ def __init__(self, name="spatialpy"):
# The name that the model is referenced by (should be a String)
self.name = name
@@ -212,61 +214,61 @@ Source code for spatialpy.core.model
self.expr = None
self.u0 = None
- def __str__(self):
+ def __str__(self):
try:
self.__update_diffusion_restrictions()
except Exception:
pass
self._resolve_all_parameters()
- divider = f"\n{'*'*10}\n"
+ divider = f"\n{'*'*10}\n"
def decorate(header):
- return f"\n{divider}{header}{divider}"
+ return f"\n{divider}{header}{divider}"
- print_string = f"{self.name}"
+ print_string = f"{self.name}"
if len(self.listOfSpecies):
print_string += decorate("Species")
for _, species in self.listOfSpecies.items():
- print_string += f"\n{str(species)}"
+ print_string += f"\n{str(species)}"
if self.listOfInitialConditions:
print_string += decorate("Initial Conditions")
for initial_condition in self.listOfInitialConditions:
- print_string += f"\n{str(initial_condition)}"
+ print_string += f"\n{str(initial_condition)}"
if len(self.listOfDiffusionRestrictions):
print_string += decorate("Diffusion Restrictions")
for species, types in self.listOfDiffusionRestrictions.items():
- print_string += f"\n{species.name} is restricted to: {str(types)}"
+ print_string += f"\n{species.name} is restricted to: {str(types)}"
if len(self.listOfParameters):
print_string += decorate("Parameters")
for _, parameter in self.listOfParameters.items():
- print_string += f"\n{str(parameter)}"
+ print_string += f"\n{str(parameter)}"
if len(self.listOfReactions):
print_string += decorate("Reactions")
for _, reaction in self.listOfReactions.items():
- print_string += f"\n{str(reaction)}"
+ print_string += f"\n{str(reaction)}"
print(print_string)
if self.domain is not None:
print(decorate("Domain"))
- print(f"\n{str(self.domain)}")
+ print(f"\n{str(self.domain)}")
return ""
- def __ne__(self, other):
+ def __ne__(self, other):
return not self.__eq__(other)
- def __eq__(self, other):
+ def __eq__(self, other):
return self.listOfParameters == other.listOfParameters and \
self.listOfSpecies == other.listOfSpecies and \
self.listOfReactions == other.listOfReactions and \
self.name == other.name
- def __getitem__(self, key):
+ def __getitem__(self, key):
if isinstance(key, str):
return self.get_element(key)
if hasattr(self.__class__, "__missing__"):
return self.__class__.__missing__(self, key)
- raise KeyError(f"{key} is an invalid key.")
+ raise KeyError(f"{key} is an invalid key.")
def __apply_initial_conditions(self):
# initalize
@@ -387,21 +389,21 @@ Source code for spatialpy.core.model
names = Model.reserved_names
if name in Model.reserved_names:
raise ModelError(
- f'Name "{name}" is unavailable. It is reserved for internal GillesPy use. Reserved Names: ({names}).'
+ f'Name "{name}" is unavailable. It is reserved for internal GillesPy use. Reserved Names: ({names}).'
)
if name in self.listOfSpecies:
- raise ModelError(f'Name "{name}" is unavailable. A species with that name exists.')
+ raise ModelError(f'Name "{name}" is unavailable. A species with that name exists.')
if name in self.listOfParameters:
- raise ModelError(f'Name "{name}" is unavailable. A parameter with that name exists.')
+ raise ModelError(f'Name "{name}" is unavailable. A parameter with that name exists.')
if name in self.listOfReactions:
- raise ModelError(f'Name "{name}" is unavailable. A reaction with that name exists.')
+ raise ModelError(f'Name "{name}" is unavailable. A reaction with that name exists.')
if name.isdigit():
- raise ModelError(f'Name "{name}" is unavailable. Names must not be numeric strings.')
+ raise ModelError(f'Name "{name}" is unavailable. Names must not be numeric strings.')
for special_character in Model.special_characters:
if special_character in name:
chars = Model.special_characters
raise ModelError(
- f'Name "{name}" is unavailable. Names must not contain special characters: {chars}.'
+ f'Name "{name}" is unavailable. Names must not contain special characters: {chars}.'
)
def _resolve_parameter(self, parameter):
@@ -411,7 +413,7 @@ Source code for spatialpy.core.model
parameter._evaluate(self.namespace) # pylint: disable=protected-access
except ModelError as err:
raise ModelError(
- f"Could not add/resolve parameter: {parameter.name}, Reason given: {err}"
+ f"Could not add/resolve parameter: {parameter.name}, Reason given: {err}"
) from err
def _resolve_all_parameters(self):
@@ -446,14 +448,14 @@ Source code for spatialpy.core.model
reaction.products[stoich_spec] = stoichiometry
del reaction.products[species]
except ModelError as err:
- raise ModelError(f"Could not add/resolve reaction: {reaction.name}, Reason given: {err}") from err
+ raise ModelError(f"Could not add/resolve reaction: {reaction.name}, Reason given: {err}") from err
def _resolve_all_reactions(self):
for _, reaction in self.listOfReactions.items():
self._resolve_reaction(reaction)
[docs] def update_namespace(self):
- """
+ """
Create a dict with flattened parameter and species objects.
"""
self.namespace = OrderedDict([])
@@ -461,7 +463,7 @@ Source code for spatialpy.core.model
self.namespace[param] = self.listOfParameters[param].value
[docs] def add(self, components):
- """
+ """
Adds a component, or list of components to the model. If a list is provided, Species
and Parameters are added before other components. Lists may contain any combination
of accepted types other than lists and do not need to be in any particular order.
@@ -513,11 +515,11 @@ Source code for spatialpy.core.model
elif isinstance(components, TimeSpan) or type(components).__name__ == TimeSpan.__name__:
self.timespan(components)
else:
- raise ModelError(f"Unsupported component: {type(components)} is not a valid component.")
+ raise ModelError(f"Unsupported component: {type(components)} is not a valid component.")
return components
[docs] def get_element(self, name):
- """
+ """
Get a model element specified by name.
:param name: Name of the element to be returned.
@@ -538,10 +540,10 @@ Source code for spatialpy.core.model
return self.get_reaction(name)
if name in self.listOfDataFunctions:
return self.get_data_function(name)
- raise ModelError(f"{self.name} does not contain an element named {name}.")
+ raise ModelError(f"{self.name} does not contain an element named {name}.")
-[docs] def add_domain(self, domain):
- """
+[docs] def add_domain(self, domain, allow_all_types=False):
+ """
Add a spatial domain to the model
:param domain: The Domain object to be added to the model
@@ -554,12 +556,12 @@ Source code for spatialpy.core.model
"Unexpected parameter for add_domain. Parameter must be of type SpatialPy.Domain."
)
- domain.compile_prep()
+ domain.compile_prep(allow_all_types=allow_all_types)
self.domain = domain
return domain
[docs] def add_species(self, species):
- """
+ """
Adds a species, or list of species to the model.
:param species: The species or list of species to be added to the model object.
@@ -579,17 +581,17 @@ Source code for spatialpy.core.model
self._problem_with_name(species.name)
self.species_map[species] = self.get_num_species()
self.listOfSpecies[species.name] = species
- self._listOfSpecies[species.name] = f'S{len(self._listOfSpecies)}'
+ self._listOfSpecies[species.name] = f'S{len(self._listOfSpecies)}'
except ModelError as err:
- errmsg = f"Could not add species: {species.name}, Reason given: {err}"
+ errmsg = f"Could not add species: {species.name}, Reason given: {err}"
raise ModelError(errmsg) from err
else:
- errmsg = f"species must be of type Species or list of Species not {type(species)}"
+ errmsg = f"species must be of type Species or list of Species not {type(species)}"
raise ModelError(errmsg)
return species
[docs] def delete_species(self, name):
- """
+ """
Removes a species object by name.
:param name: Name of the species object to be removed
@@ -603,18 +605,18 @@ Source code for spatialpy.core.model
self._listOfSpecies.pop(name)
except KeyError as err:
raise ModelError(
- f"{self.name} does not contain a species named {name}."
+ f"{self.name} does not contain a species named {name}."
) from err
[docs] def delete_all_species(self):
- """
+ """
Removes all species from the model object.
"""
self.listOfSpecies.clear()
self._listOfSpecies.clear()
[docs] def get_species(self, name):
- """
+ """
Returns a species object by name.
:param name: Name of the species object to be returned.
@@ -626,11 +628,11 @@ Source code for spatialpy.core.model
:raises ModelError: If the species is not part of the model.
"""
if name not in self.listOfSpecies:
- raise ModelError(f"Species {name} could not be found in the model.")
+ raise ModelError(f"Species {name} could not be found in the model.")
return self.listOfSpecies[name]
[docs] def get_all_species(self):
- """
+ """
Returns a dictionary of all species in the model using names as keys.
:returns: A dict of all species in the model, in the form: {name : species object}.
@@ -639,7 +641,7 @@ Source code for spatialpy.core.model
return self.listOfSpecies
[docs] def get_num_species(self):
- """
+ """
Returns total number of different species contained in the model.
:returns: Number of different species in the model.
@@ -648,7 +650,7 @@ Source code for spatialpy.core.model
return len(self.listOfSpecies)
[docs] def sanitized_species_names(self):
- """
+ """
Generate a dictionary mapping user chosen species names to simplified formats which will be used
later on by SpatialPySolvers evaluating reaction propensity functions.
@@ -657,11 +659,11 @@ Source code for spatialpy.core.model
"""
species_name_mapping = OrderedDict([])
for i, name in enumerate(self.listOfSpecies.keys()):
- species_name_mapping[name] = f'x[{i}]'
+ species_name_mapping[name] = f'x[{i}]'
return species_name_mapping
[docs] def add_initial_condition(self, init_cond):
- """
+ """
Add an initial condition object to the initialization of the model.
:param init_cond: Initial condition to be added.
@@ -684,12 +686,12 @@ Source code for spatialpy.core.model
elif isinstance(init_cond, InitialCondition) or type(init_cond).__name__ in names:
self.listOfInitialConditions.append(init_cond)
else:
- errmsg = f"init_cond must be of type InitialCondition or list of InitialCondition not {type(init_cond)}"
+ errmsg = f"init_cond must be of type InitialCondition or list of InitialCondition not {type(init_cond)}"
raise ModelError(errmsg)
return init_cond
[docs] def delete_initial_condition(self, init_cond):
- """
+ """
Removes an initial condition object from the model object.
:param init_cond: initial condition object to be removed.
@@ -702,17 +704,17 @@ Source code for spatialpy.core.model
self.listOfInitialConditions.pop(index)
except ValueError as err:
raise ModelError(
- f"{self.name} does not contain this initial condition."
+ f"{self.name} does not contain this initial condition."
) from err
[docs] def delete_all_initial_conditions(self):
- """
+ """
Removes all initial conditions from the model object.
"""
self.listOfInitialConditions.clear()
[docs] def get_all_initial_conditions(self):
- """
+ """
Returns a list of all initial conditions in the model.
:returns: A list of all initial conditions in the model.
@@ -721,7 +723,7 @@ Source code for spatialpy.core.model
return self.listOfInitialConditions
[docs] def add_parameter(self, parameters):
- """
+ """
Adds a parameter, or list of parameters to the model.
:param parameters: The parameter or list of parameters to be added to the model object.
@@ -739,14 +741,14 @@ Source code for spatialpy.core.model
self._problem_with_name(parameters.name)
self._resolve_parameter(parameters)
self.listOfParameters[parameters.name] = parameters
- self._listOfParameters[parameters.name] = f'P{len(self._listOfParameters)}'
+ self._listOfParameters[parameters.name] = f'P{len(self._listOfParameters)}'
else:
- errmsg = f"parameters must be of type Parameter or list of Parameter not {type(parameters)}"
+ errmsg = f"parameters must be of type Parameter or list of Parameter not {type(parameters)}"
raise ModelError(errmsg)
return parameters
[docs] def delete_parameter(self, name):
- """
+ """
Removes a parameter object by name.
:param name: Name of the parameter object to be removed.
@@ -758,18 +760,18 @@ Source code for spatialpy.core.model
self._listOfParameters.pop(name)
except KeyError as err:
raise ModelError(
- f"{self.name} does not contain a parameter named {name}"
+ f"{self.name} does not contain a parameter named {name}"
) from err
[docs] def delete_all_parameters(self):
- """
+ """
Removes all parameters from model object.
"""
self.listOfParameters.clear()
self._listOfParameters.clear()
[docs] def get_parameter(self, name):
- """
+ """
Returns a parameter object by name.
:param name: Name of the parameter object to be returned
@@ -781,11 +783,11 @@ Source code for spatialpy.core.model
:raises ModelError: If the parameter is not part of the model.
"""
if name not in self.listOfParameters:
- raise ModelError(f"Parameter {name} could not be found in the model.")
+ raise ModelError(f"Parameter {name} could not be found in the model.")
return self.listOfParameters[name]
[docs] def get_all_parameters(self):
- """
+ """
Return a dictionary of all model parameters, indexed by name.
:returns: A dict of all parameters in the model, in the form: {name : parameter object}
@@ -794,7 +796,7 @@ Source code for spatialpy.core.model
return self.listOfParameters
[docs] def sanitized_parameter_names(self):
- """
+ """
Generate a dictionary mapping user chosen parameter names to simplified formats which will be used
later on by SpatialPySolvers evaluating reaction propensity functions.
@@ -804,11 +806,11 @@ Source code for spatialpy.core.model
parameter_name_mapping = OrderedDict()
for i, name in enumerate(self.listOfParameters.keys()):
if name not in parameter_name_mapping:
- parameter_name_mapping[name] = f'P{i}'
+ parameter_name_mapping[name] = f'P{i}'
return parameter_name_mapping
[docs] def add_reaction(self, reactions):
- """
+ """
Adds a reaction, or list of reactions to the model.
:param reactions: The reaction or list of reactions to be added to the model object
@@ -832,12 +834,12 @@ Source code for spatialpy.core.model
)
self._listOfReactions[reactions.name] = sanitized_reaction
else:
- errmsg = f"reactions must be of type Reaction or list of Reaction not {type(reactions)}"
+ errmsg = f"reactions must be of type Reaction or list of Reaction not {type(reactions)}"
raise ModelError(errmsg)
return reactions
[docs] def delete_reaction(self, name):
- """
+ """
Removes a reaction object by name.
:param name: Name of the reaction object to be removed.
@@ -849,18 +851,18 @@ Source code for spatialpy.core.model
self._listOfReactions.pop(name)
except KeyError as err:
raise ModelError(
- f"{self.name} does not contain a reaction named {name}"
+ f"{self.name} does not contain a reaction named {name}"
) from err
[docs] def delete_all_reactions(self):
- """
+ """
Removes all reactions from the model object.
"""
self.listOfReactions.clear()
self._listOfReactions.clear()
-[docs] def get_reaction(self, rname):
- """
+[docs] def get_reaction(self, name):
+ """
Returns a reaction object by name.
:param name: Name of the reaction object to be returned
@@ -872,11 +874,11 @@ Source code for spatialpy.core.model
:raises ModelError: If the reaction is not part of the model.
"""
if name not in self.listOfReactions:
- raise ModelError(f"Reaction {name} could not be found in the model.")
+ raise ModelError(f"Reaction {name} could not be found in the model.")
return self.listOfReactions[name]
[docs] def get_all_reactions(self):
- """
+ """
Returns a dictionary of all model reactions using names as keys.
:returns: A dict of all reaction in the model, in the form: {name : reaction object}.
@@ -885,7 +887,7 @@ Source code for spatialpy.core.model
return self.listOfReactions
[docs] def get_num_reactions(self):
- """
+ """
Returns the number of reactions in this model.
:returns: The total number of different reactions in the model.
@@ -894,7 +896,7 @@ Source code for spatialpy.core.model
return len(self.listOfReactions)
[docs] def add_boundary_condition(self, bound_cond):
- """
+ """
Add an boundary condition object to the model.
:param bound_cond: Boundary condition to be added
@@ -913,12 +915,12 @@ Source code for spatialpy.core.model
bound_cond.model = self
self.listOfBoundaryConditions.append(bound_cond)
else:
- errmsg = f"bound_cond must be of type BoundaryCondition or list of BoundaryCondition not {type(bound_cond)}"
+ errmsg = f"bound_cond must be of type BoundaryCondition or list of BoundaryCondition not {type(bound_cond)}"
raise ModelError(errmsg)
return bound_cond
[docs] def delete_boundary_condition(self, bound_cond):
- """
+ """
Removes an boundary condition object from the model object.
:param bound_cond: boundary condition object to be removed.
@@ -931,17 +933,17 @@ Source code for spatialpy.core.model
self.listOfBoundaryConditions.pop(index)
except ValueError as err:
raise ModelError(
- f"{self.name} does not contain this boundary condition."
+ f"{self.name} does not contain this boundary condition."
) from err
[docs] def delete_all_boundary_conditions(self):
- """
+ """
Removes all boundary conditions from the model object.
"""
self.listOfBoundaryConditions.clear()
[docs] def get_all_boundary_conditions(self):
- """
+ """
Returns a list of all boundary conditions in the model.
:returns: A list of all boundary conditions in the model.
@@ -950,7 +952,7 @@ Source code for spatialpy.core.model
return self.listOfBoundaryConditions
[docs] def add_data_function(self, data_function):
- """
+ """
Add a scalar spatial function to the simulation. This is useful if you have a
spatially varying input to your model. Argument is a instances of subclass of the
spatialpy.DataFunction class. It must implement a function 'map(point)' which takes a
@@ -971,12 +973,12 @@ Source code for spatialpy.core.model
self._problem_with_name(data_function.name)
self.listOfDataFunctions[data_function.name] = data_function
else:
- errmsg = f"data_function must be of type DataFunction or list of DataFunction not {type(data_function)}"
+ errmsg = f"data_function must be of type DataFunction or list of DataFunction not {type(data_function)}"
raise ModelError(errmsg)
return data_function
[docs] def delete_data_function(self, name):
- """
+ """
Removes an data function object from the model object.
:param name: data function object to be removed.
@@ -988,17 +990,17 @@ Source code for spatialpy.core.model
self.listOfDataFunctions.pop(name)
except ValueError as err:
raise ModelError(
- f"{self.name} does not contain a data function named {name}."
+ f"{self.name} does not contain a data function named {name}."
) from err
[docs] def delete_all_data_functions(self):
- """
+ """
Removes all data functions from the model object.
"""
self.listOfDataFunctions.clear()
[docs] def get_data_function(self, name):
- """
+ """
Returns a data function object by name.
:param name: Name of the data function object to be returned
@@ -1010,11 +1012,11 @@ Source code for spatialpy.core.model
:raises ModelError: If the data function is not part of the model.
"""
if name not in self.listOfDataFunctions:
- raise ModelError(f"Data function {name} could not be found in the model.")
+ raise ModelError(f"Data function {name} could not be found in the model.")
return self.listOfDataFunctions[name]
[docs] def get_all_data_functions(self):
- """
+ """
Returns a dict of all data functions in the model.
:returns: A dict of all data functions in the model.
@@ -1023,7 +1025,7 @@ Source code for spatialpy.core.model
return self.listOfDataFunctions
[docs] def sanitized_data_function_names(self):
- """
+ """
Generate a dictionary mapping user chosen data function names to simplified formats which will be used
later on by SpatialPySolvers evaluating reaction propensity functions.
@@ -1032,11 +1034,11 @@ Source code for spatialpy.core.model
"""
data_fn_name_mapping = OrderedDict([])
for i, name in enumerate(self.listOfDataFunctions.keys()):
- data_fn_name_mapping[name] = f'data_fn[{i}]'
+ data_fn_name_mapping[name] = f'data_fn[{i}]'
return data_fn_name_mapping
[docs] def set_timesteps(self, output_interval, num_steps, timestep_size=None):
- """
+ """
Set the simlation time span parameters.
:param output_interval: size of each output timestep in seconds
@@ -1054,7 +1056,7 @@ Source code for spatialpy.core.model
)
[docs] def timespan(self, time_span, timestep_size=None):
- """
+ """
Set the time span of simulation. The SSA-SDPD engine does not support
non-uniform timespans.
@@ -1072,8 +1074,8 @@ Source code for spatialpy.core.model
else:
self.tspan = TimeSpan(time_span, timestep_size=timestep_size)
-[docs] def compile_prep(self):
- """
+[docs] def compile_prep(self, allow_all_types=False):
+ """
Make sure all paramters are evaluated to scalars, update the models diffusion restrictions,
create the models expression utility, and generate the domain list of type ids in preperation
of compiling the simulation files.
@@ -1086,11 +1088,11 @@ Source code for spatialpy.core.model
try:
self.tspan.validate(coverage="all")
except ModelError as err:
- raise ModelError(f"Failed to validate timespan. Reason given: {err}") from err
+ raise ModelError(f"Failed to validate timespan. Reason given: {err}") from err
if self.domain is None:
raise ModelError("The model's domain is not set. Use 'add_domain()'.")
- self.domain.compile_prep()
+ self.domain.compile_prep(allow_all_types=allow_all_types)
self.__update_diffusion_restrictions()
self.__apply_initial_conditions()
@@ -1102,7 +1104,7 @@ Source code for spatialpy.core.model
diff_coeff = species.diffusion_coefficient
if isinstance(diff_coeff, str):
if diff_coeff not in sanitized_params:
- raise ModelError(f"Parameterm {diff_coeff} doesn't exist.")
+ raise ModelError(f"Parameterm {diff_coeff} doesn't exist.")
species.diffusion_coefficient = sanitized_params[diff_coeff]
self.__get_expression_utility()
@@ -1113,7 +1115,7 @@ Source code for spatialpy.core.model
[docs] def run(self, number_of_trajectories=1, seed=None, timeout=None,
number_of_threads=None, debug_level=0, debug=False, profile=False):
- """
+ """
Simulate the model. Returns a result object containing simulation results.
:param number_of_trajectories: How many trajectories should be run.
@@ -1141,7 +1143,7 @@ Source code for spatialpy.core.model
:returns: A SpatialPy Result object containing simulation data.
:rtype: spatialpy.core.result.Result
"""
- from spatialpy.solvers.solver import Solver # pylint: disable=import-outside-toplevel
+ from spatialpy.solvers.solver import Solver # pylint: disable=import-outside-toplevel
sol = Solver(self, debug_level=debug_level)
@@ -1166,8 +1168,8 @@ Source code for spatialpy.core.model
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/parameter.html b/docs/build/html/_modules/spatialpy/core/parameter.html
index 72126344..f78c8bff 100644
--- a/docs/build/html/_modules/spatialpy/core/parameter.html
+++ b/docs/build/html/_modules/spatialpy/core/parameter.html
@@ -5,14 +5,16 @@
- spatialpy.core.parameter — SpatialPy 1.1.0 documentation
+ spatialpy.core.parameter — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -106,10 +108,10 @@ Source code for spatialpy.core.parameter
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
-from spatialpy.core.spatialpyerror import ParameterError
+from spatialpy.core.spatialpyerror import ParameterError
[docs]class Parameter():
- """
+ """
A parameter can be given as an expression (function) or directly
as a value (scalar). If given an expression, it should be
understood as evaluable in the namespace of a parent Model.
@@ -123,7 +125,7 @@ Source code for spatialpy.core.parameter
:raises ParameterError: Arg is of invalid type. Required arg set to None. Arg value is outside of accepted bounds.
"""
- def __init__(self, name=None, expression=None):
+ def __init__(self, name=None, expression=None):
# We allow expression to be passed in as a non-string type. Invalid strings
# will be caught below. It is perfectly fine to give a scalar value as the expression.
# This can then be evaluated in an empty namespace to the scalar value.
@@ -136,11 +138,11 @@ Source code for spatialpy.core.parameter
self.validate()
- def __str__(self):
- return f"{self.name}: {self.expression}"
+ def __str__(self):
+ return f"{self.name}: {self.expression}"
def _evaluate(self, namespace=None):
- """
+ """
Evaluate the expression and return the (scalar) value in the given
namespace.
@@ -162,11 +164,11 @@ Source code for spatialpy.core.parameter
self.value = float(eval(self.expression, namespace))
except Exception as err:
raise ParameterError(
- f"Could not evaluate expression: '{self.expression}'. Reason given: {err}."
+ f"Could not evaluate expression: '{self.expression}'. Reason given: {err}."
) from err
[docs] def validate(self, expression=None, coverage="all"):
- """
+ """
Validate the parameter.
:param expression: String for a function calculating parameter values. Should be
@@ -219,8 +221,8 @@ Source code for spatialpy.core.parameter
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/reaction.html b/docs/build/html/_modules/spatialpy/core/reaction.html
index 5705d7c4..ee89eac8 100644
--- a/docs/build/html/_modules/spatialpy/core/reaction.html
+++ b/docs/build/html/_modules/spatialpy/core/reaction.html
@@ -5,14 +5,16 @@
- spatialpy.core.reaction — SpatialPy 1.1.0 documentation
+ spatialpy.core.reaction — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -108,16 +110,16 @@ Source code for spatialpy.core.reaction
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ast
import uuid
-from json.encoder import JSONEncoder
+from json.encoder import JSONEncoder
import numpy as np
-from spatialpy.core.species import Species
-from spatialpy.core.parameter import Parameter
-from spatialpy.core.spatialpyerror import ReactionError
+from spatialpy.core.species import Species
+from spatialpy.core.parameter import Parameter
+from spatialpy.core.spatialpyerror import ReactionError
[docs]class Reaction():
- """
+ """
Models a biochemical reaction. A reaction conatains dictionaries of species
(reactants and products) and a parameters. The reaction's propensity functions
needs to be evaluable (and result in a non-negative scalar value) in the
@@ -165,11 +167,11 @@ Source code for spatialpy.core.reaction
model based on the order it was added. This could impact seeded simulation
results if the order of addition is not preserved.
"""
- def __init__(self, name=None, reactants=None, products=None, propensity_function=None,
+ def __init__(self, name=None, reactants=None, products=None, propensity_function=None,
ode_propensity_function=None, rate=None, annotation=None, restrict_to=None):
if name is None or name == "":
- name = f'rxn{uuid.uuid4()}'.replace('-', '_')
+ name = f'rxn{uuid.uuid4()}'.replace('-', '_')
if isinstance(propensity_function, (int, float)):
propensity_function = str(propensity_function)
if isinstance(ode_propensity_function, (int, float)):
@@ -193,18 +195,20 @@ Source code for spatialpy.core.reaction
if reactants is not None:
for r in reactants:
rtype = type(r).__name__
- if rtype == 'Species':
- self.reactants[r.name] = reactants[r]
+ name = r.name if rtype == 'Species' else r
+ if name in self.reactants:
+ self.reactants[name] += reactants[r]
else:
- self.reactants[r] = reactants[r]
-
+ self.reactants[name] = reactants[r]
+
if products is not None:
for p in products:
- rtype = type(p).__name__
- if rtype == 'Species':
- self.products[p.name] = products[p]
+ ptype = type(p).__name__
+ name = p.name if ptype == 'Species' else p
+ if name in self.products:
+ self.products[name] += products[p]
else:
- self.products[p] = products[p]
+ self.products[name] = products[p]
if self.marate is not None:
rtype = type(self.marate).__name__
@@ -227,11 +231,11 @@ Source code for spatialpy.core.reaction
if restrict_to is not None:
for type_id in restrict_to:
- self.restrict_to.append(f"type_{type_id}")
+ self.restrict_to.append(f"type_{type_id}")
self.validate(coverage="initialized")
- def __str__(self):
+ def __str__(self):
print_string = self.name
if len(self.reactants):
print_string += '\n\tReactants'
@@ -289,7 +293,7 @@ Source code for spatialpy.core.reaction
"ln": "log",
}
- def __init__(self):
+ def __init__(self):
self.string = ''
def _string_changer(self, addition):
@@ -349,7 +353,7 @@ Source code for spatialpy.core.reaction
self.generic_visit(node)
def _create_mass_action(self):
- """
+ """
Initializes the mass action propensity function given
self.reactants and a single parameter value.
"""
@@ -362,7 +366,7 @@ Source code for spatialpy.core.reaction
total_stoch += self.reactants[reactant]
if total_stoch > 2:
raise ReactionError(
- """
+ """
Reaction: A mass-action reaction cannot involve more than two of
one species or one of two species. To declare a custom propensity,
replace 'rate' with 'propensity_function'.
@@ -386,12 +390,12 @@ Source code for spatialpy.core.reaction
reactant = reactant.name
# Case 1: 2X -> Y
if stoichiometry == 2:
- propensity_function = f"0.5 * {propensity_function} * {reactant} * ({reactant} - 1) / vol"
- ode_propensity_function += f" * {reactant} * {reactant}"
+ propensity_function = f"{propensity_function} * {reactant} * ({reactant} - 1) / vol"
+ ode_propensity_function += f" * {reactant} * {reactant}"
else:
# Case 3: X1, X2 -> Y;
- propensity_function += f" * {reactant}"
- ode_propensity_function += f" * {reactant}"
+ propensity_function += f" * {reactant}"
+ ode_propensity_function += f" * {reactant}"
# Set the volume dependency based on order.
order = len(self.reactants)
@@ -413,14 +417,14 @@ Source code for spatialpy.core.reaction
return newFunc.string
def _create_sanitized_reaction(self, n_ndx, species_mappings, parameter_mappings):
- name = f"R{n_ndx}"
+ name = f"R{n_ndx}"
reactants = {species_mappings[species.name]: self.reactants[species] for species in self.reactants}
products = {species_mappings[species.name]: self.products[species] for species in self.products}
propensity_function = self.sanitized_propensity_function(species_mappings, parameter_mappings)
return Reaction(name=name, reactants=reactants, products=products, propensity_function=propensity_function)
[docs] def add_product(self, species, stoichiometry):
- """
+ """
Add a product to this reaction
:param species: Species object to be produced by the reaction
@@ -434,12 +438,15 @@ Source code for spatialpy.core.reaction
try:
self.validate(products={name: stoichiometry}, coverage="products")
except TypeError as err:
- raise ReactionError(f"Failed to validate product. Reason given: {err}") from err
+ raise ReactionError(f"Failed to validate product. Reason given: {err}") from err
- self.products[name] = stoichiometry
+ if name in self.products:
+ self.products[name] += stoichiometry
+ else:
+ self.products[name] = stoichiometry
[docs] def add_reactant(self, species, stoichiometry):
- """
+ """
Add a reactant to this reaction
:param species: reactant Species object
@@ -453,9 +460,12 @@ Source code for spatialpy.core.reaction
try:
self.validate(reactants={name: stoichiometry}, coverage="reactants")
except TypeError as err:
- raise ReactionError(f"Failed to validate reactant. Reason given: {err}") from err
+ raise ReactionError(f"Failed to validate reactant. Reason given: {err}") from err
- self.reactants[name] = stoichiometry
+ if name in self.reactants:
+ self.reactants[name] += stoichiometry
+ else:
+ self.reactants[name] = stoichiometry
if self.massaction and self.type == "mass-action":
self._create_mass_action()
@@ -488,7 +498,7 @@ Source code for spatialpy.core.reaction
return sanitized_propensity.format(*replacements)
[docs] def set_annotation(self, annotation):
- """
+ """
Add an annotation to this reaction.
:param annotation: Annotation note to be added to reaction
:type annotation: str
@@ -501,7 +511,7 @@ Source code for spatialpy.core.reaction
self.annotation = annotation
[docs] def set_propensities(self, propensity_function=None, ode_propensity_function=None):
- """
+ """
Change the reaction to a customized reaction and set the propensities.
:param propensity_function: The custom propensity function for the reaction. Must be evaluable in the
namespace of the reaction using C operations.
@@ -535,7 +545,7 @@ Source code for spatialpy.core.reaction
self.validate(coverage="initialized")
[docs] def set_rate(self, rate):
- """
+ """
Change the reaction to a mass-action reaction and set the rate.
:param rate: The rate of the mass-action reaction, take care to note the units.
:type rate: int | float | str | Parameter
@@ -571,7 +581,7 @@ Source code for spatialpy.core.reaction
[docs] def validate(self, coverage="build", reactants=None, products=None, propensity_function=None,
ode_propensity_function=None, marate=None, annotation=None, restrict_to=None):
- """
+ """
Validate the reaction.
:param reactants: The reactants that are consumed in the reaction, with stoichiometry. An
@@ -745,14 +755,14 @@ Source code for spatialpy.core.reaction
raise ReactionError(errmsg)
[docs] def annotate(self, *args, **kwargs):
- """
+ """
Add an annotation to this reaction (deprecated).
:param annotation: Annotation note to be added to reaction
:type annotation: str
"""
- from spatialpy.core import log
+ from spatialpy.core import log
log.warning(
- """
+ """
Reaction.Annotate has been deprecated. Future releases of SpatialPy may
not support this feature. Use Reaction.set_annotation instead.
"""
@@ -761,15 +771,15 @@ Source code for spatialpy.core.reaction
self.set_annotation(*args, **kwargs)
[docs] def initialize(self, model):
- """
+ """
Deferred object initialization, called by model.add_reaction() (deprecated).
:param model: Target SpatialPy Model for annotation.
:type model: spatialpy.core.model.Model
"""
- from spatialpy.core import log
+ from spatialpy.core import log
log.warning(
- """
+ """
Reaction.initialize has been deprecated. Future releases of SpatialPy may
not support this feature. Initialization of reactions is now completed in
the constructor.
@@ -794,8 +804,8 @@ Source code for spatialpy.core.reaction
©Copyright (C) 2019-2022.
|
- Powered by Sphinx 4.4.0
- & Alabaster 0.7.12
+ Powered by Sphinx 5.3.0
+ & Alabaster 0.7.13
diff --git a/docs/build/html/_modules/spatialpy/core/result.html b/docs/build/html/_modules/spatialpy/core/result.html
index 8e5ca966..d6232803 100644
--- a/docs/build/html/_modules/spatialpy/core/result.html
+++ b/docs/build/html/_modules/spatialpy/core/result.html
@@ -5,14 +5,16 @@
- spatialpy.core.result — SpatialPy 1.1.0 documentation
+ spatialpy.core.result — SpatialPy 1.2.0 documentation
+
+
@@ -73,7 +75,7 @@ Quick search
-
+
@@ -113,16 +115,16 @@ Source code for spatialpy.core.result
import shutil
import tempfile
-from collections import OrderedDict
+from collections import OrderedDict
import numpy
import plotly.graph_objs as go
-from plotly.offline import init_notebook_mode, iplot
+from plotly.offline import init_notebook_mode, iplot
# from spatialpy.core.model import *
-from spatialpy.core.visualization import Visualization
-from spatialpy.core.vtkreader import VTKReader
-from spatialpy.core.spatialpyerror import ResultError
+from spatialpy.core.visualization import Visualization
+from spatialpy.core.vtkreader import VTKReader
+from spatialpy.core.spatialpyerror import ResultError
try:
import vtk
@@ -237,10 +239,10 @@ Source code for spatialpy.core.result
return trace_list
[docs]class Result():
- """
+ """
Result object for a URDME simulation.
"""
- def __init__(self, model=None, result_dir=None):
+ def __init__(self, model=None, result_dir=None):
self.model = model
self.tspan = None
self.success = False
@@ -250,7 +252,7 @@ Source code for spatialpy.core.result
self.official_vtk = False
self.result_dir = result_dir
- def __eq__(self, other):
+ def __eq__(self, other):
if isinstance(other, Result) and self.result_dir and other.result_dir:
# Compare contents, not shallow compare
filecmp.cmpfiles.__defaults__ = (False,)
@@ -262,7 +264,7 @@ Source code for spatialpy.core.result
return False
return NotImplemented
- def __ne__(self, other):
+ def __ne__(self, other):
return not self.__eq__(other)
def __getstate__(self):
@@ -278,7 +280,7 @@ Source code for spatialpy.core.result
resultdict[filename] = state_file.read()
state['results_output'] = resultdict
except Exception as err:
- errmsg = f"Error pickling model, could not pickle the Result output files: {err}"
+ errmsg = f"Error pickling model, could not pickle the Result output files: {err}"
raise ResultError(errmsg) from err
state[key] = item
@@ -297,16 +299,16 @@ Source code for spatialpy.core.result