Skip to content

Commit

Permalink
Merge branch 'develop' into lint_missing_noise
Browse files Browse the repository at this point in the history
  • Loading branch information
dweindl authored Apr 28, 2022
2 parents 30e0d43 + 902f349 commit 57fd61d
Show file tree
Hide file tree
Showing 4 changed files with 1 addition and 213 deletions.
51 changes: 0 additions & 51 deletions petab/measurements.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,9 @@
# noqa: F405

import itertools
import math
import numbers
from pathlib import Path
from typing import Dict, List, Union
from warnings import warn

import numpy as np
import pandas as pd
Expand All @@ -18,7 +16,6 @@
'create_measurement_df',
'get_measurement_df',
'get_measurement_parameter_ids',
'get_noise_distributions',
'get_rows_for_condition',
'get_simulation_conditions',
'measurements_have_replicates',
Expand Down Expand Up @@ -63,54 +60,6 @@ def write_measurement_df(df: pd.DataFrame, filename: Union[str, Path]) -> None:
df.to_csv(filename, sep='\t', index=False)


def get_noise_distributions(measurement_df: pd.DataFrame) -> dict:
"""
Returns dictionary of cost definitions per observable, if specified.
Looks through all parameters satisfying `sbml_parameter_is_cost` and
return as dictionary.
Parameters:
measurement_df: PEtab measurement table
Returns:
Dictionary with `observableId` => `cost definition`
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

lint.assert_noise_distributions_valid(measurement_df)

# read noise distributions from measurement file
grouping_cols = core.get_notnull_columns(
measurement_df, [OBSERVABLE_ID, OBSERVABLE_TRANSFORMATION,
NOISE_DISTRIBUTION])

observables = measurement_df.fillna('').groupby(grouping_cols).size()\
.reset_index()
noise_distrs = {}
for _, row in observables.iterrows():
# prefix id to get observable id
id_ = 'observable_' + row.observableId

# extract observable transformation and noise distribution,
# use lin+normal as default if none provided
obs_trafo = row.observableTransformation \
if OBSERVABLE_TRANSFORMATION in row \
and row.observableTransformation \
else LIN
noise_distr = row.noiseDistribution \
if NOISE_DISTRIBUTION in row \
and row.noiseDistribution \
else NORMAL
# add to noise distributions
noise_distrs[id_] = {
OBSERVABLE_TRANSFORMATION: obs_trafo,
NOISE_DISTRIBUTION: noise_distr}

return noise_distrs


def get_simulation_conditions(measurement_df: pd.DataFrame) -> pd.DataFrame:
"""
Create a table of separate simulation conditions. A simulation condition
Expand Down
32 changes: 0 additions & 32 deletions petab/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
from pathlib import Path, PurePosixPath
from typing import Dict, Iterable, List, Optional, Union
from urllib.parse import unquote, urlparse, urlunparse
from warnings import warn

import libsbml
import pandas as pd
Expand Down Expand Up @@ -431,43 +430,12 @@ def get_model_parameters(self):
"""See :py:func:`petab.sbml.get_model_parameters`"""
return sbml.get_model_parameters(self.sbml_model)

def get_observables(self, remove: bool = False):
"""
Returns dictionary of observables definitions.
See :py:func:`petab.assignment_rules_to_dict` for details.
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

return sbml.get_observables(sbml_model=self.sbml_model, remove=remove)

def get_observable_ids(self):
"""
Returns dictionary of observable ids.
"""
return list(self.observable_df.index)

def get_sigmas(self, remove: bool = False):
"""
Return dictionary of observableId => sigma as defined in the SBML
model.
This does not include parameter mappings defined in the measurement
table.
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

return sbml.get_sigmas(sbml_model=self.sbml_model, remove=remove)

def get_noise_distributions(self):
"""
See :py:func:`petab.get_noise_distributions`.
"""
return measurements.get_noise_distributions(
measurement_df=self.measurement_df)

def _apply_mask(self, v: List, free: bool = True, fixed: bool = True):
"""Apply mask of only free or only fixed values.
Expand Down
104 changes: 1 addition & 103 deletions petab/sbml.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"""Functions for interacting with SBML models"""
import logging
import re
from numbers import Number
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple, Union
from typing import Dict, List, Optional, Tuple, Union
from warnings import warn

import libsbml
Expand All @@ -16,13 +15,10 @@
'add_model_output',
'add_model_output_sigma',
'add_model_output_with_sigma',
'assignment_rules_to_dict',
'create_assigment_rule',
'get_model_for_condition',
'get_model_parameters',
'get_observables',
'get_sbml_model',
'get_sigmas',
'globalize_parameters',
'is_sbml_consistent',
'load_sbml_from_file',
Expand All @@ -33,61 +29,6 @@
'write_sbml']


def assignment_rules_to_dict(
sbml_model: libsbml.Model, filter_function=lambda *_: True,
remove: bool = False) -> Dict[str, Dict[str, Any]]:
"""
Turn assignment rules into dictionary.
Parameters:
sbml_model:
a sbml model instance.
filter_function:
callback function taking assignment variable as input
and returning True/False to indicate if the respective rule should
be turned into an observable.
remove:
Remove the all matching assignment rules from the model
Returns:
::
{
assigneeId:
{
'name': assigneeName,
'formula': formulaString
}
}
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

result = {}

# iterate over rules
for rule in sbml_model.getListOfRules():
if rule.getTypeCode() != libsbml.SBML_ASSIGNMENT_RULE:
continue
assignee = rule.getVariable()
parameter = sbml_model.getParameter(assignee)
# filter
if parameter and filter_function(parameter):
result[assignee] = {
'name': parameter.getName(),
'formula': libsbml.formulaToL3String(rule.getMath())
}

# remove from model?
if remove:
for parameter_id in result:
sbml_model.removeRuleByVariable(parameter_id)
sbml_model.removeParameter(parameter_id)

return result


def is_sbml_consistent(sbml_document: libsbml.SBMLDocument,
check_units: bool = False) -> bool:
"""Check for SBML validity / consistency
Expand Down Expand Up @@ -354,49 +295,6 @@ def sbml_parameter_is_sigma(sbml_parameter: libsbml.Parameter) -> bool:
return sbml_parameter.getId().startswith('sigma_')


def get_observables(sbml_model: libsbml.Model, remove: bool = False) -> dict:
"""
Get observables defined in SBML model according to PEtab format.
Returns:
Dictionary of observable definitions.
See `assignment_rules_to_dict` for details.
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

observables = assignment_rules_to_dict(
sbml_model,
filter_function=sbml_parameter_is_observable,
remove=remove
)
return observables


def get_sigmas(sbml_model: libsbml.Model, remove: bool = False) -> dict:
"""
Get sigmas defined in SBML model according to PEtab format.
Returns:
Dictionary of sigma definitions.
Keys are observable IDs, for values see `assignment_rules_to_dict` for
details.
"""
warn("This function will be removed in future releases.",
DeprecationWarning)

sigmas = assignment_rules_to_dict(
sbml_model,
filter_function=sbml_parameter_is_sigma,
remove=remove
)
# set correct observable name
sigmas = {re.sub('^sigma_', 'observable_', key): value['formula']
for key, value in sigmas.items()}
return sigmas


def get_model_parameters(sbml_model: libsbml.Model, with_values=False
) -> Union[List[str], Dict[str, float]]:
"""Return SBML model parameters which are not Rule targets
Expand Down
27 changes: 0 additions & 27 deletions tests/test_sbml.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,6 @@
import petab # noqa: E402


def test_assignment_rules_to_dict():
# Create Sbml model with one parameter and one assignment rule
document = libsbml.SBMLDocument(3, 1)
model = document.createModel()
petab.sbml.add_model_output(sbml_model=model,
observable_id='1',
observable_name='Observable 1',
formula='a+b')

expected = {
'observable_1': {
'name': 'Observable 1',
'formula': 'a + b'
}
}

actual = petab.assignment_rules_to_dict(model, remove=False)
assert actual == expected
assert model.getAssignmentRuleByVariable('observable_1') is not None
assert len(model.getListOfParameters()) == 1

actual = petab.assignment_rules_to_dict(model, remove=True)
assert actual == expected
assert model.getAssignmentRuleByVariable('observable_1') is None
assert len(model.getListOfParameters()) == 0


def test_get_condition_specific_models():
"""Test for petab.sbml.get_condition_specific_models"""
# Create test model and data files
Expand Down

0 comments on commit 57fd61d

Please sign in to comment.