def convertSBML2Antimony(filename):

    if filename[-3:] == "xml":
        model_name = filename.replace(filename[-3:], "ant")
        antimony.loadSBMLFile(filename)
        antimony.writeAntimonyFile(model_name, antimony.getMainModuleName())

    elif filename[-3:] == "ant":
        model_name = filename.replace(filename[-3:], "xml")
        antimony.loadAntimonyFile(filename)
        antimony.writeSBMLFile(model_name, antimony.getMainModuleName())

    else:
        print("Error, input file not SBML '*.xml' or Antimony '*.ant' ")
Example #2
0
    def antimonyToSBML(self, sb_str, SBO=False):
        """ Converts an Antimony string to raw SBML.

        :param sb_str: The raw Antimony string
        :returns: A 2-tuple (module_name, raw_sbml)
        """

        import antimony as sb

        if not SBO:
            sbo_parser = antimonySBOParser(sb_str)
            try:
                sb_str = sbo_parser.elideSBOTerms()
            except:
                pass

        # try to load the Antimony code`
        code = sb.loadAntimonyString(sb_str)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model into Antimony:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sbml = sb.getSBMLString(module)
        if not SBO:
            sbml = sbo_parser.addSBOsToSBML(sbml)
        return (module, sbml)
    def antimonyToSBML(self, sb_str, SBO=False):
        """ Converts an Antimony string to raw SBML.

        :param sb_str: The raw Antimony string
        :returns: A 2-tuple (module_name, raw_sbml)
        """

        import antimony as sb

        if not SBO:
            sbo_parser = antimonySBOParser(sb_str)
            try:
                sb_str = sbo_parser.elideSBOTerms()
            except:
                pass

        # try to load the Antimony code`
        code = sb.loadAntimonyString(sb_str)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError(
                'Errors encountered when trying to load model into Antimony:\n{}'
                .format(errors))

        module = sb.getMainModuleName()
        sbml = sb.getSBMLString(module)
        if not SBO:
            sbml = sbo_parser.addSBOsToSBML(sbml)
        return (module, sbml)
    def translate_to_sbml_string(self, model_file: str = '', model_string: str = ''):
        """
        Returns string of SBML model specification translated from Antimony or CellML model specification file or string
        :param model_file: relative path to model specification file
        :param model_string: model specification string
        :return {str,str}: string of SBML model specification, string of main module name
        """

        # Just to be sure, call clear previous loads
        antimony.clearPreviousLoads()

        # Loading from model string or file?
        if model_file == '':
            res_load = antimony.loadString(model_string)
        else:
            model_path_normalized = self.normalize_path(model_file)
            res_load = antimony.loadFile(model_path_normalized)

        if res_load == -1:
            AntimonyTranslatorError(self, getAntimonyMessage=True)

        # Get main loaded module
        main_module_name = antimony.getMainModuleName()
        if not main_module_name:
            AntimonyTranslatorError(self, getAntimonyMessage=True)

        # Return string of SBML model specification
        translated_model_string = antimony.getSBMLString(main_module_name)
        if not translated_model_string:
            AntimonyTranslatorError(self, getAntimonyMessage=True)
        else:
            return translated_model_string, main_module_name
Example #5
0
def __antimony_to_sbml(ant):
    try:
        isfile = os.path.isfile(ant)
    except ValueError:
        isfile = False
    if isfile:
        code = antimony.loadAntimonyFile(ant)
    else:
        code = antimony.loadAntimonyString(ant)
    __check_antimony_return_code(code)
    mid = antimony.getMainModuleName()
    return antimony.getSBMLString(mid)
Example #6
0
 def translate_sbml(cls, sbml_file: str):
     """
         Translate SBML file to Antimony model specification.
         cayenne's model specification is loosely based on Antimony's model
         specification.
     """
     er_code = sb.loadSBMLFile(sbml_file)
     if er_code == -1:
         raise ModelError("Error while parsing model")
     sb_module = sb.getMainModuleName()
     sb_string = sb.getAntimonyString(sb_module)
     return sb_string
Example #7
0
def antimonyTosbml(antStr):
    """Convert an antimony string into SBML:

    sbmlStr = antimonyTosbml (antimonyStr)
    """
    err = antimony.loadAntimonyString(antStr)

    if err < 0:
        raise Exception("Antimony: " + antimony.getLastError())

    Id = antimony.getMainModuleName()
    return antimony.getSBMLString(Id)
def antimonyToCellML(ant):
    """ Convert Antimony to CellML string.

    :param ant: Antimony string or file
    :type ant: str | file
    :return: CellML
    :rtype: str
    """
    if os.path.isfile(ant):
        code = antimony.loadAntimonyFile(ant)
    else:
        code = antimony.loadAntimonyString(ant)
    _checkAntimonyReturnCode(code)
    mid = antimony.getMainModuleName()
    return antimony.getCellMLString(mid)
Example #9
0
 def __init__(self, model_contents: str, content_type: str) -> None:
     if content_type == "ModelString":
         er_code = sb.loadAntimonyString(model_contents)
     elif content_type == "ModelFile":
         er_code = sb.loadAntimonyFile(model_contents)
     else:
         raise KeyError(f"Unsupported content_type: {content_type}")
     self.er_code = er_code
     if self.er_code == -1:
         error_msg = "Error while parsing model. Model variable names "
         error_msg += "might be antimony keywords (see docs at https://"
         error_msg += "cayenne.readthedocs.io/en/latest/tutorial.html)."
         raise ModelError(error_msg)
     self.sb_module = sb.getMainModuleName()
     self._parse_model()
Example #10
0
def antimonyToCellML(ant):
    """ Convert Antimony to CellML string.

    :param ant: Antimony string or file
    :type ant: str | file
    :return: CellML
    :rtype: str
    """
    if os.path.isfile(ant):
        code = antimony.loadAntimonyFile(ant)
    else:
        code = antimony.loadAntimonyString(ant)
    _checkAntimonyReturnCode(code)
    mid = antimony.getMainModuleName()
    return antimony.getCellMLString(mid)
Example #11
0
def loadAntimonyModel(antStr):
    """Load an Antimony string:
    
    r = loadAntModel (antimonyStr)
    """
    err = antimony.loadAntimonyString(antStr)

    if err < 0:
        raise Exception("Antimony: " + antimony.getLastError())

    Id = antimony.getMainModuleName()
    sbmlStr = antimony.getSBMLString(Id)
    rr = roadrunner.RoadRunner(sbmlStr)

    antimony.clearPreviousLoads()

    return rr
Example #12
0
def antimonyToSBML(ant):
    """ Convert Antimony to SBML string.

    :param ant: Antimony string or file
    :type ant: str | file
    :return: SBML
    :rtype: str
    """
    try:
        isfile = os.path.isfile(ant)
    except ValueError:
        isfile = False
    if isfile:
        code = antimony.loadAntimonyFile(ant)
    else:
        code = antimony.loadAntimonyString(ant)
    _checkAntimonyReturnCode(code)
    mid = antimony.getMainModuleName()
    return antimony.getSBMLString(mid)
Example #13
0
def antimonyToSBML(ant):
    """ Convert Antimony to SBML string.

    :param ant: Antimony string or file
    :type ant: str | file
    :return: SBML
    :rtype: str
    """
    try:
        isfile = os.path.isfile(ant)
    except ValueError:
        isfile = False
    if isfile:
        code = antimony.loadAntimonyFile(ant)
    else:
        code = antimony.loadAntimonyString(ant)
    _checkAntimonyReturnCode(code)
    mid = antimony.getMainModuleName()
    return antimony.getSBMLString(mid)
Example #14
0
    def antimonyToSBML(self, sb_str):
        """ Converts an Antimony string to raw SBML.

        :param sb_str: The raw Antimony string
        :returns: A 2-tuple (module_name, raw_sbml)
        """

        import antimony as sb
        # try to load the Antimony code`
        code = sb.loadAntimonyString(sb_str)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sbml = sb.getSBMLString(module)
        return (module, sbml)
Example #15
0
    def cellmlFileToAntimony(self, sbml_path):
        """ Converts a CellML file to Antimony source.

        :param sbml_path: The path to the CellML file
        :returns: A 2-tuple (module_name, antimony_source)
        """

        import antimony as sb
        # try to load the Antimony code`
        code = sb.loadCellMLFile(sbml_path)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sb_source = sb.getAntimonyString(module)
        return (module, sb_source)
Example #16
0
    def cellmlFileToAntimony(self, sbml_path):
        """ Converts a CellML file to Antimony source.

        :param sbml_path: The path to the CellML file
        :returns: A 2-tuple (module_name, antimony_source)
        """

        import antimony as sb
        # try to load the Antimony code`
        code = sb.loadCellMLFile(sbml_path)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sb_source = sb.getAntimonyString(module)
        return (module, sb_source)
Example #17
0
    def sbmlToAntimony(self, sbml, addSBO=False):
        """ Converts a raw SBML string to Antimony source.

        :param sbml: The raw SBML string
        :returns: A 2-tuple (module_name, antimony_source)
        """

        import antimony as sb
        # try to load the Antimony code`
        code = sb.loadSBMLString(sbml)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sb_source = sb.getAntimonyString(module)
        if addSBO:
            sb_source = self.tryAddSBOTerms(sb_source, sbml_str=sbml)
        return (module, sb_source)
Example #18
0
    def sbmlToAntimony(self, sbml, addSBO=False):
        """ Converts a raw SBML string to Antimony source.

        :param sbml: The raw SBML string
        :returns: A 2-tuple (module_name, antimony_source)
        """

        import antimony as sb
        # try to load the Antimony code`
        code = sb.loadSBMLString(sbml)

        # if errors, bail
        if self.checkAntimonyReturnCode(code):
            errors = sb.getLastError()
            raise RuntimeError('Errors encountered when trying to load model:\n{}'.format(errors))

        module = sb.getMainModuleName()
        sb_source = sb.getAntimonyString(module)
        if addSBO:
            sb_source = self.tryAddSBOTerms(sb_source, sbml_str=sbml)
        return (module, sb_source)
doplot = True #plotten?
plotlegend = True #Legende plotten?
verbose = 2 #Verbose level: 0 = garnicht, 1 = Statistik 1x je outerLoop, 2 = Statistik nach jedem N, 3 = +Schleifenzaehler (Haengt sich die Simulation auf?)
Nscale=100
#Produkt der naechsten 3 Variablen ist die Anzahl der insg. simulierten Pfade
outerLoop = 1 #Anzahl Wiederholungen festlegen (multipliziert sich mit AnzahlPfade zur Anzahl der simulierten Pfade je N)
Nrange= range(3) #Bereich von N festlegen. range(5) ==  0,1,2,3,4. Daher Multiplikator N = (N+1)*Nscale
AnzahlPfade = 40 #Anzahl Wiederholungen festlegen (multipliziert sich mit outerLoop). Fuer schoene Plots hier Wert 40-100. Fuer grosse N: doplot=False, hier 1, dafuer bei outerLoop gewuenschte Werte eintragen.
#--------------stay-above-this-line----- #Modell laden, kann auch URL sein z.B. von www.biomodels.net---------
if os.path.isfile(antStr):   #----------- start copy&paste from tellurium.py
	code = antimony.loadAntimonyFile(antStr)
else:
	code = antimony.loadAntimonyString(antStr)
if code < 0:
	raise Exception('Antimony: {}'.format(antimony.getLastError()))
mid = antimony.getMainModuleName()
sbml = antimony.getSBMLString(mid)
r = roadrunner.RoadRunner(sbml) #----------- end copy&paste from tellurium.py
#----------------the-next-three-lines-should-be-user-adapted--------
r.setIntegrator('gillespie')  #Integrator auswaehlen. Andere unterstuetzen z.B. ODEs
r.getIntegrator().setValue('variable_step_size', True) #Parameter fuer Integrator setzen, anderer Integrator unterstuetzt andere Parameter
Config.setValue(Config.MAX_OUTPUT_ROWS,pow(10,7))  #bei 64-bit pow(10,11) oder weniger bei wenig Arbeitsspeicher
#-----------end-user-parameters-----------
Reactions = 0
start_time = time.time()
selectToSave = ['N'] + selectToPlot
form=(1,len(selectToSave))
r.selections = selectToSave
simuliertePfade = 0
PfadeGesamt=outerLoop*AnzahlPfade*len(Nrange)
if os.path.isfile(path+name):  #Header in CSV-Datei automatisch erzeugen, falls Datei noch nicht existiert
Example #20
0
verbose = 2  #Verbose level: 0 = garnicht, 1 = Statistik 1x je outerLoop, 2 = Statistik nach jedem N, 3 = +Schleifenzaehler (Haengt sich die Simulation auf?)
Nscale = 100
#Produkt der naechsten 3 Variablen ist die Anzahl der insg. simulierten Pfade
outerLoop = 1  #Anzahl Wiederholungen festlegen (multipliziert sich mit AnzahlPfade zur Anzahl der simulierten Pfade je N)
Nrange = range(
    3
)  #Bereich von N festlegen. range(5) ==  0,1,2,3,4. Daher Multiplikator N = (N+1)*Nscale
AnzahlPfade = 40  #Anzahl Wiederholungen festlegen (multipliziert sich mit outerLoop). Fuer schoene Plots hier Wert 40-100. Fuer grosse N: doplot=False, hier 1, dafuer bei outerLoop gewuenschte Werte eintragen.
#--------------stay-above-this-line----- #Modell laden, kann auch URL sein z.B. von www.biomodels.net---------
if os.path.isfile(antStr):  #----------- start copy&paste from tellurium.py
    code = antimony.loadAntimonyFile(antStr)
else:
    code = antimony.loadAntimonyString(antStr)
if code < 0:
    raise Exception('Antimony: {}'.format(antimony.getLastError()))
mid = antimony.getMainModuleName()
sbml = antimony.getSBMLString(mid)
r = roadrunner.RoadRunner(sbml)  #----------- end copy&paste from tellurium.py
#----------------the-next-three-lines-should-be-user-adapted--------
r.setIntegrator(
    'gillespie')  #Integrator auswaehlen. Andere unterstuetzen z.B. ODEs
r.getIntegrator().setValue(
    'variable_step_size', True
)  #Parameter fuer Integrator setzen, anderer Integrator unterstuetzt andere Parameter
Config.setValue(Config.MAX_OUTPUT_ROWS, pow(
    10, 7))  #bei 64-bit pow(10,11) oder weniger bei wenig Arbeitsspeicher
#-----------end-user-parameters-----------
Reactions = 0
start_time = time.time()
selectToSave = ['N'] + selectToPlot
form = (1, len(selectToSave))
Example #21
0
import tellurium as te
import tempfile

# load model
r = te.loada('S1 -> S2; k1*S1; k1 = 0.1; S1 = 10')
# file for export
f_matlab = tempfile.NamedTemporaryFile(suffix=".m")

# export current model state
r.exportToMatlab(f_matlab.name)

# to export the initial state when the model was loaded
# set the current argument to False
r.exportToMatlab(f_matlab.name, current=False)

# The string representations of the current model are available via
str_matlab = r.getCurrentMatlab()

# and of the initial state when the model was loaded via
str_matlab = r.getMatlab()
print(str_matlab)

# In[5]:

import antimony
antimony.loadAntimonyString('''S1 -> S2; k1*S1; k1 = 0.1; S1 = 10''')
ant_str = antimony.getCellMLString(antimony.getMainModuleName())
print(ant_str)

# In[6]:
Example #22
0
# file for export
f_matlab = tempfile.NamedTemporaryFile(suffix=".m")

# export current model state
r.exportToMatlab(f_matlab.name)

# to export the initial state when the model was loaded
# set the current argument to False
r.exportToMatlab(f_matlab.name, current=False)

# The string representations of the current model are available via
str_matlab = r.getCurrentMatlab()

# and of the initial state when the model was loaded via
str_matlab = r.getMatlab()
print(str_matlab)


# In[5]:

import antimony
antimony.loadAntimonyString('''S1 -> S2; k1*S1; k1 = 0.1; S1 = 10''')
ant_str = antimony.getCellMLString(antimony.getMainModuleName())
print(ant_str)


# In[6]:



Example #23
0
import antimony

ant = '''
model stoch()
  species A,B,C,D,E
  A -> B; k1
  B -> C; k2
  C -> D; k3
  D -> C; k4
  E -> C; k5
  
  A = 100000
  B = 1000
  C = 1000
  D = 1000
  E = 100000
  
  k1 = 0.2
  k2 = 0.05
  k3 = 0.1
  k4 = 0.01
  k5 = 0.05
end
'''

antimony.loadAntimonyString(ant)
sbmlstr = antimony.getSBMLString(antimony.getMainModuleName())
#print(sbmlstr)
with open('stoch_l3.xml', 'w') as f:
    f.write(sbmlstr)