Skip to content

Commit

Permalink
updated process devs
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexPatrie committed May 24, 2024
1 parent 02f04b6 commit 53c7645
Show file tree
Hide file tree
Showing 9 changed files with 1,411 additions and 431 deletions.
7 changes: 2 additions & 5 deletions biosimulator_processes/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,14 @@
PROCESSES_TO_REGISTER = [
('cobra', 'cobra_process.CobraProcess'),
('copasi', 'copasi_process.CopasiProcess'),
('_copasi', 'copasi_process._CopasiProcess'),
('smoldyn', 'smoldyn_process.SmoldynProcess'),
('tellurium', 'tellurium_process.TelluriumProcess'),
('amici', 'amici_process.AmiciProcess'),
('compare_ode_process', 'comparator_process.ODEComparatorProcess')]
('amici', 'amici_process.AmiciProcess')]

STEPS_TO_REGISTER = [
('get_sbml_step', 'get_sbml.GetSbmlStep'),
('plotter', 'viz.CompositionPlotter'),
('plotter2d', 'viz.Plotter2d'),
('compare_ode_step', 'comparator_step.ODEComparatorStep')]
('plotter2d', 'viz.Plotter2d')]


# core process registry implementation (unique to this package)
Expand Down
62 changes: 62 additions & 0 deletions biosimulator_processes/processes/instance.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
from dataclasses import dataclass
from typing import *

from process_bigraph.experiments.parameter_scan import RunProcess

from biosimulator_processes import CORE
from biosimulator_processes.data_model import _BaseClass


class ODEProcess(RunProcess):
def __init__(self, config=None, core=None):
super().__init__(config, core)

def run(self, input_state=None):
return self.update(input_state or {})


@dataclass
class ProcessObservable(_BaseClass):
path_root: str
root_children: list[str]
path: list[str] = None

def __post_init__(self):
self.path = [self.path_root, *self.root_children]


def generate_ode_process_instance(
entrypoint: Union[str, dict[str, any]], # either sbml model path or sed_model dict which conforms to the spec in sed data model in this repo.
process_address: str,
observables: List[str],
step_size: float,
duration: float,
**process_config
) -> ODEProcess:
"""Generate loaded ode process.
Args:
entrypoint (Union[str, dict[str, any]]): either sbml model path or sed_model dict which conforms to the spec in sed data model in this repo.
process_address (str): the address in registry of the process to be loaded as per the CORE registry
observables (list[str]): observables to be loaded in path form
step_size (float): the step size in seconds
duration (float): the duration in seconds
**process_config (dict): the process config kwargs specific to the simulator process
Returns:
ODEProcess instance
"""
if not isinstance(entrypoint, str or dict[str, any]):
raise ValueError('entrypoint must be a string sbml model path or a dict defining SED_MODEL within biosimulator_processes.data_model.sed_data_model')

config = {'model': {'model_source': entrypoint, **process_config}} if isinstance(entrypoint, str) else entrypoint
return ODEProcess(
config={
'process_address': f'local:{process_address}',
'process_config': config,
'observables': observables,
'timestep': step_size,
'runtime': duration
},
core=CORE)

187 changes: 0 additions & 187 deletions biosimulator_processes/steps/comparator_step.py

This file was deleted.

38 changes: 0 additions & 38 deletions biosimulator_processes/steps/get_sbml.py

This file was deleted.

12 changes: 7 additions & 5 deletions biosimulator_processes/utils.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from typing import Dict, Union, List, Tuple
from types import FunctionType
import os

import numpy as np
from basico import biomodels, load_model_from_string
from process_bigraph import Composite, pf
from process_bigraph import Composite, pf, pp, ProcessTypes
import nbformat
from pydantic import Field
from biosimulator_processes.data_model import _BaseModel


def register_module(items_to_register: List[Tuple[str, str]], core) -> None:
def register_module(items_to_register: List[Tuple[str, str]], core: ProcessTypes) -> None:
for process_name, path in items_to_register:
module_name, class_name = path.rsplit('.', 1)
try:
Expand All @@ -26,9 +25,12 @@ def register_module(items_to_register: List[Tuple[str, str]], core) -> None:

# Register the process
core.process_registry.register(process_name, bigraph_class)
print(f"{class_name} registered successfully.")
print(f"{class_name} registered successfully as {process_name}.\n")
except ImportError as e:
print(f"{class_name} not available. Error: {e}")
return
print(f'Available processes:\n{pf(list(core.process_registry.registry.keys()))}')



def prepare_single_ode_process_document(
Expand Down
17 changes: 17 additions & 0 deletions biosimulator_processes/verify/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,23 @@ def generate_ode_process_interval_comparison_data(outputs: list[np.array], time_
time_id=time_id)


def generate_comparison_matrix(arr1: np.ndarray, arr2: np.ndarray, *simulators: str, use_tol: bool = False) -> pd.DataFrame:
"""Generate a Mean Squared Error comparison matrix of arr1 and arr2, indexed by simulators by default, or an AllClose Tolerance routine if `use_tol` is set to true."""

# TODO: map arrs to simulators more tightly.
mse_matrix = np.zeros((3, 3), dtype=float)
outputs = [arr1, arr2]

# fill the matrices with the calculated values
for i in range(len(simulators)):
for j in range(i, len(simulators)):
mse_matrix[i, j] = calculate_mse(outputs[i], outputs[j])
if i != j:
mse_matrix[j, i] = mse_matrix[i, j]

return pd.DataFrame(mse_matrix, index=simulators, columns=simulators)


def plot_ode_process_comparison(
mse_df: pd.DataFrame,
rmse_df: pd.DataFrame,
Expand Down
Loading

0 comments on commit 53c7645

Please sign in to comment.