Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def taskTreeToPython(doc, tree):
""" Python code generation from task tree. """
# go forward through task tree
lines = []
nodeStack = SEDMLCodeFactory.Stack()
treeNodes = [n for n in tree]
# iterate over the tree
for kn, node in enumerate(treeNodes):
taskType = node.task.getTypeCode()
# Create information for task
# We are going down in the tree
if taskType == libsedml.SEDML_TASK_REPEATEDTASK:
taskLines = SEDMLCodeFactory.repeatedTaskToPython(doc, node=node)
elif taskType == libsedml.SEDML_TASK:
tid = node.task.getId()
taskLines = SEDMLCodeFactory.simpleTaskToPython(doc=doc, node=node)
else:
lines.append("# Unsupported task: {}".format(taskType))
warnings.warn("Unsupported task: {}".format(taskType))
lines.extend([" "*node.depth + line for line in taskLines])
'''
@staticmethod
def simpleTaskToPython(doc, task):
""" Create python for simple task. """
for ksub, subtask in enumerate(subtasks):
t = doc.getTask(subtask.getTask())
def outputToPython(self, doc, output):
""" Create output """
lines = []
typeCode = output.getTypeCode()
if typeCode == libsedml.SEDML_OUTPUT_REPORT:
lines.extend(SEDMLCodeFactory.outputReportToPython(self, doc, output))
elif typeCode == libsedml.SEDML_OUTPUT_PLOT2D:
lines.extend(SEDMLCodeFactory.outputPlot2DToPython(self, doc, output))
elif typeCode == libsedml.SEDML_OUTPUT_PLOT3D:
lines.extend(SEDMLCodeFactory.outputPlot3DToPython(self, doc, output))
else:
warnings.warn("# Unsupported output type '{}' in output {}".format(output.getElementName(), output.getId()))
return '\n'.join(lines)
def testInput(sedmlInput):
""" Test function run on inputStr. """
print('\n', '*'*100)
print(sedmlInput)
print('*'*100)
factory = SEDMLCodeFactory(sedmlInput)
# create python file
python_str = factory.toPython()
realPath = os.path.realpath(sedmlInput)
with open(sedmlInput + '.py', 'w') as f:
f.write(python_str)
# execute python
factory.executePython()
lines.append("if {model}.conservedMoietyAnalysis == False: {model}.conservedMoietyAnalysis = True".format(model=mid))
else:
lines.append("if {model}.conservedMoietyAnalysis == True: {model}.conservedMoietyAnalysis = False".format(model=mid))
# get parents
parents = []
parent = node.parent
while parent is not None:
parents.append(parent)
parent = parent.parent
# of all parents
# ---------------------------
selections = SEDMLCodeFactory.selectionsForTask(doc=doc, task=node.task)
for p in parents:
selections.update(SEDMLCodeFactory.selectionsForTask(doc=doc, task=p.task))
# of all parents
# ---------------------------
# apply changes based on current variables, parameters and range variables
for parent in reversed(parents):
rangeId = parent.task.getRangeId()
helperRanges = {}
for r in parent.task.getListOfRanges():
if r.getId() != rangeId:
helperRanges[r.getId()] = r
for setValue in parent.task.getListOfTaskChanges():
variables = {}
# range variables
variables[rangeId] = "__value__{}".format(rangeId)
for key in helperRanges.keys():
def sedmlToPython(inputStr, workingDir=None):
""" Convert sedml file to python code.
:param inputStr: full path name to SedML model or SED-ML string
:type inputStr: path
:return: generated python code
"""
factory = SEDMLCodeFactory(inputStr, workingDir=workingDir)
return factory.toPython()
# get sedml locations by omex
sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="omex")
if len(sedml_locations) == 0:
# falling back to zip archive
sedml_locations = omex.getLocationsByFormat(omexPath=omexPath, formatKey="sed-ml", method="zip")
warnings.warn(
"No SED-ML files in COMBINE archive based on manifest '{}'; Guessed SED-ML {}".format(omexPath, sedml_locations))
# run all sedml files
results = {}
sedml_paths = [os.path.join(extractDir, loc) for loc in sedml_locations]
for sedmlFile in sedml_paths:
factory = SEDMLCodeFactory(sedmlFile,
workingDir=os.path.dirname(sedmlFile),
createOutputs=createOutputs,
saveOutputs=saveOutputs,
outputDir=outputDir,
plottingEngine=plottingEngine
)
if printPython:
code = factory.toPython()
print(code)
results[sedmlFile] = factory.executePython()
return results
finally:
shutil.rmtree(tmp_dir)
else:
#
# master range
rangeId = task.getRangeId()
masterRange = task.getRange(rangeId)
if masterRange.getTypeCode() == libsedml.SEDML_RANGE_UNIFORMRANGE:
lines.extend(SEDMLCodeFactory.uniformRangeToPython(masterRange))
elif masterRange.getTypeCode() == libsedml.SEDML_RANGE_VECTORRANGE:
lines.extend(SEDMLCodeFactory.vectorRangeToPython(masterRange))
elif masterRange.getTypeCode() == libsedml.SEDML_RANGE_FUNCTIONALRANGE:
warnings.warn("FunctionalRange for master range not supported in task.")
# lock-in ranges
for r in task.getListOfRanges():
if r.getId() != rangeId:
if r.getTypeCode() == libsedml.SEDML_RANGE_UNIFORMRANGE:
lines.extend(SEDMLCodeFactory.uniformRangeToPython(r))
elif r.getTypeCode() == libsedml.SEDML_RANGE_VECTORRANGE:
lines.extend(SEDMLCodeFactory.vectorRangeToPython(r))
#
# iterate master range
lines.append("for __k__{}, __value__{} in enumerate(__range__{}):".format(rangeId, rangeId, rangeId))
# Everything from now on is done in every iteration of the range
# We have to collect & intent all lines in the loop)
forLines = []
# definition of lock-in ranges
helperRanges = {}
for r in task.getListOfRanges():
if r.getId() != rangeId:
helperRanges[r.getId()] = r
lines.append("{} = [None]".format(task.getId()))
mid = task.getModelReference()
sid = task.getSimulationReference()
simulation = doc.getSimulation(sid)
simType = simulation.getTypeCode()
algorithm = simulation.getAlgorithm()
if algorithm is None:
warnings.warn("Algorithm missing on simulation, defaulting to 'cvode: KISAO:0000019'")
algorithm = simulation.createAlgorithm()
algorithm.setKisaoID("KISAO:0000019")
kisao = algorithm.getKisaoID()
# is supported algorithm
if not SEDMLCodeFactory.isSupportedAlgorithmForSimulationType(kisao=kisao, simType=simType):
warnings.warn("Algorithm {} unsupported for simulation {} type {} in task {}".format(kisao, simulation.getId(), simType, task.getId()))
lines.append("# Unsupported Algorithm {} for SimulationType {}".format(kisao, simulation.getElementName()))
return lines
# set integrator/solver
integratorName = SEDMLCodeFactory.getIntegratorNameForKisaoID(kisao)
if not integratorName:
warnings.warn("No integrator exists for {} in roadrunner".format(kisao))
return lines
if simType is libsedml.SEDML_SIMULATION_STEADYSTATE:
lines.append("{}.setSteadyStateSolver('{}')".format(mid, integratorName))
else:
lines.append("{}.setIntegrator('{}')".format(mid, integratorName))
# use fixed step by default for stochastic sims
lines.append("{}.setSteadyStateSolver('{}')".format(mid, integratorName))
else:
lines.append("{}.setIntegrator('{}')".format(mid, integratorName))
# use fixed step by default for stochastic sims
if integratorName == 'gillespie':
lines.append("{}.integrator.setValue('{}', {})".format(mid, 'variable_step_size', False))
if kisao == "KISAO:0000288": # BDF
lines.append("{}.integrator.setValue('{}', {})".format(mid, 'stiff', True))
elif kisao == "KISAO:0000280": # Adams-Moulton
lines.append("{}.integrator.setValue('{}', {})".format(mid, 'stiff', False))
# integrator/solver settings (AlgorithmParameters)
for par in algorithm.getListOfAlgorithmParameters():
pkey = SEDMLCodeFactory.algorithmParameterToParameterKey(par)
# only set supported algorithm paramters
if pkey:
if pkey.dtype is str:
value = "'{}'".format(pkey.value)
else:
value = pkey.value
if value == str('inf') or pkey.value == float('inf'):
value = "float('inf')"
else:
pass
if simType is libsedml.SEDML_SIMULATION_STEADYSTATE:
lines.append("{}.steadyStateSolver.setValue('{}', {})".format(mid, pkey.key, value))
else:
lines.append("{}.integrator.setValue('{}', {})".format(mid, pkey.key, value))