Skip to content

Commit

Permalink
Minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
JR-1991 committed Mar 4, 2022
1 parent 9c6d0af commit be61950
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 15 deletions.
7 changes: 4 additions & 3 deletions pyenzyme/enzymeml/core/enzymemldocument.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,10 @@ class EnzymeMLDocument(EnzymeMLBase):
3,
description="SBML evel of the EnzymeML XML.",
inclusiveMinimum=1,
exclusiveMaximum=3,
inclusiveMaximum=3,
)

version: str = Field(
version: int = Field(
2,
description="SBML version of the EnzymeML XML.",
)
Expand Down Expand Up @@ -1094,7 +1094,7 @@ def addReaction(self, reaction: EnzymeReaction, use_parser: bool = True) -> str:
# Reset temperature for SBML compliance to Kelvin
reaction.temperature = (
reaction.temperature + 273.15
if re.match(r"^K|kelvin", reaction.temperature_unit)
if re.match(r"^c|celsius", reaction.temperature_unit.lower())
else reaction.temperature
)

Expand Down Expand Up @@ -1345,6 +1345,7 @@ def _updateReplicateMeasurementIDs(
):
"""Updates the measurement IDs of replicates."""
for measurement_data in measurement_data_dict.values():
measurement_data.measurement_id = measurement_id
replicates = measurement_data.replicates
for replicate in replicates:
replicate.measurement_id = measurement_id
Expand Down
11 changes: 11 additions & 0 deletions pyenzyme/enzymeml/core/enzymereaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ def set_meta_id(cls, id: Optional[str], values: dict):

return id

@validator("temperature_unit")
def convert_temperature_unit(cls, unit, values):
"""Converts celsius to kelvin due to SBML limitations"""

if unit:
if unit.lower() in ["celsius", "c"]:
values["temperature"] = values["temperature"] + 273.15
return "K"

return unit

# ! Getters
def getEduct(self, id: str) -> ReactionElement:
"""
Expand Down
14 changes: 13 additions & 1 deletion pyenzyme/enzymeml/core/measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from typing import List, Dict, Tuple, Optional, TYPE_CHECKING, Union
from dataclasses import dataclass
from pydantic import validate_arguments, Field, PrivateAttr
from pydantic import validate_arguments, Field, PrivateAttr, validator

from pyenzyme.enzymeml.core.enzymemlbase import EnzymeMLBase
from pyenzyme.enzymeml.core.measurementData import MeasurementData
Expand Down Expand Up @@ -94,6 +94,18 @@ class Measurement(EnzymeMLBase):
_temperature_unit_id: str = PrivateAttr(None)
_global_time_unit_id: str = PrivateAttr(None)

# ! Validators
@validator("temperature_unit")
def convert_temperature_unit(cls, unit, values):
"""Converts celsius to kelvin due to SBML limitations"""

if unit:
if unit.lower() in ["celsius", "c"]:
values["temperature"] = values["temperature"] + 273.15
return "K"

return unit

# ! Utility methods
def __repr__(self):
return self.printMeasurementScheme(stdout=False)
Expand Down
29 changes: 23 additions & 6 deletions pyenzyme/enzymeml/tools/enzymemlreader.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,8 @@
)

from libsbml import SBMLReader
from enum import Enum
from libcombine import CombineArchive
from io import StringIO, BytesIO
from io import StringIO

# ! Factories

Expand Down Expand Up @@ -105,6 +104,11 @@ def readFromFile(self, path: str) -> EnzymeMLDocument:
folder destination for plain .xml
"""

if not path.endswith(".omex"):
raise TypeError(
f"File {os.path.basename(path)} is not a valid OMEX archive"
)

# Read omex archive
self.path = path
self.archive = CombineArchive()
Expand Down Expand Up @@ -253,7 +257,7 @@ def _getUnits(self, model: libsbml.Model) -> Dict[str, UnitDef]:
name = unit.name
id = unit.id
meta_id = unit.meta_id
ontology = "NONE" # TODO get unit ontology
ontology = None # TODO get unit ontology

# Create unit definition
unitdef = UnitDef(name=name, id=id, ontology=ontology, meta_id=meta_id)
Expand Down Expand Up @@ -344,6 +348,10 @@ def _getSpecies(
"init_conc": init_conc,
"_unit_id": unit_id,
"unit": unit,
# Some attributes need special care
"ecnumber": param_dict.get("e_cnumber"),
"uniprotid": param_dict.get("uniprot_id"),
"participants": param_dict.get("participant"),
}
)

Expand Down Expand Up @@ -399,11 +407,19 @@ def camel_to_snake(name):
param_dict = {}

for enzymeMLAnnot in speciesAnnot:
key = enzymeMLAnnot.tag.split("}")[-1].lower()
key = enzymeMLAnnot.tag.split("}")[-1]
key = camel_to_snake(key)

attribute = enzymeMLAnnot.text

if key in param_dict:
# Take care of list attributes
try:
param_dict[key].append(attribute)
except AttributeError:
param_dict[key] = [param_dict[key], attribute]

continue

param_dict[key] = attribute

return param_dict
Expand Down Expand Up @@ -623,9 +639,10 @@ def _parse_parameter(self, parameter, enzmldoc):
value=value,
unit=param_dict.get("unit"),
ontology=self._sboterm_to_enum(parameter.getSBOTerm()),
initial_value=param_dict.get("initialvalue"),
initial_value=param_dict.get("initial_value"),
upper=param_dict.get("upperbound"),
lower=param_dict.get("lowerbound"),
stdev=param_dict.get("stdev"),
constant=constant,
)

Expand Down
12 changes: 11 additions & 1 deletion pyenzyme/enzymeml/tools/enzymemlwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ def appendMultiAttributes(
for key, value in objectMapping.items():
# "value" --> 10.00
if hasattr(object, value):

attribute = getattr(object, value)
if attribute:
node.addAttr(key, str(attribute))
Expand Down Expand Up @@ -432,6 +433,7 @@ def _addProteins(
"enzymeml:ECnumber": "ecnumber",
"enzymeml:uniprotID": "uniprotid",
"enzymeml:organism": "organism",
"enzymeml:organismTaxID": "organism_tax_id",
}

for protein in protein_dict.values():
Expand Down Expand Up @@ -473,7 +475,11 @@ def _addReactants(self, model: libsbml.Model, reactant_dict: Dict[str, Reactant]
"""

# EnzymeML attributes
reactantAttributes = {"enzymeml:inchi": "inchi", "enzymeml:smiles": "smiles"}
reactantAttributes = {
"enzymeml:inchi": "inchi",
"enzymeml:smiles": "smiles",
"enzymeml:chebiID": "chebi_id",
}

for reactant in reactant_dict.values():
self._addSpecies(
Expand Down Expand Up @@ -645,6 +651,9 @@ def _addReactions(
annotationNode=conditionsAnnotation,
)

if conditionsAnnotation.getNumChildren() > 0:
reactionAnnotation.addChild(conditionsAnnotation)

if reactionAnnotation.getNumChildren() > 0:
reaction.appendAnnotation(reactionAnnotation)

Expand Down Expand Up @@ -696,6 +705,7 @@ def _addModelToReaction(
"enzymeml:initialValue": "initial_value",
"enzymeml:upperBound": "upper",
"enzymeml:lowerBound": "lower",
"enzymeml:stdev": "stdev",
}

for attributeName, objectName in optional_parameters.items():
Expand Down
3 changes: 0 additions & 3 deletions pyenzyme/enzymeml/tools/unitcreator.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ def __init__(self):

self.__functionDict = {
"M": self.__Molar,
"m": self.__Mole,
"mole": self.__Mole,
"l": self.__Volume,
"liter": self.__Volume,
Expand All @@ -36,13 +35,11 @@ def __init__(self):
"seconds": self.__Seconds,
"min": self.__Minutes,
"mins": self.__Minutes,
"minute": self.__Minutes,
"minutes": self.__Minutes,
"h": self.__Hours,
"hour": self.__Hours,
"hours": self.__Hours,
"C": self.__Celsius,
"c": self.__Celsius,
"celsius": self.__Celsius,
"Celsius": self.__Celsius,
"K": self.__Kelvin,
Expand Down
2 changes: 1 addition & 1 deletion pyenzyme/enzymeml/tools/unitparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def __getPrefix(self, string, exponent):

try:
unit = re.findall(regex, string)[0][0]
return ("NONE", unit, exponent)
return (None, unit, exponent)
except IndexError:
supportedUnits = regex.split()
raise KeyError(
Expand Down

0 comments on commit be61950

Please sign in to comment.