Merge pull request #322 from MyersResearchGroup/new_sim

Made changes to the hierarchical simulator
This commit is contained in:
Leandro Watanabe 2017-04-13 16:50:23 -06:00 committed by GitHub
commit e5269d967a
47 changed files with 2650 additions and 3403 deletions

View file

@ -13,21 +13,16 @@
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.xml.stream.XMLStreamException;
@ -36,7 +31,9 @@ import org.sbml.jsbml.SBMLErrorLog;
import org.sbml.jsbml.SBMLReader;
import edu.utah.ece.async.analysis.simulation.ParentSimulator;
import edu.utah.ece.async.analysis.simulation.hierarchical.io.HierarchicalTSDWriter;
import edu.utah.ece.async.analysis.simulation.hierarchical.io.HierarchicalWriter;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.AbstractHierarchicalNode.Type;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ConstraintNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
@ -44,10 +41,13 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
* This class provides the state variables of the simulation.
*
@ -68,11 +68,8 @@ public abstract class HierarchicalSimulation implements ParentSimulator
}
protected final VariableNode currentTime;
protected double printTime;
private BufferedWriter bufferedTSDWriter;
protected final VariableNode printTime;
private boolean cancelFlag;
private boolean constraintFailureFlag;
private boolean constraintFlag;
private int currentRun;
private String[] interestingSpecies;
private double maxTimeStep;
@ -90,32 +87,27 @@ public abstract class HierarchicalSimulation implements ParentSimulator
private double stoichAmpGridValue;
protected double timeLimit;
private String rootDirectory;
private FileWriter TSDWriter;
private SBMLDocument document;
private String abstraction;
private int totalRuns;
protected final ArrayList<Double> initValues;
protected List<VariableNode> variableList;
protected double initTotalPropensity;
protected List<EventNode> eventList;
protected PriorityQueue<EventNode> triggeredEventList;
protected PriorityQueue<EventState> triggeredEventList;
protected boolean isInitialized;
private int numSubmodels;
protected boolean hasEvents;
private boolean isGrid;
private Random randomNumberGenerator;
private HierarchicalModel topmodel;
private Map<String, HierarchicalModel> submodels;
final private SimType type;
private List<HierarchicalModel> modules;
private HierarchicalNode totalPropensity;
protected List<HierarchicalModel> modules;
protected FunctionNode totalPropensity;
private double initialTime, outputStartTime;
private HierarchicalWriter writer;
public HierarchicalSimulation(String SBMLFileName, String rootDirectory, String outputDirectory, long randomSeed, int runs, double timeLimit, double maxTimeStep, double minTimeStep, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running, String[] interestingSpecies,
String quantityType, String abstraction, double initialTime, double outputStartTime, SimType type) throws XMLStreamException, IOException, BioSimException
{
@ -125,7 +117,7 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.minTimeStep = minTimeStep;
this.progress = progress;
this.printInterval = printInterval;
this.printTime = 0;
this.printTime = new VariableNode("_printTime", StateType.SCALAR);
this.rootDirectory = rootDirectory;
this.outputDirectory = outputDirectory;
this.running = running;
@ -136,9 +128,8 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.totalRuns = runs;
this.type = type;
this.topmodel = new HierarchicalModel("topmodel");
this.submodels = new HashMap<String, HierarchicalModel>(0);
this.currentTime = new VariableNode("_time", StateType.SCALAR);
this.hasEvents = false;
this.currentRun = 1;
this.randomNumberGenerator = new Random(randomSeed);
this.initialTime = initialTime;
@ -146,6 +137,12 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.initValues = new ArrayList<Double>();
this.writer = new HierarchicalTSDWriter();
this.addPrintVariable("time", printTime.getState());
this.totalPropensity = new FunctionNode(new VariableNode("propensity", StateType.SCALAR), new HierarchicalNode(Type.PLUS));
if (quantityType != null)
{
String[] printConcentration = quantityType.replaceAll(" ", "").split(",");
@ -192,6 +189,7 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.minTimeStep = copy.minTimeStep;
this.progress = copy.progress;
this.printInterval = copy.printInterval;
this.printTime = copy.printTime;
this.rootDirectory = copy.rootDirectory;
this.outputDirectory = copy.outputDirectory;
this.running = copy.running;
@ -203,11 +201,12 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.type = copy.type;
this.isGrid = copy.isGrid;
this.topmodel = copy.topmodel;
this.submodels = copy.submodels;
this.separator = copy.separator;
this.currentTime = copy.currentTime;
this.randomNumberGenerator = copy.randomNumberGenerator;
this.initValues = copy.initValues;
this.hasEvents = copy.hasEvents;
//this.totalPropensity = copy.totalPropensity;
}
public void addModelState(HierarchicalModel modelstate)
@ -220,20 +219,32 @@ public abstract class HierarchicalSimulation implements ParentSimulator
modules.add(modelstate);
}
public void addPrintVariable(String id, HierarchicalState state)
{
writer.addVariable(id, state);
}
public List<HierarchicalModel> getListOfModelStates()
public List<HierarchicalModel> getListOfHierarchicalModels()
{
return modules;
}
/**
* @return the bufferedTSDWriter
*/
public BufferedWriter getBufferedTSDWriter()
public void setListOfHierarchicalModels(List<HierarchicalModel> modules)
{
return bufferedTSDWriter;
this.modules = modules;
}
public void setHasEvents(boolean value)
{
this.hasEvents = value;
}
public boolean hasEvents()
{
return this.hasEvents;
}
/**
* @return the cancelFlag
*/
@ -242,22 +253,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return cancelFlag;
}
/**
* @return the constraintFailureFlag
*/
public boolean isConstraintFailureFlag()
{
return constraintFailureFlag;
}
/**
* @return the constraintFlag
*/
public boolean isConstraintFlag()
{
return constraintFlag;
}
/**
* @return the currentRun
*/
@ -418,23 +413,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return rootDirectory;
}
/**
* @return the tSDWriter
*/
public FileWriter getTSDWriter()
{
return TSDWriter;
}
/**
* @param bufferedTSDWriter
* the bufferedTSDWriter to set
*/
public void setBufferedTSDWriter(BufferedWriter bufferedTSDWriter)
{
this.bufferedTSDWriter = bufferedTSDWriter;
}
/**
* @param cancelFlag
* the cancelFlag to set
@ -444,24 +422,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.cancelFlag = cancelFlag;
}
/**
* @param constraintFailureFlag
* the constraintFailureFlag to set
*/
public void setConstraintFailureFlag(boolean constraintFailureFlag)
{
this.constraintFailureFlag = constraintFailureFlag;
}
/**
* @param constraintFlag
* the constraintFlag to set
*/
public void setConstraintFlag(boolean constraintFlag)
{
this.constraintFlag = constraintFlag;
}
/**
* @param currentRun
* the currentRun to set
@ -624,15 +584,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.rootDirectory = rootDirectory;
}
/**
* @param tSDWriter
* the tSDWriter to set
*/
public void setTSDWriter(FileWriter tSDWriter)
{
TSDWriter = tSDWriter;
}
/**
* @return the document
*/
@ -677,14 +628,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return totalRuns;
}
/**
* @return the numSubmodels
*/
public int getNumSubmodels()
{
return numSubmodels;
}
/**
* @return the randomNumberGenerator
*/
@ -693,13 +636,7 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return randomNumberGenerator;
}
/**
* @return the submodels
*/
public Map<String, HierarchicalModel> getSubmodels()
{
return submodels;
}
/**
* @return the topmodel
@ -725,28 +662,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.isGrid = isGrid;
}
/**
* @param numSubmodels
* the numSubmodels to set
*/
public void setNumSubmodels(int numSubmodels)
{
this.numSubmodels = numSubmodels;
}
/**
* @param submodels
* the submodels to set
*/
public void addSubmodel(String id, HierarchicalModel modelstate)
{
if (submodels == null)
{
submodels = new HashMap<String, HierarchicalModel>();
}
submodels.put(id, modelstate);
}
/**
* @param topmodel
* the topmodel to set
@ -756,14 +671,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
this.topmodel = topmodel;
}
public HierarchicalModel getModelState(String id)
{
if (id.equals("topmodel"))
{
return topmodel;
}
return submodels.get(id);
}
public SimType getType()
{
@ -775,9 +682,19 @@ public abstract class HierarchicalSimulation implements ParentSimulator
setCurrentRun(currentRun);
try
{
setTSDWriter(new FileWriter(getOutputDirectory() + "run-" + currentRun + ".tsd"));
setBufferedTSDWriter(new BufferedWriter(getTSDWriter()));
getBufferedTSDWriter().write('(');
writer.init(getOutputDirectory() + "run-" + currentRun + ".tsd");
}
catch (IOException e)
{
e.printStackTrace();
}
}
protected void print()
{
try
{
writer.print();
}
catch (IOException e)
{
@ -785,87 +702,6 @@ public abstract class HierarchicalSimulation implements ParentSimulator
}
}
protected List<ReactionNode> getReactionList()
{
List<ReactionNode> reactions = new ArrayList<ReactionNode>();
List<Integer> indexToSubmodel = new ArrayList<Integer>();
for (HierarchicalModel submodel : modules)
{
for (int i = submodel.getNumOfReactions() - 1; i >= 0; i--)
{
ReactionNode node = submodel.getReaction(i);
reactions.add(node);
indexToSubmodel.add(submodel.getIndex());
node.setIndexToSubmodel(indexToSubmodel);
}
}
return reactions;
}
protected List<EventNode> getEventList()
{
List<EventNode> events = new ArrayList<EventNode>();
for (HierarchicalModel modelstate : modules)
{
if (modelstate.getNumOfEvents() > 0)
{
events.addAll(modelstate.getEvents());
}
}
return events;
}
protected List<VariableNode> getVariableList()
{
List<VariableNode> variableList = new ArrayList<VariableNode>();
List<Integer> indexToSubmodel = new ArrayList<Integer>();
for (HierarchicalModel modelstate : modules)
{
int size = modelstate.getNumOfVariables();
for (int i = 0; i < size; ++i)
{
VariableNode node = modelstate.getVariable(i);
variableList.add(node);
node.setIndexToSubmodel(indexToSubmodel);
indexToSubmodel.add(i);
}
}
return variableList;
}
protected List<ConstraintNode> getConstraintList()
{
List<ConstraintNode> constraints = new ArrayList<ConstraintNode>();
List<Integer> indexToSubmodel = new ArrayList<Integer>();
for (HierarchicalModel modelstate : modules)
{
for (int i = modelstate.getNumOfConstraints() - 1; i >= 0; i--)
{
ConstraintNode node = modelstate.getConstraint(i);
constraints.add(node);
node.setIndexToSubmodel(indexToSubmodel);
indexToSubmodel.add(i);
}
}
return constraints;
}
public double getInitialTime()
{
@ -877,33 +713,12 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return outputStartTime;
}
public void linkPropensities()
{
HierarchicalNode propensity;
totalPropensity = new VariableNode("_totalPropensity", StateType.SCALAR);
for (HierarchicalModel modelstate : modules)
{
if (modelstate.getNumOfReactions() > 0)
{
propensity = modelstate.createPropensity();
for (ReactionNode node : modelstate.getReactions())
{
node.setTotalPropensityRef(totalPropensity);
node.setModelPropensityRef(propensity);
}
}
}
}
/**
* Returns the total propensity of all model states.
*/
protected double getTotalPropensity()
{
return totalPropensity != null ? totalPropensity.getValue(0) : 0;
return totalPropensity != null ? totalPropensity.getVariable().getValue() : 0;
}
public void setTopLevelValue(String variable, double value)
@ -934,19 +749,18 @@ public abstract class HierarchicalSimulation implements ParentSimulator
protected void printToFile()
{
while (currentTime.getValue() >= printTime && printTime <= getTimeLimit())
while (currentTime.getValue() >= printTime.getValue() && printTime.getValue() <= getTimeLimit())
{
try
{
HierarchicalWriter.printToTSD(getBufferedTSDWriter(), getTopmodel(), getSubmodels(), getInterestingSpecies(), getPrintConcentrationSpecies(), printTime);
getBufferedTSDWriter().write(",\n");
writer.print();
}
catch (IOException e)
{
e.printStackTrace();
}
printTime = getRoundedDouble(printTime + getPrintInterval());
printTime.setValue(getRoundedDouble(printTime.getValue() + getPrintInterval()));
if (getRunning() != null)
{
@ -964,48 +778,8 @@ public abstract class HierarchicalSimulation implements ParentSimulator
return newValue;
}
protected void setInitialPropensity()
{
this.initTotalPropensity = totalPropensity.getValue(0);
for (HierarchicalModel state : modules)
{
state.setInitPropensity(0);
for (int i = state.getNumOfReactions() - 1; i >= 0; i--)
{
state.getReactions().get(i).setInitPropensity(0);
}
}
}
protected void restoreInitialPropensity()
{
totalPropensity.setValue(0, initTotalPropensity);
for (HierarchicalModel state : modules)
{
state.restoreInitPropensity(0);
for (int i = state.getNumOfReactions() - 1; i >= 0; i--)
{
state.getReactions().get(i).restoreInitPropensity(state.getIndex());
}
}
}
public List<HierarchicalModel> getListOfModules()
{
return modules;
}
public void setListOfModules(List<HierarchicalModel> modules)
{
this.modules = modules;
}
public void computeAssignmentRules()
protected void computeAssignmentRules()
{
boolean changed = true;
@ -1023,6 +797,49 @@ public abstract class HierarchicalSimulation implements ParentSimulator
}
}
protected void computeEvents()
{
boolean changed = true;
double time = currentTime.getValue();
while (changed)
{
changed = false;
for(HierarchicalModel modelstate : this.modules)
{
int index = modelstate.getIndex();
for (EventNode event : modelstate.getEvents())
{
if(!event.isEnabled(index))
{
if (event.computeEnabled(index, time))
{
triggeredEventList.add(event.getEventState(index));
}
}
}
}
while (triggeredEventList != null && !triggeredEventList.isEmpty())
{
EventState eventState = triggeredEventList.peek();
EventNode event = eventState.getParent();
int index = eventState.getIndex();
if (event.getFireTime(index) <= time)
{
triggeredEventList.poll();
event.fireEvent(index, time);
changed = true;
}
else
{
break;
}
}
}
}
/**
* Calculate fixed-point of initial assignments
*
@ -1030,7 +847,7 @@ public abstract class HierarchicalSimulation implements ParentSimulator
* @param variables
* @param math
*/
public void computeFixedPoint()
protected void computeFixedPoint()
{
boolean changed = true;
@ -1062,9 +879,24 @@ public abstract class HierarchicalSimulation implements ParentSimulator
{
changed = changed | node.computePropensity(modelstate.getIndex());
}
modelstate.getPropensity().computeFunction(modelstate.getIndex());
}
}
}
}
public boolean evaluateConstraints()
{
boolean hasSuccess = true;
for(HierarchicalModel model : modules)
{
for (ConstraintNode constraintNode : model.getConstraints())
{
hasSuccess = hasSuccess && constraintNode.evaluateConstraint(model.getIndex());
}
}
return hasSuccess;
}
}

View file

@ -0,0 +1,64 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState;
public class HierarchicalCSVWriter extends HierarchicalWriter{
private StringBuilder header;
private char separator;
public HierarchicalCSVWriter()
{
super();
this.separator = ',';
this.header = new StringBuilder();
}
@Override
public void print() throws IOException {
bufferedWriter.write("\n");
if(listOfStates.size() > 0)
{
bufferedWriter.write(String.valueOf(listOfStates.get(0).getStateValue()));
for(int i = 1; i < this.listOfStates.size(); ++i)
{
bufferedWriter.write(String.valueOf(separator) + listOfStates.get(i).getStateValue());
}
}
bufferedWriter.flush();
}
@Override
public void addVariable(String id, HierarchicalState state) {
if(header.length() == 0)
{
header.append(id);
}
else
{
header.append(separator + id);
}
listOfStates.add(state);
}
@Override
public void init(String filename) throws IOException {
if(!isSet && header.length() > 0)
{
isSet = true;
}
if(isSet)
{
writer = new FileWriter(filename);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(header.toString());
bufferedWriter.flush();
}
}
}

View file

@ -0,0 +1,66 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState;
public class HierarchicalTSDWriter extends HierarchicalWriter{
private StringBuilder header;
public HierarchicalTSDWriter()
{
super();
header = new StringBuilder();
}
@Override
public void print() throws IOException {
bufferedWriter.write(",\n(");
if(listOfStates.size() > 0)
{
bufferedWriter.write(String.valueOf(listOfStates.get(0).getStateValue()));
for(int i = 1; i < this.listOfStates.size(); ++i)
{
bufferedWriter.write("," + listOfStates.get(i).getStateValue());
}
}
bufferedWriter.write(")");
bufferedWriter.flush();
}
@Override
public void addVariable(String id, HierarchicalState state) {
if(header.length() == 0)
{
header.append("(\"" + id + "\"");
}
else
{
header.append(",\"" + id + "\"");
}
listOfStates.add(state);
}
@Override
public void init(String filename) throws IOException {
if(!isSet && header.length() > 0)
{
header.append(")");
isSet = true;
}
if(isSet)
{
writer = new FileWriter(filename);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(header.toString());
bufferedWriter.flush();
}
}
}

View file

@ -14,14 +14,12 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.io;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState;
/**
*
@ -31,123 +29,26 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalMod
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class HierarchicalWriter
{
public abstract class HierarchicalWriter {
public static void printToTSD(BufferedWriter bufferedWriter, HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels, String[] interesting, Set<String> printConcentrations, double printTime) throws IOException
protected BufferedWriter bufferedWriter;
protected List<HierarchicalState> listOfStates;
protected FileWriter writer;
protected boolean isSet;
public HierarchicalWriter()
{
if (interesting == null || interesting.length == 0)
{
printAllToTSD(printTime, bufferedWriter, topmodel, submodels);
}
else
{
printInterestingToTSD(bufferedWriter, printTime, topmodel, submodels, interesting, printConcentrations);
}
}
public static void setupVariableFromTSD(BufferedWriter bufferedWriter, HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels, String[] interesting) throws IOException
{
bufferedWriter.write("(" + "\"" + "time" + "\"");
if (interesting != null && interesting.length > 0)
{
for (String s : interesting)
{
bufferedWriter.write(",\"" + s + "\"");
}
bufferedWriter.write("),\n");
return;
}
if (topmodel.getNumOfVariables() > 0)
{
for (VariableNode node : topmodel.getVariables())
{
bufferedWriter.write(",\"" + node.getName() + "\"");
}
}
for (HierarchicalModel submodel : submodels.values())
{
if (submodel.getNumOfVariables() > 0)
{
for (VariableNode node : submodel.getVariables())
{
bufferedWriter.write(",\"" + submodel.getID() + " " + node.getName() + "\"");
}
}
}
bufferedWriter.write("),\n");
}
private static void printAllToTSD(double printTime, BufferedWriter bufferedWriter, HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels) throws IOException
{
String commaSpace = ",";
bufferedWriter.write("(");
// print the current time
bufferedWriter.write(printTime + "");
if (topmodel.getNumOfVariables() > 0)
{
for (VariableNode node : topmodel.getVariables())
{
bufferedWriter.write(commaSpace + node.getValue(0));
}
}
for (HierarchicalModel submodel : submodels.values())
{
if (submodel.getNumOfVariables() > 0)
{
for (VariableNode node : submodel.getVariables())
{
bufferedWriter.write(commaSpace + node.getValue(submodel.getIndex()));
}
}
}
bufferedWriter.write(")");
bufferedWriter.flush();
}
private static void printInterestingToTSD(BufferedWriter bufferedWriter, double printTime, HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels, String[] interesting, Set<String> printConcentrations) throws IOException
{
String commaSpace = "";
bufferedWriter.write("(");
commaSpace = "";
// print the current time
bufferedWriter.write(printTime + ",");
for (String s : interesting)
{
String element = s.replaceAll("(.+)__", "");
String id = s.replace("__" + element, "");
HierarchicalModel ms = (id.equals(s)) ? topmodel : submodels.get(id);
VariableNode node = ms.getNode(element);
double value = node.getValue(ms.getIndex());
if (printConcentrations.contains(s))
{
SpeciesNode species = (SpeciesNode) node;
value = species.getConcentration(ms.getIndex());
}
bufferedWriter.write(commaSpace + value);
commaSpace = ",";
}
bufferedWriter.write(")");
bufferedWriter.flush();
listOfStates = new ArrayList<HierarchicalState>();
isSet = false;
}
public abstract void init(String filename) throws IOException;
public abstract void print() throws IOException;
public abstract void addVariable(String id, HierarchicalState state);
}

View file

@ -687,7 +687,7 @@ public final class Evaluator
double value = 0;
if (!species.hasOnlySubstance(index))
if (!species.hasOnlySubstance())
{
value = species.getConcentration(index);
}
@ -702,7 +702,7 @@ public final class Evaluator
{
ReactionNode reaction = (ReactionNode) node;
if (reaction.hasEnoughMolecules())
if (reaction.hasEnoughMoleculesFd(index))
{
return reaction.getValue(index);
}

View file

@ -14,7 +14,11 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
/**
*
@ -32,33 +36,30 @@ public class EventNode extends HierarchicalNode
private boolean isPersistent;
private boolean useTriggerValue;
private boolean isEnabled;
private double fireTime;
private double maxDisabledTime;
private double minEnabledTime;
private double priority;
private double[] assignmentValues;
List<FunctionNode> eventAssignments;
public EventNode(Type type)
{
super(type);
maxDisabledTime = Double.NEGATIVE_INFINITY;
minEnabledTime = Double.POSITIVE_INFINITY;
fireTime = Double.POSITIVE_INFINITY;
}
Map<Integer, EventState> eventState;
public EventNode(HierarchicalNode trigger)
{
super(Type.PLUS);
this.addChild(trigger);
maxDisabledTime = Double.NEGATIVE_INFINITY;
minEnabledTime = Double.POSITIVE_INFINITY;
fireTime = Double.POSITIVE_INFINITY;
eventState = new HashMap<Integer, EventState>();
}
public EventState addEventState(int index)
{
EventState state = new EventState(index, this);
eventState.put(index, state);
return state;
}
public EventState getEventState(int index)
{
return eventState.get(index);
}
public HierarchicalNode getDelayValue()
{
return delayValue;
@ -89,44 +90,44 @@ public class EventNode extends HierarchicalNode
this.useTriggerValue = useTriggerValue;
}
public boolean isEnabled()
public boolean isEnabled(int index)
{
return isEnabled;
return eventState.get(index).isEnabled();
}
public void setEnabled(boolean isEnabled)
public void setEnabled(int index, boolean isEnabled)
{
this.isEnabled = isEnabled;
eventState.get(index).setEnabled(isEnabled);
}
public double getFireTime()
public double getFireTime(int index)
{
return fireTime;
return eventState.get(index).getFireTime();
}
public void setFireTime(double fireTime)
public void setFireTime(int index, double fireTime)
{
this.fireTime = fireTime;
eventState.get(index).setFireTime(fireTime);
}
public double getMaxDisabledTime()
public double getMaxDisabledTime(int index)
{
return maxDisabledTime;
return eventState.get(index).getMaxDisabledTime();
}
public void setMaxDisabledTime(double maxDisabledTime)
public void setMaxDisabledTime(int index, double maxDisabledTime)
{
this.maxDisabledTime = maxDisabledTime;
eventState.get(index).setMaxDisabledTime(maxDisabledTime);
}
public double getMinEnabledTime()
public double getMinEnabledTime(int index)
{
return minEnabledTime;
return eventState.get(index).getMinEnabledTime();
}
public void setMinEnabledTime(double minEnabledTime)
public void setMinEnabledTime(int index, double minEnabledTime)
{
this.minEnabledTime = minEnabledTime;
eventState.get(index).setMinEnabledTime(minEnabledTime);
}
public void addEventAssignment(FunctionNode eventAssignmentNode)
@ -142,58 +143,68 @@ public class EventNode extends HierarchicalNode
public boolean computeEnabled(int index, double time)
{
if (maxDisabledTime >= 0 && maxDisabledTime <= minEnabledTime && minEnabledTime <= time)
EventState state = eventState.get(index);
if (state.getMaxDisabledTime() >= 0 && state.getMaxDisabledTime() <= state.getMinEnabledTime() && state.getMinEnabledTime() <= time)
{
isEnabled = true;
state.setEnabled(true);
if (priorityValue != null)
{
priority = Evaluator.evaluateExpressionRecursive(priorityValue, 0);
state.setPriority(Evaluator.evaluateExpressionRecursive(priorityValue, index));
}
double fireTime = time;
if (delayValue != null)
{
fireTime = time + Evaluator.evaluateExpressionRecursive(delayValue, 0);
}
else
{
fireTime = time;
fireTime += Evaluator.evaluateExpressionRecursive(delayValue, index);
}
state.setFireTime(fireTime);
if (useTriggerValue)
{
computeEventAssignmentValues(0, time);
computeEventAssignmentValues(index, time);
}
}
return isEnabled;
return state.isEnabled();
}
public void fireEvent(int index, double time)
{
if (isEnabled && fireTime <= time)
EventState state = eventState.get(index);
if (state.isEnabled() && state.getFireTime() <= time)
{
isEnabled = false;
maxDisabledTime = Double.NEGATIVE_INFINITY;
minEnabledTime = Double.POSITIVE_INFINITY;
state.setEnabled(false);
state.setPriority(0);
state.setMaxDisabledTime(Double.NEGATIVE_INFINITY);
state.setMinEnabledTime(Double.POSITIVE_INFINITY);
if (!isPersistent)
{
if (!computeTrigger(index))
{
maxDisabledTime = time;
state.setMaxDisabledTime(time);
return;
}
}
if (!useTriggerValue)
if (useTriggerValue)
{
computeEventAssignmentValues(index, time);
double[] assignmentValues = state.getAssignmentValues();
for (int i = 0; i < eventAssignments.size(); i++)
{
FunctionNode eventAssignmentNode = eventAssignments.get(i);
VariableNode variable = eventAssignmentNode.getVariable();
variable.setValue(index, assignmentValues[i]);
}
}
for (int i = 0; i < eventAssignments.size(); i++)
else
{
FunctionNode eventAssignmentNode = eventAssignments.get(i);
VariableNode variable = eventAssignmentNode.getVariable();
variable.setValue(index, assignmentValues[i]);
for(FunctionNode node : eventAssignments)
{
node.computeFunction(index);
}
}
isTriggeredAtTime(time, index);
}
@ -202,18 +213,19 @@ public class EventNode extends HierarchicalNode
private void computeEventAssignmentValues(int index, double time)
{
assignmentValues = new double[eventAssignments.size()];
double[] assignmentValues = new double[eventAssignments.size()];
eventState.get(index).setAssignmentValues(assignmentValues);
for (int i = 0; i < eventAssignments.size(); i++)
{
FunctionNode eventAssignmentNode = eventAssignments.get(i);
VariableNode variable = eventAssignmentNode.getVariable();
double value = Evaluator.evaluateExpressionRecursive(eventAssignmentNode, false, 0);
double value = Evaluator.evaluateExpressionRecursive(eventAssignmentNode, false, index);
if (variable.isSpecies())
{
SpeciesNode species = (SpeciesNode) variable;
if (!species.hasOnlySubstance(index))
if (!species.hasOnlySubstance())
{
assignmentValues[i] = value * species.getCompartment().getValue(0);
assignmentValues[i] = value * species.getCompartment().getValue(index);
continue;
}
}
@ -223,6 +235,7 @@ public class EventNode extends HierarchicalNode
public boolean computeTrigger(int index)
{
double triggerResult = Evaluator.evaluateExpressionRecursive(this, index);
return triggerResult != 0;
}
@ -230,38 +243,33 @@ public class EventNode extends HierarchicalNode
public boolean isTriggeredAtTime(double time, int index)
{
boolean trigger = computeTrigger(index);
EventState state = eventState.get(index);
if (trigger)
{
if (maxDisabledTime >= 0 && time > maxDisabledTime && time < minEnabledTime)
if(state.getMaxDisabledTime() >= 0 && time > state.getMaxDisabledTime() && time < state.getMinEnabledTime())
{
minEnabledTime = time;
state.setMinEnabledTime(time);
}
return maxDisabledTime >= 0 && minEnabledTime <= time;
return state.getMaxDisabledTime() >= 0 && state.getMinEnabledTime() <= time;
}
else
{
if (time > maxDisabledTime)
if (time > state.getMaxDisabledTime())
{
maxDisabledTime = time;
state.setMaxDisabledTime(time);
}
return false;
}
}
public double getPriority()
public double getPriority(int index)
{
if (isEnabled)
{
return priority;
}
return 0;
EventState state = eventState.get(index);
return state.getPriority();
}
public HierarchicalNode getPriorityValue()
{
return priorityValue;
}
public void setPriorityValue(HierarchicalNode priorityValue)
{
@ -272,16 +280,4 @@ public class EventNode extends HierarchicalNode
{
return eventAssignments;
}
public void setEventAssignments(List<FunctionNode> eventAssignments)
{
this.eventAssignments = eventAssignments;
}
@Override
public EventNode clone()
{
// TODO
return null;
}
}

View file

@ -43,8 +43,15 @@ public class FunctionNode extends HierarchicalNode
public FunctionNode(HierarchicalNode math)
{
super(Type.PLUS);
this.addChild(math);
super(math.getType());
if(math.getNumOfChild() > 0)
{
for(HierarchicalNode node : math.getChildren())
{
this.addChild(node);
}
}
}

View file

@ -38,7 +38,6 @@ public class HierarchicalNode extends AbstractHierarchicalNode
private List<HierarchicalNode> children;
private ArrayNode arrayNode;
protected HierarchicalState state;
protected List<Integer> indexToSubmodel;
public HierarchicalNode(Type type)
{
@ -167,7 +166,6 @@ public class HierarchicalNode extends AbstractHierarchicalNode
{
state = new ValueState();
}
//TODO: error on else
return state;
}
@ -178,8 +176,7 @@ public class HierarchicalNode extends AbstractHierarchicalNode
public void setValue(int index, double value)
{
//TODO:
state.setStateValue(value);
state.setStateValue(index, value);
}
public double getValue()
@ -189,7 +186,7 @@ public class HierarchicalNode extends AbstractHierarchicalNode
public double getValue(int index)
{
return state.getStateValue();
return state.getStateValue(index);
}
public double getRate()
@ -207,17 +204,6 @@ public class HierarchicalNode extends AbstractHierarchicalNode
return state;
}
public void setIndexToSubmodel(List<Integer> indexToSubmodel)
{
this.indexToSubmodel = indexToSubmodel;
}
public int getSubmodelIndex(int index)
{
return indexToSubmodel.get(index);
}
@Override
public String report()
{

View file

@ -14,10 +14,14 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.math;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.ReactionState;
/**
*
*
@ -31,21 +35,16 @@ public class ReactionNode extends VariableNode
private List<SpeciesReferenceNode> reactants;
private List<SpeciesReferenceNode> products;
private Map<String, VariableNode> localParameters;
private HierarchicalNode forwardRate;
private HierarchicalNode reverseRate;
private boolean hasEnoughMoleculesFd;
private boolean hasEnoughMoleculesRv;
private double forwardRateValue;
private double reverseRateValue;
private HierarchicalNode totalPropensityRef;
private HierarchicalNode modelPropensityRef;
private double initPropensity;
private double initForwardPropensity;
private Map<Integer, ReactionState> reactionState;
public ReactionNode(String name)
{
super(name);
isReaction = true;
reactionState = new HashMap<Integer, ReactionState>();
}
public ReactionNode(ReactionNode copy)
@ -54,6 +53,12 @@ public class ReactionNode extends VariableNode
isReaction = true;
}
public ReactionState addReactionState(int index)
{
ReactionState state = new ReactionState();
reactionState.put(index, state);
return state;
}
public List<SpeciesReferenceNode> getListOfReactants()
{
return reactants;
@ -95,31 +100,17 @@ public class ReactionNode extends VariableNode
return forwardRate;
}
public boolean hasEnoughMolecules()
{
return hasEnoughMoleculesFd;
}
public boolean computePropensity(int index)
{
double oldValue = getValue(index);
if (forwardRate != null)
{
forwardRateValue = Evaluator.evaluateExpressionRecursive(forwardRate, index);
double forwardRateValue = Evaluator.evaluateExpressionRecursive(forwardRate, index);
setValue(index, forwardRateValue);
}
if (reverseRate != null)
{
reverseRateValue = Evaluator.evaluateExpressionRecursive(reverseRate, index);
setValue(index, forwardRateValue + reverseRateValue);
}
if (totalPropensityRef != null)
{
totalPropensityRef.setValue(index, totalPropensityRef.getValue(index) + (getValue(index) - oldValue));
}
if (modelPropensityRef != null)
{
modelPropensityRef.setValue(index, modelPropensityRef.getValue(index) + (getValue(index) - oldValue));
//TODO
}
return oldValue != getValue(index);
}
@ -151,6 +142,7 @@ public class ReactionNode extends VariableNode
dependentReactions.addAll(speciesNode.getReactionDependents());
}
}
computePropensity(index);
updateDependentReactions(index, dependentReactions);
}
}
@ -158,14 +150,15 @@ public class ReactionNode extends VariableNode
public void fireReaction(int index, double threshold)
{
computeNotEnoughEnoughMolecules(index);
if (forwardRateValue >= threshold)
{
fireReaction(index, hasEnoughMoleculesFd, reactants, products);
}
else
{
fireReaction(index, hasEnoughMoleculesRv, products, reactants);
}
ReactionState state = reactionState.get(index);
// if (state.getForwardRateValue() >= threshold)
// {
fireReaction(index, state.hasEnoughMoleculesFd(), reactants, products);
// }
// else
// {
// fireReaction(index, state.hasEnoughMoleculesRv(), products, reactants);
// }
}
private void updateDependentReactions(int index, Set<ReactionNode> dependentReactions)
@ -178,28 +171,29 @@ public class ReactionNode extends VariableNode
public void computeNotEnoughEnoughMolecules(int index)
{
hasEnoughMoleculesFd = true;
ReactionState state = reactionState.get(index);
state.setHasEnoughMoleculesFd(true);
if (reactants != null)
{
for (SpeciesReferenceNode specRef : reactants)
{
if (specRef.getSpecies().getValue(index) < specRef.getValue(index))
{
hasEnoughMoleculesFd = false;
state.setHasEnoughMoleculesFd(false);
break;
}
}
}
if (reverseRate != null)
{
hasEnoughMoleculesRv = true;
state.setHasEnoughMoleculesRv(true);
if (products != null)
{
for (SpeciesReferenceNode specRef : products)
{
if (specRef.getSpecies().getValue(index) < specRef.getValue(index))
{
hasEnoughMoleculesRv = false;
state.setHasEnoughMoleculesRv(false);
return;
}
}
@ -207,16 +201,6 @@ public class ReactionNode extends VariableNode
}
}
public void setModelPropensityRef(HierarchicalNode ref)
{
this.modelPropensityRef = ref;
}
public void setTotalPropensityRef(HierarchicalNode ref)
{
this.totalPropensityRef = ref;
}
public void setReverseRate(HierarchicalNode rate)
{
this.reverseRate = rate;
@ -224,16 +208,31 @@ public class ReactionNode extends VariableNode
public void setInitPropensity(int index)
{
int subModel = indexToSubmodel.get(index);
this.initPropensity = getValue(subModel);
this.initForwardPropensity = forwardRateValue;
ReactionState state = reactionState.get(index);
state.setInitPropensity(getValue(index));
state.setInitForwardPropensity(state.getForwardRateValue());
}
public void addLocalParameter(String id, VariableNode node)
{
if(localParameters == null)
{
localParameters = new HashMap<String, VariableNode>();
}
localParameters.put(id, node);
}
public Map<String, VariableNode> getLocalParameters()
{
return localParameters;
}
public void restoreInitPropensity(int index)
{
setValue(index, initPropensity);
this.forwardRateValue = initForwardPropensity;
this.reverseRateValue = getValue(index) - forwardRateValue;
ReactionState state = reactionState.get(index);
setValue(index, state.getInitPropensity());
state.setForwardRateValue(state.getInitForwardPropensity());
state.setReverseRateValue(state.getInitPropensity() - state.getInitForwardPropensity());
}
@Override
@ -241,4 +240,8 @@ public class ReactionNode extends VariableNode
{
return new ReactionNode(this);
}
public boolean hasEnoughMoleculesFd(int index) {
return reactionState.get(index).hasEnoughMoleculesFd();
}
}

View file

@ -13,9 +13,6 @@
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.math;
import java.util.ArrayList;
import java.util.List;
/**
*
*
@ -29,7 +26,7 @@ public class SpeciesNode extends VariableNode
private VariableNode compartment;
private HierarchicalNode odeRate;
private List<SpeciesTemplate> speciesTemplates;
private SpeciesTemplate speciesTemplates;
public SpeciesNode(String name)
{
@ -58,44 +55,29 @@ public class SpeciesNode extends VariableNode
return this.getValue(index) / compartment.getValue(index);
}
public void createSpeciesTemplate(int index)
public void createSpeciesTemplate()
{
if(speciesTemplates == null)
{
speciesTemplates = new ArrayList<SpeciesTemplate>();
}
while(speciesTemplates.size() <= index)
{
speciesTemplates.add(null);
}
if(speciesTemplates.get(index) == null)
{
SpeciesTemplate speciesTemplate = new SpeciesTemplate();
speciesTemplates.set(index, speciesTemplate);
}
speciesTemplates = new SpeciesTemplate();
}
public boolean isBoundaryCondition(int index)
public boolean isBoundaryCondition()
{
return speciesTemplates.get(index).isBoundary;
return speciesTemplates.isBoundary;
}
public void setBoundaryCondition(boolean isBoundary, int index)
public void setBoundaryCondition(boolean isBoundary)
{
speciesTemplates.get(index).isBoundary = isBoundary;
speciesTemplates.isBoundary = isBoundary;
}
public boolean hasOnlySubstance(int index)
public boolean hasOnlySubstance()
{
return speciesTemplates.get(index).hasOnlySubstance;
return speciesTemplates.hasOnlySubstance;
}
public void setHasOnlySubstance(boolean substance, int index)
public void setHasOnlySubstance(boolean substance)
{
speciesTemplates.get(index).hasOnlySubstance = substance;
speciesTemplates.hasOnlySubstance = substance;
}
public HierarchicalNode getODERate()
@ -144,7 +126,7 @@ public class SpeciesNode extends VariableNode
{
rate = Evaluator.evaluateExpressionRecursive(rateRule, false, index);
if (!speciesTemplates.get(index).hasOnlySubstance)
if (!speciesTemplates.hasOnlySubstance)
{
double compartmentChange = compartment.computeRateOfChange(index, time);
if (compartmentChange != 0)
@ -157,7 +139,7 @@ public class SpeciesNode extends VariableNode
rate = rate * compartment.getValue(index);
}
}
else if (odeRate != null && !speciesTemplates.get(index).isBoundary)
else if (odeRate != null && !speciesTemplates.isBoundary)
{
rate = Evaluator.evaluateExpressionRecursive(odeRate, index);
}
@ -165,7 +147,7 @@ public class SpeciesNode extends VariableNode
return rate;
}
else if (odeRate != null && !speciesTemplates.get(index).isBoundary)
else if (odeRate != null && !speciesTemplates.isBoundary)
{
rate = Evaluator.evaluateExpressionRecursive(odeRate, index);
}

View file

@ -22,8 +22,10 @@ import javax.xml.stream.XMLStreamException;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import edu.utah.ece.async.analysis.fba.FluxBalanceAnalysis;
import edu.utah.ece.async.analysis.simulation.hierarchical.HierarchicalSimulation;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
/**
@ -72,7 +74,7 @@ public class HierarchicalFBASimulator extends HierarchicalSimulation
HierarchicalModel topmodel = getTopmodel();
for (String reaction : flux.keySet())
{
topmodel.getNode(reaction).setValue(0, flux.get(reaction));
topmodel.getNode(reaction).setValue(topmodel.getIndex(), flux.get(reaction));
}
}
@ -117,7 +119,13 @@ public class HierarchicalFBASimulator extends HierarchicalSimulation
HierarchicalModel topmodel = getTopmodel();
for (String name : values.keySet())
{
values.put(name, topmodel.getNode(name).getValue(0));
VariableNode node = topmodel.getNode(name);
double value = node.getValue(topmodel.getIndex());
if(Math.abs(value) < 1e-9)
{
value = 0;
}
values.put(name, value);
}
}

View file

@ -14,6 +14,7 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.methods;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.swing.JFrame;
@ -23,11 +24,9 @@ import javax.xml.stream.XMLStreamException;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.HierarchicalSimulation;
import edu.utah.ece.async.analysis.simulation.hierarchical.io.HierarchicalWriter;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.setup.ModelSetup;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
@ -61,11 +60,13 @@ public final class HierarchicalMixedSimulator extends HierarchicalSimulation
{
setCurrentTime(0);
this.wrapper = new VectorWrapper(initValues);
ModelSetup.setupModels(this, ModelType.HODE, wrapper);
computeFixedPoint();
setupForOutput(runNumber);
HierarchicalWriter.setupVariableFromTSD(getBufferedTSDWriter(), getTopmodel(), getSubmodels(), getInterestingSpecies());
setupForOutput(runNumber);
isInitialized = true;
}
@ -91,13 +92,13 @@ public final class HierarchicalMixedSimulator extends HierarchicalSimulation
}
}
double nextEndTime = currentTime.getValue(0);
while (currentTime.getValue(0) < timeLimit)
while (currentTime.getValue() < timeLimit)
{
nextEndTime = currentTime.getValue(0) + getMaxTimeStep();
nextEndTime = currentTime.getValue() + getMaxTimeStep();
if (nextEndTime > printTime)
if (nextEndTime > printTime.getValue())
{
nextEndTime = printTime;
nextEndTime = printTime.getValue();
}
if (nextEndTime > getTimeLimit())
@ -112,20 +113,10 @@ public final class HierarchicalMixedSimulator extends HierarchicalSimulation
odeSim.simulate();
currentTime.setValue(0, nextEndTime);
currentTime.setValue(nextEndTime);
printToFile();
}
try
{
getBufferedTSDWriter().write(')');
getBufferedTSDWriter().flush();
}
catch (IOException e)
{
}
}
@Override
@ -143,20 +134,10 @@ public final class HierarchicalMixedSimulator extends HierarchicalSimulation
{
}
public void createODESim(HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels)
public void createODESim(HierarchicalModel topmodel, List<HierarchicalModel> odeModels) throws IOException, XMLStreamException
{
try
{
odeSim = new HierarchicalODERKSimulator(this, topmodel, submodels);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
odeSim = new HierarchicalODERKSimulator(this, topmodel);
odeSim.setListOfHierarchicalModels(odeModels);
}
public void createSSASim(HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels)
@ -176,5 +157,10 @@ public final class HierarchicalMixedSimulator extends HierarchicalSimulation
// TODO Auto-generated method stub
}
VectorWrapper getVectorWrapper()
{
return this.wrapper;
}
}

View file

@ -14,8 +14,6 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.methods;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import javax.swing.JFrame;
@ -24,6 +22,7 @@ import javax.xml.stream.XMLStreamException;
import org.apache.commons.math3.exception.DimensionMismatchException;
import org.apache.commons.math3.exception.MaxCountExceededException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.ode.FirstOrderDifferentialEquations;
import org.apache.commons.math3.ode.events.EventHandler;
import org.apache.commons.math3.ode.nonstiff.HighamHall54Integrator;
@ -35,6 +34,7 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.HierarchicalEventComparator;
@ -42,398 +42,309 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.util.setup.ModelSetup
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim
* Contributors </a>
* @version %I%
*/
public final class HierarchicalODERKSimulator extends HierarchicalSimulation
{
private boolean isSingleStep;
private HighamHall54Integrator odecalc;
private double relativeError, absoluteError;
private DifferentialEquations de;
private List<ReactionNode> reactionList;
private List<EventNode> eventList;
private PriorityQueue<EventNode> triggeredEventList;
private final VectorWrapper vectorWrapper;
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory, double timeLimit) throws IOException, XMLStreamException, BioSimException
{
public final class HierarchicalODERKSimulator extends HierarchicalSimulation {
this(SBMLFileName, rootDirectory, rootDirectory, 0, timeLimit, Double.POSITIVE_INFINITY, 0, null, Double.POSITIVE_INFINITY, 0, null, null, 1, 1e-6, 1e-9, "amount", "none", 0, 0, false);
isInitialized = false;
isSingleStep = true;
this.printTime = Double.POSITIVE_INFINITY;
}
private boolean isSingleStep;
private HighamHall54Integrator odecalc;
private double relativeError, absoluteError;
private DifferentialEquations de;
private final VectorWrapper vectorWrapper;
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running, String[] interestingSpecies, int numSteps,
double relError, double absError, String quantityType, String abstraction, double initialTime, double outputStartTime) throws IOException, XMLStreamException, BioSimException
{
this(SBMLFileName, rootDirectory, outputDirectory, runs, timeLimit, maxTimeStep, randomSeed, progress, printInterval, stoichAmpValue, running, interestingSpecies, numSteps, relError, absError, quantityType, abstraction, initialTime, outputStartTime, true);
this.isInitialized = false;
this.isSingleStep = false;
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory,
double timeLimit) throws IOException, XMLStreamException, BioSimException {
this(SBMLFileName, rootDirectory, rootDirectory, 0, timeLimit,
Double.POSITIVE_INFINITY, 0, null, Double.POSITIVE_INFINITY, 0, null,
null, 1, 1e-6, 1e-9, "amount", "none", 0, 0, false);
isInitialized = false;
isSingleStep = true;
this.printTime.setValue(Double.POSITIVE_INFINITY);
}
}
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running, String[] interestingSpecies, int numSteps,
double relError, double absError, String quantityType, String abstraction, double initialTime, double outputStartTime, boolean print) throws IOException, XMLStreamException, BioSimException
{
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory,
String outputDirectory, int runs, double timeLimit, double maxTimeStep,
long randomSeed, JProgressBar progress, double printInterval,
double stoichAmpValue, JFrame running, String[] interestingSpecies,
int numSteps, double relError, double absError, String quantityType,
String abstraction, double initialTime, double outputStartTime)
throws IOException, XMLStreamException, BioSimException {
this(SBMLFileName, rootDirectory, outputDirectory, runs, timeLimit,
maxTimeStep, randomSeed, progress, printInterval, stoichAmpValue, running,
interestingSpecies, numSteps, relError, absError, quantityType,
abstraction, initialTime, outputStartTime, true);
this.isInitialized = false;
this.isSingleStep = false;
}
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs, timeLimit, maxTimeStep, 0.0, progress, printInterval, stoichAmpValue, running, interestingSpecies, quantityType, abstraction, initialTime, outputStartTime, SimType.HODE);
this.relativeError = relError;
this.absoluteError = absError;
this.isSingleStep = false;
this.absoluteError = absoluteError == 0 ? 1e-12 : absoluteError;
this.relativeError = absoluteError == 0 ? 1e-9 : relativeError;
this.printTime = outputStartTime;
this.vectorWrapper = new VectorWrapper(initValues);
if (numSteps > 0)
{
setPrintInterval(timeLimit / numSteps);
}
odecalc = new HighamHall54Integrator(getMinTimeStep(), getMaxTimeStep(), absoluteError, relativeError);
isInitialized = false;
public HierarchicalODERKSimulator(String SBMLFileName, String rootDirectory,
String outputDirectory, int runs, double timeLimit, double maxTimeStep,
long randomSeed, JProgressBar progress, double printInterval,
double stoichAmpValue, JFrame running, String[] interestingSpecies,
int numSteps, double relError, double absError, String quantityType,
String abstraction, double initialTime, double outputStartTime,
boolean print) throws IOException, XMLStreamException, BioSimException {
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs,
timeLimit, maxTimeStep, 0.0, progress, printInterval, stoichAmpValue,
running, interestingSpecies, quantityType, abstraction, initialTime,
outputStartTime, SimType.HODE);
this.relativeError = relError;
this.absoluteError = absError;
this.isSingleStep = false;
this.absoluteError = absoluteError == 0 ? 1e-12 : absoluteError;
this.relativeError = absoluteError == 0 ? 1e-9 : relativeError;
this.printTime.setValue(outputStartTime);
this.vectorWrapper = new VectorWrapper(initValues);
if (numSteps > 0) {
setPrintInterval(timeLimit / numSteps);
}
odecalc = new HighamHall54Integrator(getMinTimeStep(), getMaxTimeStep(),
absoluteError, relativeError);
isInitialized = false;
}
}
public HierarchicalODERKSimulator(HierarchicalMixedSimulator sim, HierarchicalModel topmodel, Map<String, HierarchicalModel> submodels) throws IOException, XMLStreamException
{
super(sim);
this.relativeError = 1e-6;
this.absoluteError = 1e-9;
this.odecalc = new HighamHall54Integrator(getMinTimeStep(), getMaxTimeStep(), absoluteError, relativeError);
this.isInitialized = true;
this.isSingleStep = true;
this.printTime = Double.POSITIVE_INFINITY;
public HierarchicalODERKSimulator(HierarchicalMixedSimulator sim,
HierarchicalModel topmodel) throws IOException, XMLStreamException {
super(sim);
this.relativeError = 1e-6;
this.absoluteError = 1e-9;
this.odecalc = new HighamHall54Integrator(getMinTimeStep(),
getMaxTimeStep(), absoluteError, relativeError);
this.isInitialized = true;
this.isSingleStep = true;
this.printTime.setValue(Double.POSITIVE_INFINITY);
this.vectorWrapper = sim.getVectorWrapper();
de = new DifferentialEquations();
if (sim.hasEvents()) {
HierarchicalEventHandler handler = new HierarchicalEventHandler();
HierarchicalTriggeredEventHandler triggeredHandler =
new HierarchicalTriggeredEventHandler();
odecalc.addEventHandler(handler, getPrintInterval(), 1e-20, 10000);
odecalc.addEventHandler(triggeredHandler, getPrintInterval(), 1e-20,
10000);
triggeredEventList =
new PriorityQueue<EventState>(1, new HierarchicalEventComparator());
computeEvents();
}
}
this.eventList = getEventList();
this.variableList = getVariableList();
this.reactionList = getReactionList();
this.vectorWrapper = new VectorWrapper(initValues);
de = new DifferentialEquations();
if (!eventList.isEmpty())
{
HierarchicalEventHandler handler = new HierarchicalEventHandler();
HierarchicalTriggeredEventHandler triggeredHandler = new HierarchicalTriggeredEventHandler();
odecalc.addEventHandler(handler, getPrintInterval(), 1e-20, 10000);
odecalc.addEventHandler(triggeredHandler, getPrintInterval(), 1e-20, 10000);
triggeredEventList = new PriorityQueue<EventNode>(0, new HierarchicalEventComparator());
@Override
public void cancel() {
setCancelFlag(true);
}
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, currentTime.getValue(0));
}
vectorWrapper.initStateValues();
}
@Override
public void clear() {
}
@Override
public void cancel()
{
setCancelFlag(true);
}
@Override
public void clear()
{
}
@Override
public void initialize(long randomSeed, int runNumber) throws IOException, XMLStreamException
{
if (!isInitialized)
{
setCurrentTime(getInitialTime());
ModelSetup.setupModels(this, ModelType.HODE, vectorWrapper);
eventList = getEventList();
variableList = getVariableList();
reactionList = getReactionList();
de = new DifferentialEquations();
computeFixedPoint();
if (!eventList.isEmpty())
{
HierarchicalEventHandler handler = new HierarchicalEventHandler();
HierarchicalTriggeredEventHandler triggeredHandler = new HierarchicalTriggeredEventHandler();
odecalc.addEventHandler(handler, getPrintInterval(), 1e-20, 10000);
odecalc.addEventHandler(triggeredHandler, getPrintInterval(), 1e-20, 10000);
triggeredEventList = new PriorityQueue<EventNode>(1, new HierarchicalEventComparator());
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, currentTime.getValue());
}
vectorWrapper.initStateValues();
if (!isSingleStep)
{
setupForOutput(runNumber);
HierarchicalWriter.setupVariableFromTSD(getBufferedTSDWriter(), getTopmodel(), getSubmodels(), getInterestingSpecies());
}
isInitialized = true;
}
}
@Override
public void simulate()
{
if (!isInitialized)
{
try
{
initialize(0, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
}
double nextEndTime = 0;
while (currentTime.getValue() < getTimeLimit() && !isCancelFlag())
{
// if (!HierarchicalUtilities.evaluateConstraints(constraintList))
// {
// return;
// }
nextEndTime = currentTime.getValue() + getMaxTimeStep();
if (nextEndTime > printTime)
{
nextEndTime = printTime;
}
if (nextEndTime > getTimeLimit())
{
nextEndTime = getTimeLimit();
}
if (vectorWrapper.getSize() > 0)
{
try
{
odecalc.integrate(de, currentTime.getValue(0), vectorWrapper.getValues(), nextEndTime, vectorWrapper.getValues());
computeAssignmentRules();
}
catch (Exception e)
{
setCurrentTime(nextEndTime);
}
}
else
{
setCurrentTime(nextEndTime);
}
if (!isSingleStep)
{
printToFile();
}
}
if (!isSingleStep)
{
try
{
getBufferedTSDWriter().write(')');
getBufferedTSDWriter().flush();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
@Override
public void setupForNewRun(int newRun)
{
}
@Override
public void printStatisticsTSD()
{
// TODO Auto-generated method stub
}
public class HierarchicalEventHandler implements EventHandler
{
private double value = -1;
@Override
public void init(double t0, double[] y0, double t)
{
}
@Override
public double g(double t, double[] y)
{
double returnValue = -value;
currentTime.setValue(0, t);
for (int i = 0; i < y.length; i++)
{
VariableNode node = variableList.get(i);
node.setValue(0, y[i]);
}
for (int i = eventList.size()-1; i >= 0; i--)
{
EventNode event = eventList.get(i);
if (event.isTriggeredAtTime(t, 0))
{
returnValue = value;
}
}
return returnValue;
}
@Override
public Action eventOccurred(double t, double[] y, boolean increasing)
{
value = -value;
currentTime.setValue(0, t);
for (int i = 0; i < y.length; i++)
{
VariableNode variableNode = variableList.get(i);
variableNode.setValue(0, y[i]);
}
computeAssignmentRules();
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, t);
computeAssignmentRules();
for (int i = 0; i < y.length; i++)
{
VariableNode variableNode = variableList.get(i);
//TODO
y[i] = variableNode.getValue(0);
@Override
public void initialize(long randomSeed, int runNumber)
throws IOException, XMLStreamException {
if (!isInitialized) {
setCurrentTime(getInitialTime());
ModelSetup.setupModels(this, ModelType.HODE, vectorWrapper);
de = new DifferentialEquations();
computeFixedPoint();
if (hasEvents()) {
HierarchicalEventHandler handler = new HierarchicalEventHandler();
HierarchicalTriggeredEventHandler triggeredHandler =
new HierarchicalTriggeredEventHandler();
odecalc.addEventHandler(handler, getPrintInterval(), 1e-20, 10000);
odecalc.addEventHandler(triggeredHandler, getPrintInterval(), 1e-20,
10000);
triggeredEventList =
new PriorityQueue<EventState>(1, new HierarchicalEventComparator());
computeEvents();
}
return EventHandler.Action.STOP;
}
@Override
public void resetState(double t, double[] y)
{
// TODO Auto-generated method stub
}
}
public class HierarchicalTriggeredEventHandler implements EventHandler
{
private double value = -1;
@Override
public void init(double t0, double[] y0, double t)
{
}
@Override
public double g(double t, double[] y)
{
currentTime.setValue(0, t);
if (!triggeredEventList.isEmpty())
{
if (triggeredEventList.peek().getFireTime() <= t)
{
return value;
}
}
return -value;
}
@Override
public Action eventOccurred(double t, double[] y, boolean increasing)
{
value = -value;
currentTime.setValue(0, t);
for (int i = 0; i < y.length; i++)
{
VariableNode variableNode = variableList.get(i);
//TODO
variableNode.setValue(0, y[i]);
}
computeAssignmentRules();
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, t);
computeAssignmentRules();
for (int i = 0; i < y.length; i++)
{
VariableNode variableNode = variableList.get(i);
//TODO
y[i] = variableNode.getValue(0);
if (!isSingleStep) {
setupForOutput(runNumber);
}
return EventHandler.Action.STOP;
}
isInitialized = true;
}
}
@Override
public void resetState(double t, double[] y)
{
// TODO Auto-generated method stub
}
}
public class DifferentialEquations implements FirstOrderDifferentialEquations
{
@Override
public int getDimension()
{
return vectorWrapper.getSize();
}
public void computeReactionPropensities()
{
for (int i = reactionList.size() - 1; i >= 0; i--)
{
ReactionNode reaction = reactionList.get(i);
reaction.computePropensity(reaction.getSubmodelIndex(i));
@Override
public void simulate() {
if (!isInitialized) {
try {
initialize(0, 1);
} catch (IOException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
}
}
@Override
public void computeDerivatives(double t, double[] y, double[] yDot) throws MaxCountExceededException, DimensionMismatchException
{
double nextEndTime = 0;
while (currentTime.getValue() < getTimeLimit() && !isCancelFlag()) {
// if (!HierarchicalUtilities.evaluateConstraints(constraintList))
// {
// return;
// }
nextEndTime = currentTime.getValue() + getMaxTimeStep();
if (nextEndTime > printTime.getValue()) {
nextEndTime = printTime.getValue();
}
if (nextEndTime > getTimeLimit()) {
nextEndTime = getTimeLimit();
}
if (vectorWrapper.getSize() > 0) {
try {
odecalc.integrate(de, currentTime.getValue(),
vectorWrapper.getValues(), nextEndTime, vectorWrapper.getValues());
computeAssignmentRules();
} catch (NumberIsTooSmallException e) {
setCurrentTime(nextEndTime);
}
} else {
setCurrentTime(nextEndTime);
}
if (!isSingleStep) {
printToFile();
}
}
if (!isSingleStep) {
print();
}
}
setCurrentTime(t);
computeAssignmentRules();
computeReactionPropensities();
//
for (int i = 0; i < yDot.length; i++)
{
VariableNode variableNode = variableList.get(i);
yDot[i] = variableNode.computeRateOfChange(0, t);
}
vectorWrapper.setRates(yDot);
}
}
@Override
public void setupForNewRun(int newRun) {
}
@Override
public void printStatisticsTSD() {
// TODO Auto-generated method stub
}
public class HierarchicalEventHandler implements EventHandler {
private double value = -1;
@Override
public void init(double t0, double[] y0, double t) {
}
@Override
public double g(double t, double[] y) {
double returnValue = -value;
currentTime.setValue(t);
vectorWrapper.setValues(y);
for (HierarchicalModel modelstate : modules) {
int index = modelstate.getIndex();
for (EventNode event : modelstate.getEvents()) {
if (!event.isEnabled(index)) {
if (event.isTriggeredAtTime(t, index)) {
returnValue = value;
}
}
}
}
return returnValue;
}
@Override
public Action eventOccurred(double t, double[] y, boolean increasing) {
value = -value;
currentTime.setValue(t);
vectorWrapper.setValues(y);
computeAssignmentRules();
computeEvents();
return EventHandler.Action.STOP;
}
@Override
public void resetState(double t, double[] y) {
}
}
public class HierarchicalTriggeredEventHandler implements EventHandler {
private double value = -1;
@Override
public void init(double t0, double[] y0, double t) {
}
@Override
public double g(double t, double[] y) {
currentTime.setValue(0, t);
if (!triggeredEventList.isEmpty()) {
if (triggeredEventList.peek().getFireTime() <= t) {
return value;
}
}
return -value;
}
@Override
public Action eventOccurred(double t, double[] y, boolean increasing) {
value = -value;
currentTime.setValue(t);
vectorWrapper.setValues(y);
computeAssignmentRules();
computeEvents();
return EventHandler.Action.STOP;
}
@Override
public void resetState(double t, double[] y) {
// TODO Auto-generated method stub
}
}
public class DifferentialEquations
implements FirstOrderDifferentialEquations {
@Override
public int getDimension() {
return vectorWrapper.getSize();
}
public void computeReactionPropensities() {
for (HierarchicalModel hierarchicalModel : modules) {
hierarchicalModel.computePropensities();
}
}
@Override
public void computeDerivatives(double t, double[] y, double[] yDot)
throws MaxCountExceededException, DimensionMismatchException {
setCurrentTime(t);
vectorWrapper.setValues(y);
computeAssignmentRules();
computeReactionPropensities();
int i = 0;
for (HierarchicalModel hierarchicalModel : modules) {
int index = hierarchicalModel.getIndex();
for (VariableNode node : hierarchicalModel.getListOfVariables()) {
yDot[i++] = node.computeRateOfChange(index, t);
}
}
vectorWrapper.setRates(yDot);
}
}
}

View file

@ -26,6 +26,7 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.HierarchicalEventComparator;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.setup.ModelSetup;
@ -41,298 +42,265 @@ import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
*/
public class HierarchicalSSADirectSimulator extends HierarchicalSimulation
{
private final boolean print;
private final boolean print;
private long randomSeed;
private long randomSeed;
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running,
String[] interestingSpecies, String quantityType, String abstraction, double initialTime, double outputStartTime) throws IOException, XMLStreamException, BioSimException
{
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running,
String[] interestingSpecies, String quantityType, String abstraction, double initialTime, double outputStartTime) throws IOException, XMLStreamException, BioSimException
{
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs, timeLimit, maxTimeStep, minTimeStep, progress, printInterval, stoichAmpValue, running, interestingSpecies, quantityType, abstraction, initialTime, outputStartTime, SimType.HSSA);
this.print = true;
this.randomSeed = randomSeed;
}
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs, timeLimit, maxTimeStep, minTimeStep, progress, printInterval, stoichAmpValue, running, interestingSpecies, quantityType, abstraction, initialTime, outputStartTime, SimType.HSSA);
this.print = true;
this.randomSeed = randomSeed;
}
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running,
String[] interestingSpecies, String quantityType, String abstraction, double initialTime, double outputStartTime, boolean print) throws IOException, XMLStreamException, BioSimException
{
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, double maxTimeStep, double minTimeStep, long randomSeed, JProgressBar progress, double printInterval, double stoichAmpValue, JFrame running,
String[] interestingSpecies, String quantityType, String abstraction, double initialTime, double outputStartTime, boolean print) throws IOException, XMLStreamException, BioSimException
{
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs, timeLimit, maxTimeStep, minTimeStep, progress, printInterval, stoichAmpValue, running, interestingSpecies, quantityType, abstraction, initialTime, outputStartTime, SimType.HSSA);
this.print = print;
this.randomSeed = randomSeed;
super(SBMLFileName, rootDirectory, outputDirectory, randomSeed, runs, timeLimit, maxTimeStep, minTimeStep, progress, printInterval, stoichAmpValue, running, interestingSpecies, quantityType, abstraction, initialTime, outputStartTime, SimType.HSSA);
this.print = print;
this.randomSeed = randomSeed;
}
}
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, long randomSeed, double printInterval, double initialTime, double outputStartTime, boolean print) throws IOException, XMLStreamException, BioSimException
{
public HierarchicalSSADirectSimulator(String SBMLFileName, String rootDirectory, String outputDirectory, int runs, double timeLimit, long randomSeed, double printInterval, double initialTime, double outputStartTime, boolean print) throws IOException, XMLStreamException, BioSimException
{
this(SBMLFileName, rootDirectory, outputDirectory, runs, timeLimit, Double.POSITIVE_INFINITY, 0, randomSeed, null, printInterval, 1, null, null, null, null, 0, 0, print);
this(SBMLFileName, rootDirectory, outputDirectory, runs, timeLimit, Double.POSITIVE_INFINITY, 0, randomSeed, null, printInterval, 1, null, null, null, null, 0, 0, print);
}
}
@Override
public void initialize(long randomSeed, int runNumber) throws IOException, XMLStreamException
{
if (!isInitialized)
{
setCurrentTime(getInitialTime());
ModelSetup.setupModels(this, ModelType.HSSA);
eventList = getEventList();
variableList = getVariableList();
//constraintList = getConstraintList();
computeFixedPoint();
if (!eventList.isEmpty())
{
triggeredEventList = new PriorityQueue<EventNode>(1, new HierarchicalEventComparator());
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, currentTime.getValue(0));
}
//TODO: get initial values
setInitialPropensity();
@Override
public void initialize(long randomSeed, int runNumber) throws IOException, XMLStreamException
{
if (!isInitialized)
{
setCurrentTime(getInitialTime());
ModelSetup.setupModels(this, ModelType.HSSA);
computeFixedPoint();
setupForOutput(runNumber);
HierarchicalWriter.setupVariableFromTSD(getBufferedTSDWriter(), getTopmodel(), getSubmodels(), getInterestingSpecies());
isInitialized = true;
}
for(HierarchicalModel model : this.getListOfHierarchicalModels())
{
totalPropensity.addChild(model.getPropensity().getVariable());
}
totalPropensity.computeFunction(0);
if (hasEvents)
{
triggeredEventList = new PriorityQueue<EventState>(1, new HierarchicalEventComparator());
computeEvents();
}
}
setupForOutput(runNumber);
isInitialized = true;
}
/**
* cancels the current run
*/
@Override
public void cancel()
{
setCancelFlag(true);
}
}
/**
* clears data structures for new run
*/
@Override
public void clear()
{
/**
* cancels the current run
*/
@Override
public void cancel()
{
setCancelFlag(true);
}
}
/**
* clears data structures for new run
*/
@Override
public void clear()
{
/**
* does minimized initialization process to prepare for a new run
*/
@Override
public void setupForNewRun(int newRun)
{
setCurrentTime(getInitialTime());
setConstraintFlag(true);
setupForOutput(newRun);
//TODO: restore init state
restoreInitialPropensity();
}
try
{
HierarchicalWriter.setupVariableFromTSD(getBufferedTSDWriter(), getTopmodel(), getSubmodels(), getInterestingSpecies());
}
catch (IOException e)
{
e.printStackTrace();
}
@Override
public void setupForNewRun(int newRun)
{
setCurrentTime(getInitialTime());
setupForOutput(newRun);
}
}
@Override
public void simulate()
{
@Override
public void simulate()
{
double r1 = 0, r2 = 0, totalPropensity = 0, delta_t = 0, nextReactionTime = 0, previousTime = 0, nextEventTime = 0, nextMaxTime = 0;
double r1 = 0, r2 = 0, totalPropensity = 0, delta_t = 0, nextReactionTime = 0, previousTime = 0, nextEventTime = 0, nextMaxTime = 0;
if (isSbmlHasErrorsFlag())
{
return;
}
if (isSbmlHasErrorsFlag())
{
return;
}
if (!isInitialized)
{
try
{
this.initialize(randomSeed, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
}
printTime.setValue(getOutputStartTime());
previousTime = 0;
nextEventTime = getNextEventTime();
if (!isInitialized)
{
try
{
this.initialize(randomSeed, 1);
}
catch (IOException e)
{
e.printStackTrace();
}
catch (XMLStreamException e)
{
e.printStackTrace();
}
}
printTime = getOutputStartTime();
previousTime = 0;
nextEventTime = getNextEventTime();
while (currentTime.getValue(0) < getTimeLimit() && !isCancelFlag())
{
// if (!HierarchicalUtilities.evaluateConstraints(constraintList))
// {
// return;
// }
if (print)
{
printToFile();
}
r1 = getRandomNumberGenerator().nextDouble();
r2 = getRandomNumberGenerator().nextDouble();
totalPropensity = getTotalPropensity();
delta_t = computeNextTimeStep(r1, totalPropensity);
nextReactionTime = currentTime.getValue(0) + delta_t;
nextEventTime = getNextEventTime();
nextMaxTime = currentTime.getValue(0) + getMaxTimeStep();
previousTime = currentTime.getValue(0);
while (currentTime.getValue(0) < getTimeLimit() && !isCancelFlag())
{
// if (!HierarchicalUtilities.evaluateConstraints(constraintList))
// {
// return;
// }
if (nextReactionTime < nextEventTime && nextReactionTime < nextMaxTime)
{
setCurrentTime(nextReactionTime);
}
else if (nextEventTime <= nextMaxTime)
{
setCurrentTime(nextEventTime);
}
else
{
setCurrentTime(nextMaxTime);
}
r1 = getRandomNumberGenerator().nextDouble();
r2 = getRandomNumberGenerator().nextDouble();
totalPropensity = getTotalPropensity();
delta_t = computeNextTimeStep(r1, totalPropensity);
nextReactionTime = currentTime.getValue(0) + delta_t;
nextEventTime = getNextEventTime();
nextMaxTime = currentTime.getValue(0) + getMaxTimeStep();
previousTime = currentTime.getValue(0);
if (currentTime.getValue() > getTimeLimit())
{
break;
}
if (nextReactionTime < nextEventTime && nextReactionTime < nextMaxTime)
{
setCurrentTime(nextReactionTime);
}
else if (nextEventTime <= nextMaxTime)
{
setCurrentTime(nextEventTime);
}
else
{
setCurrentTime(nextMaxTime);
}
if (print)
{
printToFile();
}
if (currentTime.getValue(0) > getTimeLimit())
{
break;
}
if (currentTime.getValue(0) == nextReactionTime)
{
update(true, false, false, r2, previousTime);
}
else if (currentTime.getValue(0) == nextEventTime)
{
update(false, false, true, r2, previousTime);
}
else
{
update(false, true, false, r2, previousTime);
}
}
if (currentTime.getValue(0) == nextReactionTime)
{
update(true, false, false, r2, previousTime);
}
else if (currentTime.getValue(0) == nextEventTime)
{
update(false, false, true, r2, previousTime);
}
else
{
update(false, true, false, r2, previousTime);
}
if (!isCancelFlag())
{
setCurrentTime(getTimeLimit());
update(false, true, true, r2, previousTime);
if (print)
{
printToFile();
}
}
if (print)
{
printToFile();
}
if (!isCancelFlag())
{
setCurrentTime(getTimeLimit());
update(false, true, true, r2, previousTime);
print();
}
}
if (print)
{
printToFile();
}
private void update(boolean reaction, boolean rateRule, boolean events, double r2, double previousTime)
{
if (reaction)
{
selectAndPerformReaction(r2);
}
try
{
getBufferedTSDWriter().write(')');
getBufferedTSDWriter().flush();
}
catch (IOException e1)
{
e1.printStackTrace();
}
}
}
if (rateRule)
{
fireRateRules(previousTime);
}
private void update(boolean reaction, boolean rateRule, boolean events, double r2, double previousTime)
{
if (reaction)
{
selectAndPerformReaction(r2);
}
if (events)
{
computeEvents();
}
computeAssignmentRules();
for(HierarchicalModel modelstate : this.getListOfHierarchicalModels())
{
for(ReactionNode node : modelstate.getReactions())
{
node.computePropensity(modelstate.getIndex());
}
modelstate.getPropensity().computeFunction(modelstate.getIndex());
}
this.totalPropensity.computeFunction(0);
}
if (rateRule)
{
fireRateRules(previousTime);
}
public double computeNextTimeStep(double r1, double totalPropensity)
{
return Math.log(1 / r1) / totalPropensity;
}
if (events)
{
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, currentTime.getValue(0));
}
computeAssignmentRules();
private void fireRateRules(double previousTime)
{
}
}
public double computeNextTimeStep(double r1, double totalPropensity)
{
return Math.log(1 / r1) / totalPropensity;
}
private void selectAndPerformReaction(double r2)
{
double sum = 0;
double threshold = getTotalPropensity() * r2;
for(HierarchicalModel model : this.getListOfHierarchicalModels())
{
for(ReactionNode node : model.getReactions())
{
sum += node.getValue(model.getIndex());
private void fireRateRules(double previousTime)
{
if(sum >= threshold)
{
node.fireReaction(model.getIndex(), sum - threshold);
return;
}
}
}
}
}
private void selectAndPerformReaction(double r2)
{
double threshold = getTotalPropensity() * r2;
double totalRunningPropensity = getTopmodel().getPropensity(0);
if (totalRunningPropensity >= threshold)
{
performReaction(getTopmodel(), threshold);
}
else
{
for (HierarchicalModel submodel : getSubmodels().values())
{
totalRunningPropensity += submodel.getPropensity(0);
if (totalRunningPropensity >= threshold)
{
performReaction(submodel, threshold - (totalRunningPropensity - submodel.getPropensity(submodel.getIndex())));
}
}
}
}
@Override
public void printStatisticsTSD()
{
private void performReaction(HierarchicalModel modelstate, double threshold)
{
double runningSum = 0;
for (ReactionNode reactionNode : modelstate.getReactions())
{
runningSum += reactionNode.getValue(modelstate.getIndex());
}
if (runningSum >= threshold)
{
reactionNode.fireReaction(modelstate.getIndex(), runningSum - threshold);
return;
}
}
}
public double getNextEventTime()
{
for(HierarchicalModel model : modules)
{
@Override
public void printStatisticsTSD()
{
}
public double getNextEventTime()
{
for (int i = eventList.size() - 1; i >= 0; i--)
{
EventNode event = eventList.get(i);
event.isTriggeredAtTime(currentTime.getValue(0), event.getSubmodelIndex(i));
}
HierarchicalUtilities.triggerAndFireEvents(eventList, triggeredEventList, currentTime.getValue(0));
if (triggeredEventList != null && !triggeredEventList.isEmpty())
{
return triggeredEventList.peek().getFireTime();
}
return Double.POSITIVE_INFINITY;
}
for (EventNode event : model.getEvents())
{
event.isTriggeredAtTime(currentTime.getValue(), model.getIndex());
}
}
computeEvents();
if (triggeredEventList != null && !triggeredEventList.isEmpty())
{
return triggeredEventList.peek().getFireTime();
}
return Double.POSITIVE_INFINITY;
}
}

View file

@ -23,12 +23,14 @@ import java.util.Set;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.AbstractHierarchicalNode.Type;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ConstraintNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
/**
@ -42,37 +44,36 @@ import edu.utah.ece.async.dataModels.util.GlobalConstants;
public final class HierarchicalModel
{
public static enum ModelType
{
HSSA, HODE, HFBA, NONE;
}
private boolean isInitSet;
public static enum ModelType
{
HSSA, HODE, HFBA, NONE;
}
private ModelType type;
private Set<String> deletedBySId;
private Set<String> deletedByMetaId;
private List<EventNode> events;
private List<VariableNode> variables;
private List<ReactionNode> reactions;
private List<VariableNode> arrays;
private List<ConstraintNode> constraints;
private List<FunctionNode> initAssignments;
private List<FunctionNode> assignRules;
private List<FunctionNode> assignRules;
private List<VariableNode> variables;
private Map<String, VariableNode> idToNode;
private String ID;
protected int index;
private double maxPropensity;
private double minPropensity;
private HierarchicalNode propensity;
private double initPropensity;
// TODO: keep track of child model states because needed when cloning
private String ID;
protected int index;
private double maxPropensity;
private double minPropensity;
private FunctionNode propensity;
private Map<String, HierarchicalModel> idToSubmodel;
public HierarchicalModel(String submodelID)
{
this(submodelID, 0);
@ -80,37 +81,42 @@ public final class HierarchicalModel
public HierarchicalModel(String submodelID, int index)
{
this.ID = submodelID;
this.index = index;
minPropensity = Double.MAX_VALUE / 10.0;
maxPropensity = Double.MIN_VALUE / 10.0;
this.minPropensity = Double.MAX_VALUE / 10.0;
this.maxPropensity = Double.MIN_VALUE / 10.0;
this.idToNode = new HashMap<String, VariableNode>();
this.variables = new ArrayList<VariableNode>();
this.events = new LinkedList<EventNode>();
this.constraints = new ArrayList<ConstraintNode>();
this.reactions = new ArrayList<ReactionNode>();
this.arrays = new ArrayList<VariableNode>();
this.propensity = new FunctionNode(new VariableNode("propensity", StateType.SCALAR), new HierarchicalNode(Type.PLUS));
}
public HierarchicalModel(HierarchicalModel state)
{
this.type = state.type;
this.isInitSet = state.isInitSet;
// TODO: fix this
this.deletedBySId = state.deletedBySId;
this.deletedByMetaId = state.deletedByMetaId;
this.events = state.events;
this.variables = state.variables;
this.reactions = state.reactions;
this.arrays = state.arrays;
this.constraints = state.constraints;
this.idToNode = state.idToNode;
this.ID = state.ID;
this.minPropensity = state.minPropensity;
this.maxPropensity = state.maxPropensity;
this.index = state.index;
if (state.propensity != null)
{
this.propensity = state.propensity;
this.initPropensity = state.initPropensity;
}
this.minPropensity = state.minPropensity;
this.maxPropensity = state.maxPropensity;
this.index = state.index;
if (state.propensity != null)
{
this.propensity = state.propensity;
}
}
public void clear()
@ -123,19 +129,19 @@ public final class HierarchicalModel
{
return new HierarchicalModel(this);
}
public boolean isInitSet()
public VariableNode addVariable(VariableNode node)
{
return isInitSet;
variables.add(node);
idToNode.put(node.getName(), node);
return node;
}
public Map<String, VariableNode> createVariableToNodeMap()
public List<VariableNode> getListOfVariables()
{
Map<String, VariableNode> variableToNodes = new HashMap<String, VariableNode>();
this.idToNode = variableToNodes;
return variableToNodes;
return variables;
}
public Map<String, VariableNode> getVariableToNodeMap()
{
return idToNode;
@ -148,88 +154,34 @@ public final class HierarchicalModel
return node;
}
public ReactionNode addReaction(ReactionNode node)
public void addReaction(ReactionNode node)
{
if (reactions == null)
{
reactions = new ArrayList<ReactionNode>();
}
if (idToNode == null)
{
idToNode = new HashMap<String, VariableNode>();
}
reactions.add(node);
idToNode.put(node.getName(), node);
return node;
}
public EventNode addEvent(HierarchicalNode triggerNode)
{
EventNode node = new EventNode(triggerNode);
return addEvent(node);
addEvent(node);
return node;
}
public EventNode addEvent(EventNode node)
public void addEvent(EventNode node)
{
if (events == null)
{
events = new LinkedList<EventNode>();
}
events.add(node);
return node;
}
public VariableNode addArray(VariableNode node)
{
if (arrays == null)
{
arrays = new ArrayList<VariableNode>();
}
if (idToNode == null)
{
idToNode = new HashMap<String, VariableNode>();
}
arrays.add(node);
idToNode.put(node.getName(), node);
return node;
}
public VariableNode addVariable(String variable, double value)
{
VariableNode node = new VariableNode(variable);
return addVariable(node);
}
public VariableNode addVariable(VariableNode node)
{
if (variables == null)
{
variables = new ArrayList<VariableNode>();
}
if (idToNode == null)
{
idToNode = new HashMap<String, VariableNode>();
}
variables.add(node);
idToNode.put(node.getName(), node);
return node;
}
public ConstraintNode addConstraint(String variable, HierarchicalNode node)
{
if (constraints == null)
{
constraints = new ArrayList<ConstraintNode>();
}
ConstraintNode constraintNode = new ConstraintNode(variable, node);
constraints.add(constraintNode);
@ -252,16 +204,6 @@ public final class HierarchicalModel
return idToNode.get(variable);
}
public List<VariableNode> getVariables()
{
return variables;
}
public VariableNode getVariable(int index)
{
return variables.get(index);
}
public List<ConstraintNode> getConstraints()
{
return constraints;
@ -316,31 +258,6 @@ public final class HierarchicalModel
return deletedByMetaId.contains(metaid);
}
public int getNumOfVariables()
{
return variables == null ? 0 : variables.size();
}
public int getNumOfReactions()
{
return reactions == null ? 0 : reactions.size();
}
public int getNumOfEvents()
{
return events == null ? 0 : events.size();
}
public int getNumOfConstraints()
{
return constraints == null ? 0 : constraints.size();
}
public int getNumOfArrays()
{
return arrays == null ? 0 : arrays.size();
}
public List<VariableNode> getArrays()
{
return arrays;
@ -406,107 +323,135 @@ public final class HierarchicalModel
type = ModelType.HSSA;
}
}
public String getID()
{
return ID;
}
{
return ID;
}
public double getMaxPropensity()
{
return maxPropensity;
}
public double getMaxPropensity()
{
return maxPropensity;
}
public double getMinPropensity()
{
return minPropensity;
}
public double getMinPropensity()
{
return minPropensity;
}
public double getPropensity(int index)
{
return propensity.getValue(index);
}
public FunctionNode getPropensity()
{
return propensity;
}
public void setID(String iD)
{
ID = iD;
}
public void setID(String iD)
{
ID = iD;
}
public void setMaxPropensity(double maxPropensity)
{
this.maxPropensity = maxPropensity;
}
public void setMaxPropensity(double maxPropensity)
{
this.maxPropensity = maxPropensity;
}
public void setMinPropensity(double minPropensity)
{
this.minPropensity = minPropensity;
}
public void setMinPropensity(double minPropensity)
{
this.minPropensity = minPropensity;
}
public HierarchicalNode createPropensity()
{
this.propensity = new HierarchicalNode(0);
return propensity;
}
public int getIndex()
{
return index;
}
public void setInitPropensity(int index)
{
if (propensity != null)
public void addInitAssignment(FunctionNode node)
{
if(initAssignments == null)
{
initAssignments = new ArrayList<FunctionNode>();
}
initAssignments.add(node);
}
public void addAssignRule(FunctionNode node)
{
if(assignRules == null)
{
assignRules = new ArrayList<FunctionNode>();
}
assignRules.add(node);
}
public List<FunctionNode> getInitAssignments()
{
return initAssignments;
}
public void setInitAssignments(List<FunctionNode> initAssignments)
{
this.initAssignments = initAssignments;
}
public List<FunctionNode> getAssignRules()
{
return assignRules;
}
public void setAssignRules(List<FunctionNode> assignRules)
{
this.assignRules = assignRules;
}
public void addSubmodel(HierarchicalModel submodel)
{
if(idToSubmodel == null)
{
idToSubmodel = new HashMap<String, HierarchicalModel>();
}
idToSubmodel.put(submodel.getID(), submodel);
}
public HierarchicalModel getSubmodel(String id)
{
HierarchicalModel submodel = null;
if(idToSubmodel != null)
{
submodel = idToSubmodel.get(id);
}
return submodel;
}
public boolean containsSubmodel(String id)
{
if(idToSubmodel != null)
{
return idToSubmodel.containsKey(id);
}
return false;
}
public void computePropensities()
{
for(ReactionNode node : reactions)
{
this.initPropensity = propensity.getValue(index);
node.computePropensity(index);
}
}
public void restoreInitPropensity(int index)
{
this.propensity.setValue(index, initPropensity);
}
public int getIndex()
{
return index;
}
public void addInitAssignment(FunctionNode node)
{
if(initAssignments == null)
{
initAssignments = new ArrayList<FunctionNode>();
}
initAssignments.add(node);
}
public void addAssignRule(FunctionNode node)
{
if(assignRules == null)
{
assignRules = new ArrayList<FunctionNode>();
}
assignRules.add(node);
}
public List<FunctionNode> getInitAssignments()
{
return initAssignments;
}
public void setInitAssignments(List<FunctionNode> initAssignments)
{
this.initAssignments = initAssignments;
}
public List<FunctionNode> getAssignRules()
{
return assignRules;
}
public void setAssignRules(List<FunctionNode> assignRules)
{
this.assignRules = assignRules;
}
}
public void removeSubmodel(String id)
{
idToSubmodel.remove(id);
}
public void insertPropensity(ReactionNode reaction)
{
this.propensity.addChild(reaction);
}
}

View file

@ -101,5 +101,14 @@ public class DenseState extends TreeState
return builder.toString();
}
@Override
protected boolean containsChild(int index) {
if(listOfStates.size() <= index)
{
return false;
}
return true;
}
}

View file

@ -0,0 +1,98 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.states;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
public class EventState {
private double fireTime;
private double maxDisabledTime;
private double minEnabledTime;
private double priority;
private boolean isEnabled;
private int index;
private EventNode parent;
private double[] assignmentValues;
public EventState(int index, EventNode parent)
{
this.maxDisabledTime = Double.NEGATIVE_INFINITY;
this.minEnabledTime = Double.POSITIVE_INFINITY;
this.fireTime = Double.POSITIVE_INFINITY;
this.isEnabled = false;
this.parent = parent;
this.index = index;
}
public int getIndex()
{
return index;
}
public double getFireTime() {
return fireTime;
}
public void setFireTime(double fireTime) {
this.fireTime = fireTime;
}
public double getMaxDisabledTime() {
return maxDisabledTime;
}
public void setMaxDisabledTime(double maxDisabledTime) {
this.maxDisabledTime = maxDisabledTime;
}
public double getMinEnabledTime() {
return minEnabledTime;
}
public void setMinEnabledTime(double minEnabledTime) {
this.minEnabledTime = minEnabledTime;
}
public double getPriority() {
return priority;
}
public void setPriority(double priority) {
this.priority = priority;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public EventNode getParent() {
return parent;
}
public void setParent(EventNode parent) {
this.parent = parent;
}
public double[] getAssignmentValues() {
return assignmentValues;
}
public void setAssignmentValues(double[] assignmentValues) {
this.assignmentValues = assignmentValues;
}
}

View file

@ -26,7 +26,6 @@ public abstract class HierarchicalState
{
protected double value;
protected int arrayIndex;
public enum StateType
{

View file

@ -0,0 +1,94 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.states;
public class ReactionState {
private boolean hasEnoughMoleculesFd;
private boolean hasEnoughMoleculesRv;
private double forwardRateValue;
private double reverseRateValue;
private double initPropensity;
private double initForwardPropensity;
public ReactionState()
{
hasEnoughMoleculesFd = false;
hasEnoughMoleculesRv = false;
forwardRateValue = 0;
reverseRateValue = 0;
initPropensity = 0;
initForwardPropensity = 0;
}
public boolean hasEnoughMoleculesFd() {
return hasEnoughMoleculesFd;
}
public void setHasEnoughMoleculesFd(boolean hasEnoughMoleculesFd) {
this.hasEnoughMoleculesFd = hasEnoughMoleculesFd;
}
public boolean hasEnoughMoleculesRv() {
return hasEnoughMoleculesRv;
}
public void setHasEnoughMoleculesRv(boolean hasEnoughMoleculesRv) {
this.hasEnoughMoleculesRv = hasEnoughMoleculesRv;
}
public double getForwardRateValue() {
return forwardRateValue;
}
public void setForwardRateValue(double forwardRateValue) {
this.forwardRateValue = forwardRateValue;
}
public double getReverseRateValue() {
return reverseRateValue;
}
public void setReverseRateValue(double reverseRateValue) {
this.reverseRateValue = reverseRateValue;
}
public double getInitPropensity() {
return initPropensity;
}
public void setInitPropensity(double initPropensity) {
this.initPropensity = initPropensity;
}
public double getInitForwardPropensity() {
return initForwardPropensity;
}
public void setInitForwardPropensity(double initForwardPropensity) {
this.initForwardPropensity = initForwardPropensity;
}
@Override
public String toString() {
return "fw_rate =" + forwardRateValue;
}
}

View file

@ -78,4 +78,9 @@ public class SparseState extends TreeState
return builder.toString();
}
@Override
protected boolean containsChild(int index) {
return mapOfStates.containsKey(index);
}
}

View file

@ -26,11 +26,19 @@ public abstract class TreeState extends HierarchicalState{
@Override
public double getStateValue(int index) {
if(!containsChild(index))
{
return 0;
}
return getState(index).getStateValue();
}
@Override
public void setStateValue(int index, double value) {
if(!containsChild(index))
{
addState(index);
}
getState(index).setStateValue(value);
}
@ -43,5 +51,7 @@ public abstract class TreeState extends HierarchicalState{
public double getRateValue(int index) {
return 0;
}
protected abstract boolean containsChild(int index);
}

View file

@ -57,7 +57,7 @@ public class ValueState extends HierarchicalState
public HierarchicalState getState(int index)
{
// can't have children
return null;
return this;
}
@Override

View file

@ -67,7 +67,7 @@ public class VectorState extends HierarchicalState{
@Override
public HierarchicalState getState(int index) {
return null;
return this;
}
@Override

View file

@ -27,7 +27,6 @@ import java.util.List;
public class VectorWrapper {
private double[] values;
private double[] rates;
private int[] submodels;
private boolean isSet;
private int size;
private List<Double> initValues;
@ -36,7 +35,6 @@ public class VectorWrapper {
{
this.size = 0;
this.values = null;
this.submodels = null;
this.values = null;
this.initValues = null;
this.isSet = false;

View file

@ -25,6 +25,7 @@ import java.util.Set;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.ASTNode.Type;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ConstraintNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
@ -34,8 +35,6 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.RateSplitterInterpreter;
import org.sbml.jsbml.Model;
/**
*
*
@ -189,64 +188,7 @@ public class HierarchicalUtilities
}
}
public static void alterLocalParameter(ASTNode math, String id, String parameterID)
{
if (math.isName() && math.getName().equals(id))
{
// math.setVariable(null);
math.setName(parameterID);
}
else
{
for (ASTNode child : math.getChildren())
{
alterLocalParameter(child, id, parameterID);
}
}
}
public static void triggerAndFireEvents(List<EventNode> eventList, PriorityQueue<EventNode> triggeredEventList, double time)
{
boolean changed = true;
while (changed)
{
changed = false;
for (int i = eventList.size() - 1; i >= 0; i--)
{
EventNode event = eventList.get(i);
if (event.computeEnabled(0, time))
{
eventList.remove(i);
triggeredEventList.add(event);
}
}
while (triggeredEventList != null && !triggeredEventList.isEmpty())
{
EventNode event = triggeredEventList.peek();
if (event.getFireTime() <= time)
{
triggeredEventList.poll();
event.fireEvent(0, time);
eventList.add(event);
changed = true;
}
else
{
break;
}
}
}
}
public static ASTNode[] splitMath(ASTNode math)
{
ASTNode plus = new ASTNode(Type.PLUS);
@ -268,14 +210,4 @@ public class HierarchicalUtilities
return plus.getChildCount() > 0 && minus.getChildCount() > 0 ? result : null;
}
public static boolean evaluateConstraints(List<ConstraintNode> listOfConstraints)
{
boolean hasSuccess = true;
for (int i = listOfConstraints.size() - 1; i >= 0; i--)
{
ConstraintNode constraintNode = listOfConstraints.get(i);
hasSuccess = hasSuccess && constraintNode.evaluateConstraint(constraintNode.getSubmodelIndex(i));
}
return hasSuccess;
}
}

View file

@ -15,7 +15,7 @@ package edu.utah.ece.async.analysis.simulation.hierarchical.util.comp;
import java.util.Comparator;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
/**
*
@ -25,10 +25,10 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class HierarchicalEventComparator implements Comparator<EventNode>
public class HierarchicalEventComparator implements Comparator<EventState>
{
@Override
public int compare(EventNode event1, EventNode event2)
public int compare(EventState event1, EventState event2)
{
if (event1.getFireTime() > event2.getFireTime())
{

View file

@ -0,0 +1,111 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.util.comp;
import java.util.HashMap;
import java.util.Map;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.ext.comp.CompConstants;
import org.sbml.jsbml.ext.comp.CompModelPlugin;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
public class ModelContainer
{
private Model model;
private HierarchicalModel hierarchicalModel;
private CompModelPlugin compModel;
private ModelContainer parent;
private Map<String, ModelContainer> children;
private String prefix;
public ModelContainer(Model model, HierarchicalModel hierarchicalModel, ModelContainer parent)
{
this.model = model;
this.hierarchicalModel = hierarchicalModel;
this.compModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
this.parent = parent;
setPrefix();
addChild();
setModelType(hierarchicalModel, model);
}
public Model getModel() {
return model;
}
public HierarchicalModel getHierarchicalModel() {
return hierarchicalModel;
}
public CompModelPlugin getCompModel() {
return compModel;
}
public ModelContainer getParent() {
return parent;
}
public ModelContainer getChild(String id)
{
if(children != null)
{
return children.get(id);
}
return null;
}
private void addChild()
{
if(parent != null)
{
if(parent.children == null)
{
parent.children = new HashMap<String, ModelContainer>();
}
parent.children.put(hierarchicalModel.getID(), this);
parent.hierarchicalModel.addSubmodel(hierarchicalModel);
}
}
private void setModelType(HierarchicalModel modelstate, Model model)
{
int sboTerm = model.isSetSBOTerm() ? model.getSBOTerm() : -1;
if (sboTerm == GlobalConstants.SBO_FLUX_BALANCE)
{
modelstate.setModelType(ModelType.HFBA);
}
else if (sboTerm == GlobalConstants.SBO_NONSPATIAL_DISCRETE)
{
modelstate.setModelType(ModelType.HSSA);
}
else if (sboTerm == GlobalConstants.SBO_NONSPATIAL_CONTINUOUS)
{
modelstate.setModelType(ModelType.HODE);
}
else
{
modelstate.setModelType(ModelType.NONE);
}
}
private void setPrefix()
{
if(parent != null)
{
this.prefix = hierarchicalModel.getID() + "__" + parent.prefix;
}
else
{
this.prefix = "";
}
}
public String getPrefix()
{
return prefix;
}
}

View file

@ -1,72 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.comp;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ReplacementHandler
{
private HierarchicalModel fromModelState;
private String fromVariable;
private HierarchicalModel toModelState;
private String toVariable;
public ReplacementHandler(HierarchicalModel fromModelState, String fromVariable, HierarchicalModel toModelState, String toVariable)
{
this.fromModelState = fromModelState;
this.fromVariable = fromVariable;
this.toModelState = toModelState;
this.toVariable = toVariable;
}
public void copyNodeTo()
{
toModelState.addMappingNode(toVariable, fromModelState.getNode(fromVariable));
}
public HierarchicalModel getFromModelState()
{
return fromModelState;
}
public String getFromVariable()
{
return fromVariable;
}
public HierarchicalModel getToModelState()
{
return toModelState;
}
public String getToVariable()
{
return toVariable;
}
@Override
public String toString()
{
return "copy " + fromVariable + " of " + fromModelState.getID() + " to " + toVariable + " of " + toModelState.getID();
}
}

View file

@ -483,43 +483,4 @@ public final class MathInterpreter
return node;
}
private static boolean replaceNodes(HierarchicalNode parent, HierarchicalNode node, Map<String, VariableNode> variableToNodes, boolean useValue, int index)
{
boolean result = false;
for (HierarchicalNode child : node.getChildren())
{
if (child.isName())
{
VariableNode varNode = (VariableNode) child;
if (variableToNodes.containsKey(varNode.getName()))
{
if (useValue)
{
parent.addChild(new HierarchicalNode(varNode.getValue(index)));
}
else
{
parent.addChild(variableToNodes.get(varNode.getName()));
}
result = true;
continue;
}
}
if (child.getNumOfChild() == 0)
{
parent.addChild(child.clone());
}
else
{
HierarchicalNode newNode = new HierarchicalNode(child.getType());
result = result | replaceNodes(newNode, child, variableToNodes, useValue, index);
parent.addChild(newNode);
}
}
return result;
}
}

View file

@ -182,10 +182,9 @@ public class ArraysSetup
public static void linkDimensionSize(HierarchicalModel modelstate)
{
for (int i = modelstate.getNumOfArrays() - 1; i >= 0; i--)
for (VariableNode var : modelstate.getArrays())
{
ArrayNode node = modelstate.getArrays().get(i).getArrayNode();
ArrayNode node = var.getArrayNode();
for (int j = node.getNumDimensions(); j >= 0; j--)
{
node.setDimensionSize(j, modelstate.getNode(node.getDimensionSizeId(j)));
@ -248,9 +247,8 @@ public class ArraysSetup
public static void expandArrays(HierarchicalModel modelstate)
{
for (int i = modelstate.getNumOfArrays() - 1; i >= 0; i--)
for (VariableNode node : modelstate.getArrays())
{
HierarchicalNode node = modelstate.getArrays().get(i);
expandArray(modelstate, node);
}

View file

@ -1,77 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class CompartmentSetup
{
public static void setupCompartments(HierarchicalModel modelstate, StateType type, Model model, VectorWrapper wrapper)
{
for (Compartment compartment : model.getListOfCompartments())
{
if (modelstate.isDeletedBySId(compartment.getId()))
{
continue;
}
setupSingleCompartment(modelstate, compartment, type, wrapper);
}
}
private static void setupSingleCompartment(HierarchicalModel modelstate, Compartment compartment, StateType type, VectorWrapper wrapper)
{
String compartmentID = compartment.getId();
VariableNode node = new VariableNode(compartmentID);
if (compartment.getConstant())
{
node.createState(StateType.SCALAR, wrapper);
modelstate.addMappingNode(compartmentID, node);
}
else
{
node.createState(type, wrapper);
modelstate.addVariable(node);
}
if (Double.isNaN(compartment.getSize()))
{
node.setValue(modelstate.getIndex(), 1);
}
else
{
node.setValue(modelstate.getIndex(), compartment.getSize());
}
}
}

View file

@ -1,73 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.Constraint;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ConstraintSetup
{
/**
* puts constraint-related information into data structures
*/
public static void setupConstraints(HierarchicalModel modelstate, Model model)
{
int count = 0;
for (Constraint constraint : model.getListOfConstraints())
{
String id = null;
if (constraint.isSetMetaId())
{
id = constraint.getMetaId();
}
else
{
id = "constraint " + count++;
}
if (modelstate.isDeletedByMetaId(constraint.getMetaId()))
{
continue;
}
setupSingleConstraint(modelstate, id, constraint.getMath(), model);
}
}
public static void setupSingleConstraint(HierarchicalModel modelstate, String id, ASTNode math, Model model)
{
math = HierarchicalUtilities.inlineFormula(modelstate, math, model);
HierarchicalNode constraintNode = MathInterpreter.parseASTNode(math, modelstate.getVariableToNodeMap());
modelstate.addConstraint(id, constraintNode);
}
}

View file

@ -14,13 +14,44 @@
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import java.io.IOException;
import java.util.Map;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.AssignmentRule;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.Constraint;
import org.sbml.jsbml.Delay;
import org.sbml.jsbml.Event;
import org.sbml.jsbml.EventAssignment;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.Priority;
import org.sbml.jsbml.RateRule;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.Rule;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import org.sbml.jsbml.Trigger;
import edu.utah.ece.async.analysis.simulation.hierarchical.HierarchicalSimulation;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.AbstractHierarchicalNode.Type;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesReferenceNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.ModelContainer;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.EventState;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
/**
@ -34,30 +65,575 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalSt
public class CoreSetup
{
public static void initializeVariables(HierarchicalModel modelstate, Model model, StateType type, VariableNode time, VectorWrapper wrapper) throws IOException
static void initializeModel(HierarchicalSimulation sim, ModelContainer container, StateType type, VariableNode time, VectorWrapper wrapper, boolean split) throws IOException
{
modelstate.createVariableToNodeMap();
modelstate.addMappingNode(time.getName(), time);
ParameterSetup.setupParameters(modelstate, type, model, wrapper);
CompartmentSetup.setupCompartments(modelstate, type, model, wrapper);
SpeciesSetup.setupSpecies(modelstate, type, model, wrapper);
ReactionSetup.setupReactions(modelstate, model, type, wrapper);
container.getHierarchicalModel().addMappingNode("_time", time);
setupParameters(sim, container, type, wrapper);
setupCompartments(sim, container, type, wrapper);
setupSpecies(sim, container, type, wrapper);
setupReactions(sim, container, type, wrapper);
setupEvents(sim, container);
setupConstraints(sim, container);
setupRules(sim, container);
setupInitialAssignments(sim, container);
//ArraysSetup.linkDimensionSize(modelstate);
//ArraysSetup.expandArrays(modelstate);
}
//TODO: might be able to merge these
public static void initializeModel(HierarchicalModel modelstate, Model model, VariableNode time)
private static void setupCompartments(HierarchicalSimulation sim, ModelContainer container, StateType type, VectorWrapper wrapper)
{
initializeModel(modelstate, model, time, false);
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
VariableNode node;
for (Compartment compartment : model.getListOfCompartments())
{
String compartmentID = compartment.getId();
node = modelstate.getNode(compartmentID);
if(node == null)
{
node = new VariableNode(compartmentID);
}
ReplacementSetup.setupReplacement(compartment, node, container);
if (modelstate.isDeletedBySId(compartmentID))
{
continue;
}
if (compartment.getConstant())
{
node.createState(StateType.SCALAR, wrapper);
modelstate.addMappingNode(compartmentID, node);
}
else
{
node.createState(type, wrapper);
modelstate.addVariable(node);
node.getState().addState(modelstate.getIndex(), 0);
sim.addPrintVariable(container.getPrefix() + compartmentID, node.getState().getState(modelstate.getIndex()));
}
if (Double.isNaN(compartment.getSize()))
{
node.setValue(modelstate.getIndex(), 1);
}
else
{
node.setValue(modelstate.getIndex(), compartment.getSize());
}
}
}
public static void initializeModel(HierarchicalModel modelstate, Model model, VariableNode time, boolean split)
/**
* puts constraint-related information into data structures
*/
private static void setupConstraints(HierarchicalSimulation sim, ModelContainer container)
{
ArraysSetup.linkDimensionSize(modelstate);
ArraysSetup.expandArrays(modelstate);
EventSetup.setupEvents(modelstate, model);
ConstraintSetup.setupConstraints(modelstate, model);
RuleSetup.setupRules(modelstate, model);
InitAssignmentSetup.setupInitialAssignments(modelstate, model);
int count = 0;
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
for (Constraint constraint : model.getListOfConstraints())
{
String id = null;
ReplacementSetup.setupReplacement(constraint, container);
if (constraint.isSetMetaId())
{
if (modelstate.isDeletedByMetaId(constraint.getMetaId()))
{
continue;
}
id = constraint.getMetaId();
}
else
{
id = "constraint " + count++;
}
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, constraint.getMath(), model);
HierarchicalNode constraintNode = MathInterpreter.parseASTNode(math, modelstate.getVariableToNodeMap());
modelstate.addConstraint(id, constraintNode);
}
}
private static void setupEventAssignments(HierarchicalSimulation sim, ModelContainer container, EventNode eventNode, Event event)
{
HierarchicalModel modelstate = container.getHierarchicalModel();
for (EventAssignment eventAssignment : event.getListOfEventAssignments())
{
ReplacementSetup.setupReplacement(eventAssignment, container);
if (eventAssignment.isSetMetaId() && modelstate.isDeletedByMetaId(eventAssignment.getMetaId()) || !eventAssignment.isSetMath())
{
continue;
}
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, eventAssignment.getMath(), container.getModel());
HierarchicalNode assignmentNode = MathInterpreter.parseASTNode(math, modelstate.getVariableToNodeMap());
VariableNode variable = modelstate.getNode(eventAssignment.getVariable());
FunctionNode eventAssignmentNode = new FunctionNode(variable, assignmentNode);
eventNode.addEventAssignment(eventAssignmentNode);
}
}
/**
* puts event-related information into data structures
*/
private static void setupEvents(HierarchicalSimulation sim, ModelContainer container)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
Map<String, VariableNode> variableToNodeMap = modelstate.getVariableToNodeMap();
int index = modelstate.getIndex();
for (Event event : model.getListOfEvents())
{
ReplacementSetup.setupReplacement(event, null, container);
if (modelstate.isDeletedBySId(event.getId()))
{
continue;
}
sim.setHasEvents(true);
if(event.isSetTrigger() && event.getTrigger().isSetMath())
{
Trigger trigger = event.getTrigger();
ASTNode triggerMath = HierarchicalUtilities.inlineFormula(modelstate, trigger.getMath(), model);
HierarchicalNode triggerNode = MathInterpreter.parseASTNode(triggerMath, variableToNodeMap);
EventNode node = modelstate.addEvent(triggerNode);
EventState state = node.addEventState(index);
boolean useValuesFromTrigger = event.getUseValuesFromTriggerTime();
boolean isPersistent = trigger.isSetPersistent() ? trigger.getPersistent() : false;
boolean initValue = trigger.isSetInitialValue() ? trigger.getInitialValue() : false;
node.setUseTriggerValue(useValuesFromTrigger);
node.setPersistent(isPersistent);
if (!initValue)
{
state.setMaxDisabledTime(0);
if (node.computeTrigger(modelstate.getIndex()))
{
state.setMinEnabledTime(0);
}
}
if (event.isSetPriority())
{
Priority priority = event.getPriority();
if (!(priority.isSetMetaId() && modelstate.isDeletedByMetaId(priority.getMetaId())) && priority.isSetMath())
{
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, priority.getMath(), model);
HierarchicalNode priorityNode = MathInterpreter.parseASTNode(math, variableToNodeMap);
node.setPriorityValue(priorityNode);
}
}
if (event.isSetDelay())
{
Delay delay = event.getDelay();
if (!(delay.isSetMetaId() && modelstate.isDeletedByMetaId(delay.getMetaId())) && delay.isSetMath())
{
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, delay.getMath(), model);
HierarchicalNode delayNode = MathInterpreter.parseASTNode(math, variableToNodeMap);
node.setDelayValue(delayNode);
}
}
setupEventAssignments(sim, container, node, event);
}
}
}
private static void setupInitialAssignments(HierarchicalSimulation sim, ModelContainer container)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
for (InitialAssignment initAssignment : model.getListOfInitialAssignments())
{
ReplacementSetup.setupReplacement(initAssignment, container);
if (initAssignment.isSetMetaId() && modelstate.isDeletedByMetaId(initAssignment.getMetaId()))
{
continue;
}
String variable = initAssignment.getVariable();
VariableNode variableNode = modelstate.getNode(variable);
if(initAssignment.isSetMath())
{
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, initAssignment.getMath(), model);
HierarchicalNode initAssignNode = MathInterpreter.parseASTNode(math, modelstate.getVariableToNodeMap());
if (variableNode.isSpecies())
{
SpeciesNode node = (SpeciesNode) variableNode;
if (!node.hasOnlySubstance())
{
HierarchicalNode amountNode = new HierarchicalNode(Type.TIMES);
amountNode.addChild(initAssignNode);
amountNode.addChild(node.getCompartment());
initAssignNode = amountNode;
}
}
FunctionNode node = new FunctionNode(variableNode, initAssignNode);
node.setIsInitAssignment(true);
modelstate.addInitAssignment(node);
}
}
}
/**
* puts parameter-related information into data structures
*/
private static void setupParameters(HierarchicalSimulation sim, ModelContainer container, StateType type, VectorWrapper wrapper)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
VariableNode node;
for (Parameter parameter : model.getListOfParameters())
{
node = modelstate.getNode(parameter.getId());
if(node == null)
{
node = new VariableNode(parameter.getId());
}
ReplacementSetup.setupReplacement(parameter, node, container);
if (modelstate.isDeletedBySId(parameter.getId()))
{
continue;
}
else if (ArraysSetup.checkArray(parameter))
{
continue;
}
if (parameter.isConstant())
{
node.createState(StateType.SCALAR, wrapper);
modelstate.addMappingNode(parameter.getId(), node);
}
else
{
node.createState(type, wrapper);
modelstate.addVariable(node);
node.getState().addState(modelstate.getIndex(), 0);
sim.addPrintVariable(container.getPrefix() + parameter.getId(), node.getState().getState(modelstate.getIndex()));
}
node.setValue(modelstate.getIndex(), parameter.getValue());
}
}
private static void setupProduct(HierarchicalSimulation sim, ModelContainer container, ReactionNode reaction, String productID, SpeciesReference product, StateType type, VectorWrapper wrapper)
{
HierarchicalModel modelstate = container.getHierarchicalModel();
ReplacementSetup.setupReplacement(product, container);
if (product.isSetId() && modelstate.isDeletedBySId(product.getId()))
{
return;
}
if (product.isSetMetaId() && modelstate.isDeletedByMetaId(product.getMetaId()))
{
return;
}
double stoichiometryValue = Double.isNaN(product.getStoichiometry()) ? 1 : product.getStoichiometry();
SpeciesReferenceNode speciesReferenceNode = new SpeciesReferenceNode();
if(!product.isConstant())
{
speciesReferenceNode.createState(type, wrapper);
}
else
{
speciesReferenceNode.createState(StateType.SCALAR, wrapper);
}
speciesReferenceNode.setValue(modelstate.getIndex(), stoichiometryValue);
SpeciesNode species = (SpeciesNode) modelstate.getNode(productID);
speciesReferenceNode.setSpecies(species);
reaction.addProduct(speciesReferenceNode);
if (product.isSetId() && product.getId().length() > 0)
{
speciesReferenceNode.setName(product.getId());
if (!product.getConstant())
{
speciesReferenceNode.setIsVariableConstant(false);
modelstate.addVariable(speciesReferenceNode );
}
else
{
modelstate.addMappingNode(product.getId(), speciesReferenceNode);
}
}
species.addODERate(reaction, speciesReferenceNode);
}
private static void setupReactant(HierarchicalSimulation sim, ModelContainer container, ReactionNode reaction, String reactantID, SpeciesReference reactant, StateType type, VectorWrapper wrapper)
{
HierarchicalModel modelstate = container.getHierarchicalModel();
ReplacementSetup.setupReplacement(reactant, container);
if (reactant.isSetId() && modelstate.isDeletedBySId(reactant.getId()))
{
return;
}
if (reactant.isSetMetaId() && modelstate.isDeletedByMetaId(reactant.getMetaId()))
{
return;
}
double stoichiometryValue = Double.isNaN(reactant.getStoichiometry()) ? 1 : reactant.getStoichiometry();
SpeciesReferenceNode speciesReferenceNode = new SpeciesReferenceNode();
if(!reactant.isConstant())
{
speciesReferenceNode.createState(type, wrapper);
}
else
{
speciesReferenceNode.createState(StateType.SCALAR, wrapper);
}
speciesReferenceNode.setValue(modelstate.getIndex(), stoichiometryValue);
SpeciesNode species = (SpeciesNode) modelstate.getNode(reactantID);
speciesReferenceNode.setSpecies(species);
reaction.addReactant(speciesReferenceNode);
if (reactant.isSetId() && reactant.getId().length() > 0)
{
speciesReferenceNode.setName(reactant.getId());
if (!reactant.getConstant())
{
speciesReferenceNode.setIsVariableConstant(false);
modelstate.addVariable(speciesReferenceNode );
}
else
{
modelstate.addMappingNode(reactant.getId(), speciesReferenceNode);
}
}
species.subtractODERate(reaction, speciesReferenceNode);
}
private static void setupReactions(HierarchicalSimulation sim, ModelContainer container, StateType type, VectorWrapper wrapper)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
boolean split = modelstate.getModelType() == ModelType.HSSA;
for (Reaction reaction : model.getListOfReactions())
{
ReactionNode reactionNode = (ReactionNode) modelstate.getNode(reaction.getId());
if(reactionNode == null)
{
reactionNode = modelstate.addReaction(reaction.getId());
reactionNode.addReactionState(modelstate.getIndex());
reactionNode.createState(type, wrapper);
modelstate.insertPropensity(reactionNode);
}
ReplacementSetup.setupReplacement(reaction, reactionNode, container);
if (modelstate.isDeletedBySId(reaction.getId()))
{
continue;
}
else if (ArraysSetup.checkArray(reaction))
{
continue;
}
reactionNode.setValue(modelstate.getIndex(), 0);
for (SpeciesReference reactant : reaction.getListOfReactants())
{
setupReactant(sim, container, reactionNode, reactant.getSpecies(), reactant, type, wrapper);
}
for (SpeciesReference product : reaction.getListOfProducts())
{
setupProduct(sim, container, reactionNode, product.getSpecies(), product, type, wrapper);
}
KineticLaw kineticLaw = reaction.getKineticLaw();
if (kineticLaw != null)
{
for (LocalParameter localParameter : kineticLaw.getListOfLocalParameters())
{
String id = localParameter.getId();
if (localParameter.isSetMetaId() && modelstate.isDeletedByMetaId(localParameter.getMetaId()))
{
continue;
}
VariableNode node = new VariableNode(id, StateType.SCALAR);
node.setValue(localParameter.getValue());
reactionNode.addLocalParameter(id, node);
}
if (kineticLaw.isSetMath())
{
ASTNode reactionFormula = kineticLaw.getMath();
reactionFormula = HierarchicalUtilities.inlineFormula(modelstate, reactionFormula, model);
if (reaction.isReversible() && split)
{
setupSingleRevReaction(sim, modelstate, reactionNode, reactionFormula);
}
else
{
setupSingleNonRevReaction(sim, modelstate, reactionNode, reactionFormula, model);
}
}
}
}
}
private static void setupRules(HierarchicalSimulation sim, ModelContainer container)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
Map<String, VariableNode> variableToNodes = modelstate.getVariableToNodeMap();
for (Rule rule : model.getListOfRules())
{
ReplacementSetup.setupReplacement(rule, container);
if (rule.isSetMetaId() && modelstate.isDeletedByMetaId(rule.getMetaId()) || !rule.isSetMath())
{
continue;
}
if (rule.isAssignment())
{
AssignmentRule assignRule = (AssignmentRule) rule;
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, assignRule.getMath(), model);
VariableNode variableNode = variableToNodes.get(assignRule.getVariable());
HierarchicalNode assignRuleNode = MathInterpreter.parseASTNode(math, variableToNodes, variableNode);
FunctionNode node = new FunctionNode(variableNode, assignRuleNode);
modelstate.addAssignRule(node);
variableNode.setHasRule(true);
}
else if (rule.isRate())
{
RateRule rateRule = (RateRule) rule;
//TODO: fix
if(rateRule.isSetMath())
{
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, rateRule.getMath(), model);
VariableNode variableNode = variableToNodes.get(rateRule.getVariable());
HierarchicalNode rateNode = MathInterpreter.parseASTNode(math, variableToNodes);
variableNode.setRateRule(rateNode);
}
}
}
}
private static void setupSingleNonRevReaction(HierarchicalSimulation sim, HierarchicalModel modelstate, ReactionNode reactionNode, ASTNode reactionFormula, Model model)
{
HierarchicalNode math = MathInterpreter.parseASTNode(reactionFormula, modelstate.getVariableToNodeMap(), reactionNode.getLocalParameters(), reactionNode);
reactionNode.setForwardRate(math);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
private static void setupSingleRevReaction(HierarchicalSimulation sim, HierarchicalModel modelstate, ReactionNode reactionNode, ASTNode reactionFormula)
{
ASTNode[] splitMath = HierarchicalUtilities.splitMath(reactionFormula);
if (splitMath == null)
{
HierarchicalNode math = MathInterpreter.parseASTNode(reactionFormula, modelstate.getVariableToNodeMap(), reactionNode.getLocalParameters(), reactionNode);
reactionNode.setForwardRate(math);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
else
{
HierarchicalNode forwardRate = MathInterpreter.parseASTNode(splitMath[0], modelstate.getVariableToNodeMap(), reactionNode);
HierarchicalNode reverseRate = MathInterpreter.parseASTNode(splitMath[1], modelstate.getVariableToNodeMap(), reactionNode);
reactionNode.setForwardRate(forwardRate);
reactionNode.setReverseRate(reverseRate);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
}
/**
* puts species-related information into data structures
*
*/
private static void setupSpecies(HierarchicalSimulation sim, ModelContainer container, StateType type, VectorWrapper wrapper)
{
Model model = container.getModel();
HierarchicalModel modelstate = container.getHierarchicalModel();
int index = modelstate.getIndex();
SpeciesNode node;
for (Species species : model.getListOfSpecies())
{
node = (SpeciesNode) modelstate.getNode(species.getId());
if(node == null)
{
node = new SpeciesNode(species.getId());
node.createSpeciesTemplate();
if(species.getConstant())
{
node.createState(StateType.SCALAR, wrapper);
modelstate.addMappingNode(node.getName(), node);
}
else
{
node.createState(type, wrapper);
modelstate.addVariable(node);
node.getState().addState(modelstate.getIndex(), 0);
sim.addPrintVariable(container.getPrefix() + species.getId(), node.getState().getState(modelstate.getIndex()));
}
}
ReplacementSetup.setupReplacement(species, node, container);
if (modelstate.isDeletedBySId(species.getId()))
{
continue;
}
if (ArraysSetup.checkArray(species))
{
continue;
}
node.setBoundaryCondition(species.getBoundaryCondition());
node.setHasOnlySubstance(species.getHasOnlySubstanceUnits());
VariableNode compartment = modelstate.getNode(species.getCompartment());
node.setCompartment(compartment);
if (species.isSetInitialAmount())
{
node.setValue(modelstate.getIndex(), species.getInitialAmount());
}
else if (species.isSetInitialConcentration())
{
HierarchicalNode initConcentration = new HierarchicalNode(Type.TIMES);
initConcentration.addChild(new HierarchicalNode(species.getInitialConcentration()));
initConcentration.addChild(compartment);
FunctionNode functionNode = new FunctionNode(node, initConcentration);
modelstate.addInitAssignment(functionNode);
functionNode.setIsInitAssignment(true);
}
//TODO: check initial assignment on replaced species
ReplacementSetup.setupReplacement(species, node, container);
}
}
}

View file

@ -1,149 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import java.util.Map;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.Delay;
import org.sbml.jsbml.Event;
import org.sbml.jsbml.EventAssignment;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Priority;
import org.sbml.jsbml.Trigger;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.EventNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class EventSetup
{
/**
* puts event-related information into data structures
*/
public static void setupEvents(HierarchicalModel modelstate, Model model)
{
Map<String, VariableNode> variableToNodeMap = modelstate.getVariableToNodeMap();
for (Event event : model.getListOfEvents())
{
if (modelstate.isDeletedBySId(event.getId()))
{
continue;
}
if(event.isSetTrigger() && event.getTrigger().isSetMath())
{
Trigger trigger = event.getTrigger();
ASTNode triggerMath = HierarchicalUtilities.inlineFormula(modelstate, trigger.getMath(), model);
HierarchicalNode triggerNode = MathInterpreter.parseASTNode(triggerMath, variableToNodeMap);
EventNode node = modelstate.addEvent(triggerNode);
boolean useValuesFromTrigger = event.getUseValuesFromTriggerTime();
boolean isPersistent = trigger.isSetPersistent() ? trigger.getPersistent() : false;
boolean initValue = trigger.isSetInitialValue() ? trigger.getInitialValue() : false;
setupSingleEvent(modelstate, node, event.getTrigger().getMath(), useValuesFromTrigger, initValue, isPersistent, model, variableToNodeMap);
if (event.isSetPriority())
{
Priority priority = event.getPriority();
if (!(priority.isSetMetaId() && modelstate.isDeletedByMetaId(priority.getMetaId())) && priority.isSetMath())
{
setupSinglePriority(modelstate, node, event.getPriority().getMath(), model, variableToNodeMap);
}
}
if (event.isSetDelay())
{
Delay delay = event.getDelay();
if (!(delay.isSetMetaId() && modelstate.isDeletedByMetaId(delay.getMetaId())) && delay.isSetMath())
{
setupSingleDelay(modelstate, node, event.getDelay().getMath(), model, variableToNodeMap);
}
}
setupEventAssignments(modelstate, node, event, model, variableToNodeMap);
}
}
}
public static void setupEventAssignments(HierarchicalModel modelstate, EventNode eventNode, Event event, Model model, Map<String, VariableNode> variableToNodeMap)
{
for (EventAssignment eventAssignment : event.getListOfEventAssignments())
{
if (eventAssignment.isSetMetaId() && modelstate.isDeletedByMetaId(eventAssignment.getMetaId()) || !eventAssignment.isSetMath())
{
continue;
}
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, eventAssignment.getMath(), model);
HierarchicalNode assignmentNode = MathInterpreter.parseASTNode(math, variableToNodeMap);
VariableNode variable = variableToNodeMap.get(eventAssignment.getVariable());
FunctionNode eventAssignmentNode = new FunctionNode(variable, assignmentNode);
eventNode.addEventAssignment(eventAssignmentNode);
}
}
public static void setupSinglePriority(HierarchicalModel modelstate, EventNode node, ASTNode math, Model model, Map<String, VariableNode> variableToNodeMap)
{
math = HierarchicalUtilities.inlineFormula(modelstate, math, model);
HierarchicalNode priorityNode = MathInterpreter.parseASTNode(math, variableToNodeMap);
node.setPriorityValue(priorityNode);
}
public static void setupSingleDelay(HierarchicalModel modelstate, EventNode node, ASTNode math, Model model, Map<String, VariableNode> variableToNodeMap)
{
math = HierarchicalUtilities.inlineFormula(modelstate, math, model);
HierarchicalNode delayNode = MathInterpreter.parseASTNode(math, variableToNodeMap);
node.setDelayValue(delayNode);
}
/**
* sets up a single event
*
* @param event
*/
public static void setupSingleEvent(HierarchicalModel modelstate, EventNode node, ASTNode trigger, boolean useFromTrigger, boolean initValue, boolean persistent, Model model, Map<String, VariableNode> variableToNodeMap)
{
node.setUseTriggerValue(useFromTrigger);
node.setPersistent(persistent);
if (!initValue)
{
node.setMaxDisabledTime(0);
if (node.computeTrigger(modelstate.getIndex()))
{
node.setMinEnabledTime(0);
}
}
}
}

View file

@ -1,77 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.Model;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.AbstractHierarchicalNode.Type;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class InitAssignmentSetup
{
public static void setupInitialAssignments(HierarchicalModel modelstate, Model model)
{
for (InitialAssignment initAssignment : model.getListOfInitialAssignments())
{
if (initAssignment.isSetMetaId() && modelstate.isDeletedByMetaId(initAssignment.getMetaId()))
{
continue;
}
String variable = initAssignment.getVariable();
VariableNode variableNode = modelstate.getNode(variable);
if(initAssignment.isSetMath())
{
ASTNode math = HierarchicalUtilities.inlineFormula(modelstate, initAssignment.getMath(), model);
HierarchicalNode initAssignNode = MathInterpreter.parseASTNode(math, modelstate.getVariableToNodeMap());
if (variableNode.isSpecies())
{
SpeciesNode node = (SpeciesNode) variableNode;
if (!node.hasOnlySubstance(modelstate.getIndex()))
{
HierarchicalNode amountNode = new HierarchicalNode(Type.TIMES);
amountNode.addChild(initAssignNode);
amountNode.addChild(node.getCompartment());
initAssignNode = amountNode;
}
}
FunctionNode node = new FunctionNode(variableNode, initAssignNode);
node.setIsInitAssignment(true);
modelstate.addInitAssignment(node);
}
}
}
}

View file

@ -18,6 +18,7 @@ import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@ -37,11 +38,10 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.methods.HierarchicalMixedSimulator;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.ReplacementHandler;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.ModelContainer;
/**
*
@ -76,227 +76,123 @@ public class ModelSetup
SBMLDocument document = sim.getDocument();
Model model = document.getModel();
String rootPath = sim.getRootDirectory();
List<HierarchicalModel> listOfModules = new ArrayList<HierarchicalModel>();
List<Model> listOfModels = new ArrayList<Model>();
List<String> listOfPrefix = new ArrayList<String>();
List<ReplacementHandler> listOfHandlers = new ArrayList<ReplacementHandler>();
HierarchicalModel hierarchicalModel = new HierarchicalModel("topmodel");
sim.setTopmodel(hierarchicalModel);
Map<String, Integer> mapOfModels = new HashMap<String, Integer>();
sim.setListOfModules(listOfModules);
CompSBMLDocumentPlugin sbmlComp = (CompSBMLDocumentPlugin) document.getPlugin(CompConstants.namespaceURI);
CompModelPlugin sbmlCompModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
HierarchicalModel topmodel = new HierarchicalModel("topmodel");
sim.setTopmodel(topmodel);
mapOfModels.put("topmodel", 0);
setModelType(topmodel, model);
listOfPrefix.add("");
listOfModules.add(topmodel);
listOfModels.add(model);
if (sbmlCompModel != null)
LinkedList<ModelContainer> unproc = new LinkedList<ModelContainer>();
List<ModelContainer> listOfContainers = new ArrayList<ModelContainer>();
//TODO: Map<String, ModelContainer> templateFromSource;
unproc.push(new ModelContainer(model, hierarchicalModel, null));
while(!unproc.isEmpty())
{
setupSubmodels(sim, rootPath, "", sbmlComp, sbmlCompModel, listOfModules, listOfModels, listOfPrefix, mapOfModels);
ReplacementSetup.setupReplacements(listOfHandlers, listOfModules, listOfModels, listOfPrefix, mapOfModels);
}
initializeModelStates(sim, listOfHandlers, listOfModules, listOfModels, sim.getCurrentTime(), type, wrapper);
if (sim instanceof HierarchicalMixedSimulator)
{
initializeHybridSimulation((HierarchicalMixedSimulator) sim, listOfModels, listOfModules);
}
}
private static void setupSubmodels(HierarchicalSimulation sim, String path, String prefix, CompSBMLDocumentPlugin sbmlComp, CompModelPlugin sbmlCompModel, List<HierarchicalModel> listOfModules, List<Model> listOfModels, List<String> listOfPrefix, Map<String, Integer> mapOfModels)
throws XMLStreamException, IOException
{
for (Submodel submodel : sbmlCompModel.getListOfSubmodels())
{
String newPrefix = prefix + submodel.getId() + "__";
Model model = null;
CompModelPlugin compModel = null;
CompSBMLDocumentPlugin compDoc = sbmlComp;
if (sbmlComp.getListOfExternalModelDefinitions() != null && sbmlComp.getListOfExternalModelDefinitions().get(submodel.getModelRef()) != null)
ModelContainer container = unproc.pop();
listOfContainers.add(container);
sim.addModelState(container.getHierarchicalModel());
if (container.getCompModel() != null)
{
ExternalModelDefinition ext = sbmlComp.getListOfExternalModelDefinitions().get(submodel.getModelRef());
String source = ext.getSource();
String extDef = path + HierarchicalUtilities.separator + source;
SBMLDocument extDoc = SBMLReader.read(new File(extDef));
model = extDoc.getModel();
compDoc = (CompSBMLDocumentPlugin) extDoc.getPlugin(CompConstants.namespaceURI);
compModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
while (ext.isSetModelRef())
for (Submodel submodel : container.getCompModel().getListOfSubmodels())
{
if (compDoc.getExternalModelDefinition(ext.getModelRef()) != null)
model = null;
CompSBMLDocumentPlugin compDoc = sbmlComp;
if (sbmlComp.getListOfExternalModelDefinitions() != null && sbmlComp.getListOfExternalModelDefinitions().get(submodel.getModelRef()) != null)
{
ext = compDoc.getListOfExternalModelDefinitions().get(ext.getModelRef());
source = ext.getSource().replace("file:", "");
extDef = path + HierarchicalUtilities.separator + source;
extDoc = SBMLReader.read(new File(extDef));
ExternalModelDefinition ext = sbmlComp.getListOfExternalModelDefinitions().get(submodel.getModelRef());
String source = ext.getSource();
String extDef = rootPath + HierarchicalUtilities.separator + source;
SBMLDocument extDoc = SBMLReader.read(new File(extDef));
model = extDoc.getModel();
compDoc = (CompSBMLDocumentPlugin) extDoc.getPlugin(CompConstants.namespaceURI);
compModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
while (ext.isSetModelRef())
{
if (compDoc.getExternalModelDefinition(ext.getModelRef()) != null)
{
ext = compDoc.getListOfExternalModelDefinitions().get(ext.getModelRef());
source = ext.getSource().replace("file:", "");
extDef = rootPath + HierarchicalUtilities.separator + source;
extDoc = SBMLReader.read(new File(extDef));
model = extDoc.getModel();
compDoc = (CompSBMLDocumentPlugin) extDoc.getPlugin(CompConstants.namespaceURI);
}
else if (compDoc.getModelDefinition(ext.getModelRef()) != null)
{
model = compDoc.getModelDefinition(ext.getModelRef());
break;
}
else
{
break;
}
}
}
else if (compDoc.getModelDefinition(ext.getModelRef()) != null)
else if (sbmlComp.getListOfModelDefinitions() != null && sbmlComp.getListOfModelDefinitions().get(submodel.getModelRef()) != null)
{
model = compDoc.getModelDefinition(ext.getModelRef());
compModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
break;
model = sbmlComp.getModelDefinition(submodel.getModelRef());
}
else
if (model != null)
{
break;
hierarchicalModel = new HierarchicalModel(submodel.getId());
unproc.push(new ModelContainer(model, hierarchicalModel, container));
}
}
}
else if (sbmlComp.getListOfModelDefinitions() != null && sbmlComp.getListOfModelDefinitions().get(submodel.getModelRef()) != null)
{
model = sbmlComp.getModelDefinition(submodel.getModelRef());
compModel = (CompModelPlugin) model.getPlugin(CompConstants.namespaceURI);
}
if (model != null)
{
String id = prefix + submodel.getId();
HierarchicalModel modelstate = new HierarchicalModel(id);
sim.addSubmodel(id, modelstate);
mapOfModels.put(id, mapOfModels.size());
listOfPrefix.add(newPrefix);
listOfModules.add(modelstate);
listOfModels.add(model);
setModelType(modelstate, model);
setupSubmodels(sim, path, newPrefix, compDoc, compModel, listOfModules, listOfModels, listOfPrefix, mapOfModels);
}
}
initializeModelStates(sim, listOfContainers, sim.getCurrentTime(), type, wrapper);
if (sim instanceof HierarchicalMixedSimulator)
{
initializeHybridSimulation((HierarchicalMixedSimulator) sim, listOfContainers);
}
}
private static void initializeModelStates(HierarchicalSimulation sim, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, VariableNode time, ModelType modelType, VectorWrapper wrapper) throws IOException
private static void initializeModelStates(HierarchicalSimulation sim, List<ModelContainer> listOfContainers, VariableNode time, ModelType modelType, VectorWrapper wrapper) throws IOException
{
StateType type = StateType.SPARSE;
boolean isSSA = modelType == ModelType.HSSA;
if(modelType == ModelType.HODE)
{
type = StateType.VECTOR;
}
for (int i = 0; i < listOfModules.size(); i++)
for(ModelContainer container : listOfContainers)
{
CoreSetup.initializeVariables(listOfModules.get(i), listOfModels.get(i), type, time, wrapper);
ReplacementSetup.setupDeletion(container);
CoreSetup.initializeModel(sim, container, type, time, wrapper, isSSA);
}
for (int i = listOfHandlers.size() - 1; i >= 0; i--)
{
listOfHandlers.get(i).copyNodeTo();
}
boolean isSSA = modelType == ModelType.HSSA;
for (int i = 0; i < listOfModules.size(); i++)
if(wrapper != null)
{
CoreSetup.initializeModel(listOfModules.get(i), listOfModels.get(i), time, isSSA);
}
if (isSSA)
{
sim.linkPropensities();
wrapper.initStateValues();
}
}
private static void initializeHybridSimulation(HierarchicalMixedSimulator sim, List<Model> listOfModels, List<HierarchicalModel> listOfModules) throws IOException
private static void initializeHybridSimulation(HierarchicalMixedSimulator sim, List<ModelContainer> listOfContainers) throws IOException, XMLStreamException
{
List<HierarchicalModel> listOfODEStates = new ArrayList<HierarchicalModel>();
List<HierarchicalModel> listOfSSAStates = new ArrayList<HierarchicalModel>();
List<HierarchicalModel> listOfFBAStates = new ArrayList<HierarchicalModel>();
List<Model> listOfFBAModels = new ArrayList<Model>();
for (int i = 0; i < listOfModels.size(); i++)
List<HierarchicalModel> listOfODEModels = new ArrayList<HierarchicalModel>();
for (ModelContainer container : listOfContainers)
{
Model model = listOfModels.get(i);
HierarchicalModel state = listOfModules.get(i);
HierarchicalModel state = container.getHierarchicalModel();
if (state.getModelType() == ModelType.HFBA)
{
listOfFBAStates.add(state);
listOfFBAModels.add(model);
sim.createFBASim(state, container.getModel());
}
else if (state.getModelType() == ModelType.HSSA)
else if(state.getModelType() == ModelType.HODE)
{
listOfSSAStates.add(state);
}
else
{
listOfODEStates.add(state);
listOfODEModels.add(state);
}
}
addSimulationMethod(sim, listOfODEStates, false);
addSimulationMethod(sim, listOfSSAStates, true);
addFBA(sim, listOfFBAModels, listOfFBAStates);
}
private static void addSimulationMethod(HierarchicalMixedSimulator sim, List<HierarchicalModel> listOfODEStates, boolean isSSA)
{
if (listOfODEStates.size() > 0)
{
HierarchicalModel topmodel = listOfODEStates.get(0);
Map<String, HierarchicalModel> submodels = listOfODEStates.size() > 1 ? new HashMap<String, HierarchicalModel>() : null;
for (int i = 1; i < listOfODEStates.size(); i++)
{
HierarchicalModel submodel = listOfODEStates.get(i);
submodels.put(submodel.getID(), submodel);
}
if (isSSA)
{
sim.createODESim(topmodel, submodels);
}
else
{
sim.createODESim(topmodel, submodels);
}
}
}
// TODO: generalize this
private static void addFBA(HierarchicalMixedSimulator sim, List<Model> listOfFBAModels, List<HierarchicalModel> listOfFBAStates)
{
if (listOfFBAModels.size() > 0)
{
HierarchicalModel state = listOfFBAStates.get(0);
Model model = listOfFBAModels.get(0);
sim.createFBASim(state, model);
}
}
private static void setModelType(HierarchicalModel modelstate, Model model)
{
int sboTerm = model.isSetSBOTerm() ? model.getSBOTerm() : -1;
if (sboTerm == GlobalConstants.SBO_FLUX_BALANCE)
{
modelstate.setModelType(ModelType.HFBA);
}
else if (sboTerm == GlobalConstants.SBO_NONSPATIAL_DISCRETE)
{
modelstate.setModelType(ModelType.HSSA);
}
else if (sboTerm == GlobalConstants.SBO_NONSPATIAL_CONTINUOUS)
{
modelstate.setModelType(ModelType.HODE);
}
else
{
modelstate.setModelType(ModelType.NONE);
}
sim.createODESim(listOfContainers.get(0).getHierarchicalModel(), listOfODEModels);
}
}

View file

@ -1,122 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.LocalParameter;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.Reaction;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ParameterSetup
{
/**
* puts parameter-related information into data structures
*/
public static void setupParameters(HierarchicalModel modelstate, StateType type, Model model, VectorWrapper wrapper)
{
for (Parameter parameter : model.getListOfParameters())
{
if (modelstate.isDeletedBySId(parameter.getId()))
{
continue;
}
else if (ArraysSetup.checkArray(parameter))
{
continue;
}
setupSingleParameter(modelstate, parameter, type, wrapper);
}
}
/**
* sets up a single (non-local) parameter
*
* @param parameter
*/
private static void setupSingleParameter(HierarchicalModel modelstate, Parameter parameter, StateType type, VectorWrapper wrapper)
{
VariableNode node = new VariableNode(parameter.getId());
if (parameter.isConstant())
{
node.createState(StateType.SCALAR, wrapper);
modelstate.addMappingNode(parameter.getId(), node);
}
else
{
node.createState(type, wrapper);
modelstate.addVariable(node);
}
node.setValue(modelstate.getIndex(), parameter.getValue());
}
/**
* sets up the local parameters in a single kinetic law
*
* @param kineticLaw
* @param reactionID
*/
public static void setupLocalParameters(HierarchicalModel modelstate, KineticLaw kineticLaw, Reaction reaction)
{
String reactionID = reaction.getId();
if (kineticLaw != null)
{
for (LocalParameter localParameter : kineticLaw.getListOfLocalParameters())
{
String id = localParameter.getId();
if (modelstate.isDeletedBySId(id))
{
continue;
}
else if (localParameter.isSetMetaId() && modelstate.isDeletedByMetaId(localParameter.getMetaId()))
{
continue;
}
String parameterID = reactionID + "_" + id;
VariableNode node = new VariableNode(parameterID, StateType.SCALAR);
node.setValue(localParameter.getValue());
modelstate.addMappingNode(parameterID, node);
HierarchicalUtilities.alterLocalParameter(kineticLaw.getMath(), id, parameterID);
}
}
}
}

View file

@ -1,133 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.KineticLaw;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.SpeciesReference;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class ReactionSetup
{
public static void setupReactions(HierarchicalModel modelstate, Model model, StateType type, VectorWrapper wrapper)
{
Reaction reaction;
for (int i = 0; i < model.getNumReactions(); i++)
{
reaction = model.getReaction(i);
ParameterSetup.setupLocalParameters(modelstate, reaction.getKineticLaw(), reaction);
if (modelstate.isDeletedBySId(reaction.getId()))
{
continue;
}
else if (ArraysSetup.checkArray(reaction))
{
continue;
}
setupSingleReaction(modelstate, reaction, false, model, type, wrapper);
}
}
/**
* calculates the initial propensity of a single reaction also does some
* initialization stuff
*
* @param reactionID
* @param reactionFormula
* @param reversible
* @param reactantsList
* @param productsList
* @param modifiersList
*/
private static void setupSingleReaction(HierarchicalModel modelstate, Reaction reaction, boolean split, Model model, StateType type, VectorWrapper wrapper)
{
ReactionNode reactionNode = modelstate.addReaction(reaction.getId());
//TODO: change scalar to other types too
reactionNode.createState(StateType.SCALAR, wrapper);
reactionNode.setValue(modelstate.getIndex(), 0);
for (SpeciesReference reactant : reaction.getListOfReactants())
{
SpeciesReferenceSetup.setupSingleReactant(modelstate, reactionNode, reactant.getSpecies(), reactant, type, wrapper);
}
for (SpeciesReference product : reaction.getListOfProducts())
{
SpeciesReferenceSetup.setupSingleProduct(modelstate, reactionNode, product.getSpecies(), product, type, wrapper);
}
KineticLaw kineticLaw = reaction.getKineticLaw();
if (kineticLaw != null && kineticLaw.isSetMath())
{
ASTNode reactionFormula = kineticLaw.getMath();
reactionFormula = HierarchicalUtilities.inlineFormula(modelstate, reactionFormula, model);
if (reaction.isReversible() && split)
{
setupSingleRevReaction(modelstate, reactionNode, reactionFormula);
}
else
{
setupSingleNonRevReaction(modelstate, reactionNode, reactionFormula, model);
}
}
}
private static void setupSingleNonRevReaction(HierarchicalModel modelstate, ReactionNode reactionNode, ASTNode reactionFormula, Model model)
{
HierarchicalNode math = MathInterpreter.parseASTNode(reactionFormula, modelstate.getVariableToNodeMap(), reactionNode);
reactionNode.setForwardRate(math);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
private static void setupSingleRevReaction(HierarchicalModel modelstate, ReactionNode reactionNode, ASTNode reactionFormula)
{
ASTNode[] splitMath = HierarchicalUtilities.splitMath(reactionFormula);
if (splitMath == null)
{
HierarchicalNode math = MathInterpreter.parseASTNode(reactionFormula, modelstate.getVariableToNodeMap(), reactionNode);
reactionNode.setForwardRate(math);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
else
{
HierarchicalNode forwardRate = MathInterpreter.parseASTNode(splitMath[0], modelstate.getVariableToNodeMap(), reactionNode);
HierarchicalNode reverseRate = MathInterpreter.parseASTNode(splitMath[1], modelstate.getVariableToNodeMap(), reactionNode);
reactionNode.setForwardRate(forwardRate);
reactionNode.setReverseRate(reverseRate);
//reactionNode.computeNotEnoughEnoughMolecules(modelstate.getIndex());
}
}
}

View file

@ -13,22 +13,8 @@
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import java.util.List;
import java.util.Map;
import org.sbml.jsbml.AbstractNamedSBase;
import org.sbml.jsbml.Compartment;
import org.sbml.jsbml.Constraint;
import org.sbml.jsbml.Event;
import org.sbml.jsbml.InitialAssignment;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.ModifierSpeciesReference;
import org.sbml.jsbml.Parameter;
import org.sbml.jsbml.Reaction;
import org.sbml.jsbml.Rule;
import org.sbml.jsbml.SBase;
import org.sbml.jsbml.Species;
import org.sbml.jsbml.SpeciesReference;
import org.sbml.jsbml.ext.comp.CompConstants;
import org.sbml.jsbml.ext.comp.CompModelPlugin;
import org.sbml.jsbml.ext.comp.CompSBasePlugin;
@ -39,8 +25,9 @@ import org.sbml.jsbml.ext.comp.ReplacedElement;
import org.sbml.jsbml.ext.comp.SBaseRef;
import org.sbml.jsbml.ext.comp.Submodel;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.ReplacementHandler;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.ModelContainer;
/**
*
@ -53,194 +40,83 @@ import edu.utah.ece.async.analysis.simulation.hierarchical.util.comp.Replacement
public class ReplacementSetup
{
public static void setupReplacements(List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, List<String> listOfPrefix, Map<String, Integer> mapOfModels)
{
static void setupDeletion(ModelContainer container)
{
CompModelPlugin topCompModel = container.getCompModel();
HierarchicalModel top = container.getHierarchicalModel();
if (topCompModel.isSetListOfSubmodels())
{
for (Submodel submodel : topCompModel.getListOfSubmodels())
{
if (submodel.isSetListOfDeletions())
{
for (Deletion deletion : submodel.getListOfDeletions())
{
HierarchicalModel sub = top.getSubmodel(submodel.getId());
if (deletion.isSetIdRef())
{
if (sub.containsSubmodel(deletion.getIdRef()))
{
sub = top.getSubmodel(deletion.getIdRef());
}
if (deletion.isSetSBaseRef())
{
if (deletion.getSBaseRef().isSetIdRef())
{
String subId = deletion.getSBaseRef().getIdRef();
sub.addDeletedBySid(subId);
}
else if (deletion.getSBaseRef().isSetMetaIdRef())
{
String subId = deletion.getSBaseRef().getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
}
else
{
String subId = deletion.getIdRef();
sub.addDeletedBySid(subId);
}
}
else if (deletion.isSetMetaIdRef())
{
String subId = deletion.getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
else if (deletion.isSetPortRef())
{
CompModelPlugin subModel = container.getChild(submodel.getId()).getCompModel();
Port port = subModel.getListOfPorts().get(deletion.getPortRef());
if (port.isSetIdRef())
{
String subId = port.getIdRef();
sub.addDeletedBySid(subId);
}
else if (port.isSetMetaIdRef())
{
String subId = port.getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
else if (port.isSetSBaseRef())
{
SBaseRef ref = port.getSBaseRef();
if (ref.isSetIdRef())
{
sub.addDeletedBySid(ref.getIdRef());
}
else if (ref.isSetMetaIdRef())
{
sub.addDeletedByMetaId(ref.getMetaIdRef());
}
}
}
}
}
}
}
}
for (int i = 0; i < listOfModels.size(); i++)
{
Model model = listOfModels.get(i);
HierarchicalModel modelstate = listOfModules.get(i);
CompModelPlugin topCompModel = (CompModelPlugin) model.getExtension(CompConstants.shortLabel);
String prefix = listOfPrefix.get(i);
setupDeletion(topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
for (Parameter parameter : model.getListOfParameters())
{
setupReplacement(parameter, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (Compartment compartment : model.getListOfCompartments())
{
setupReplacement(compartment, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (Species species : model.getListOfSpecies())
{
setupReplacement(species, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (Reaction reaction : model.getListOfReactions())
{
setupReplacement(reaction, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
for (SpeciesReference reactant : reaction.getListOfReactants())
{
setupReplacement(reactant, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (SpeciesReference product : reaction.getListOfProducts())
{
setupReplacement(product, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (ModifierSpeciesReference modifier : reaction.getListOfModifiers())
{
setupReplacement(modifier, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
}
for (Event event : model.getListOfEvents())
{
setupReplacement(event, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
if (event.isSetDelay())
{
setupReplacement(event.getDelay(), modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
if (event.isSetPriority())
{
setupReplacement(event.getPriority(), modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
}
for (Constraint constraint : model.getListOfConstraints())
{
setupReplacement(constraint, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (Rule rule : model.getListOfRules())
{
setupReplacement(rule, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
for (InitialAssignment initAssignment : model.getListOfInitialAssignments())
{
setupReplacement(initAssignment, modelstate, topCompModel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
}
}
private static void setupDeletion(CompModelPlugin topCompModel, String prefix, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
if (topCompModel.isSetListOfSubmodels())
{
for (Submodel submodel : topCompModel.getListOfSubmodels())
{
setupDeletion(submodel, prefix, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
}
}
private static void setupDeletion(Submodel submodel, String prefix, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
if (submodel.isSetListOfDeletions())
{
String subModelId = prefix + submodel.getId();
for (Deletion deletion : submodel.getListOfDeletions())
{
int subIndex = mapOfModels.get(subModelId);
HierarchicalModel sub = listOfModules.get(subIndex);
Model model = listOfModels.get(subIndex);
if (deletion.isSetIdRef())
{
String tmp = subModelId + "__" + deletion.getIdRef();
if (mapOfModels.containsKey(tmp))
{
subIndex = mapOfModels.get(tmp);
sub = listOfModules.get(subIndex);
}
if (deletion.isSetSBaseRef())
{
if (deletion.getSBaseRef().isSetIdRef())
{
String subId = deletion.getSBaseRef().getIdRef();
sub.addDeletedBySid(subId);
}
else if (deletion.getSBaseRef().isSetMetaIdRef())
{
String subId = deletion.getSBaseRef().getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
}
else
{
String subId = deletion.getIdRef();
sub.addDeletedBySid(subId);
}
}
else if (deletion.isSetMetaIdRef())
{
String subId = deletion.getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
else if (deletion.isSetPortRef())
{
CompModelPlugin subModel = (CompModelPlugin) model.getExtension("comp");
Port port = subModel.getListOfPorts().get(deletion.getPortRef());
if (port.isSetIdRef())
{
String subId = port.getIdRef();
sub.addDeletedBySid(subId);
}
else if (port.isSetMetaIdRef())
{
String subId = port.getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
else if (port.isSetSBaseRef())
{
SBaseRef ref = port.getSBaseRef();
if (ref.isSetIdRef())
{
sub.addDeletedBySid(ref.getIdRef());
}
else if (ref.isSetMetaIdRef())
{
sub.addDeletedByMetaId(ref.getMetaIdRef());
}
}
}
}
}
}
private static void setupReplacement(AbstractNamedSBase sbase, HierarchicalModel top, CompModelPlugin topCompModel, String prefix, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
CompSBasePlugin sbasePlugin = (CompSBasePlugin) sbase.getExtension(CompConstants.shortLabel);
String id = sbase.getId();
if (sbasePlugin != null)
{
if (sbasePlugin.isSetReplacedBy())
{
ReplacementHandler handler = setupReplacedBy(sbasePlugin.getReplacedBy(), id, prefix, top, topCompModel, listOfHandlers, listOfModules, listOfModels, mapOfModels);
if (handler != null)
{
id = handler.getFromVariable();
top = handler.getFromModelState();
}
}
if (sbasePlugin.isSetListOfReplacedElements())
{
for (ReplacedElement element : sbasePlugin.getListOfReplacedElements())
{
setupReplacedElement(element, id, prefix, top, topCompModel, listOfHandlers, listOfModules, listOfModels, mapOfModels);
}
}
}
}
private static void setupReplacement(SBase sbase, HierarchicalModel top, CompModelPlugin topCompModel, String prefix, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
static void setupReplacement(SBase sbase, ModelContainer container)
{
CompSBasePlugin sbasePlugin = (CompSBasePlugin) sbase.getExtension(CompConstants.shortLabel);
@ -248,164 +124,170 @@ public class ReplacementSetup
{
if (sbasePlugin.isSetReplacedBy())
{
setupReplacedBy(sbasePlugin.getReplacedBy(), prefix, top, topCompModel, listOfHandlers, listOfModules, listOfModels, mapOfModels);
setupReplacedBy(sbasePlugin.getReplacedBy(), container);
}
if (sbasePlugin.isSetListOfReplacedElements())
{
for (ReplacedElement element : sbasePlugin.getListOfReplacedElements())
{
setupReplacedElement(element, prefix, top, topCompModel, listOfHandlers, listOfModules, listOfModels, mapOfModels);
setupReplacedElement(element, container);
}
}
}
}
static void setupReplacement(AbstractNamedSBase sbase, VariableNode node, ModelContainer container)
{
CompSBasePlugin sbasePlugin = (CompSBasePlugin) sbase.getExtension(CompConstants.shortLabel);
private static ReplacementHandler setupReplacedBy(ReplacedBy replacement, String id, String prefix, HierarchicalModel top, CompModelPlugin topCompModel, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
if (sbasePlugin != null)
{
if (sbasePlugin.isSetReplacedBy())
{
setupReplacedBy(sbasePlugin.getReplacedBy(), node,container);
}
if (sbasePlugin.isSetListOfReplacedElements())
{
for (ReplacedElement element : sbasePlugin.getListOfReplacedElements())
{
setupReplacedElement(element, node, container);
}
}
}
}
private static void setupReplacedElement(ReplacedElement element, VariableNode node, ModelContainer container)
{
String subModelId = element.getSubmodelRef();
HierarchicalModel top = container.getHierarchicalModel();
HierarchicalModel sub = top.getSubmodel(subModelId);
CompModelPlugin compModel = container.getChild(subModelId).getCompModel();
if (element.isSetIdRef())
{
if (sub.containsSubmodel(element.getIdRef()))
{
sub = sub.getSubmodel(element.getIdRef());
}
if (element.isSetSBaseRef())
{
SBaseRef ref = element.getSBaseRef();
while (ref.isSetSBaseRef())
{
sub = sub.getSubmodel(element.getIdRef());
}
String subId = ref.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
sub.addDeletedBySid(subId);
}
else
{
String subId = element.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
sub.addDeletedBySid(subId);
}
}
else if (element.isSetPortRef())
{
Port port = compModel.getListOfPorts().get(element.getPortRef());
String subId = port.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
sub.addDeletedBySid(subId);
}
}
private static void setupReplacedBy(ReplacedBy element, VariableNode node, ModelContainer container)
{
String subModelId = element.getSubmodelRef();
HierarchicalModel top = container.getHierarchicalModel();
HierarchicalModel sub = top.getSubmodel(subModelId);
CompModelPlugin compModel = container.getChild(subModelId).getCompModel();
if (element.isSetIdRef())
{
if (sub.containsSubmodel(element.getIdRef()))
{
sub = sub.getSubmodel(element.getIdRef());
}
if (element.isSetSBaseRef())
{
SBaseRef ref = element.getSBaseRef();
while (ref.isSetSBaseRef())
{
sub = sub.getSubmodel(element.getIdRef());
}
String subId = ref.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
top.addDeletedBySid(subId);
}
else
{
String subId = element.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
top.addDeletedBySid(subId);
}
}
else if (element.isSetPortRef())
{
Port port = compModel.getListOfPorts().get(element.getPortRef());
String subId = port.getIdRef();
if(node != null)
{
sub.addMappingNode(subId, node);
}
top.addDeletedBySid(subId);
}
}
private static void setupReplacedElement(ReplacedElement element, ModelContainer container)
{
String subModelId = prefix + replacement.getSubmodelRef();
int subIndex = mapOfModels.get(subModelId);
HierarchicalModel sub = listOfModules.get(subIndex);
Model submodel = listOfModels.get(subIndex);
ReplacementHandler handler = null;
if (replacement.isSetIdRef())
{
String tmp = subModelId + "__" + replacement.getIdRef();
if (mapOfModels.containsKey(tmp))
{
subIndex = mapOfModels.get(tmp);
sub = listOfModules.get(subIndex);
submodel = listOfModels.get(subIndex);
}
if (replacement.isSetSBaseRef())
{
String subId = replacement.getSBaseRef().getIdRef();
handler = new ReplacementHandler(sub, subId, top, id);
listOfHandlers.add(handler);
top.addDeletedBySid(id);
}
else
{
String subId = replacement.getIdRef();
handler = new ReplacementHandler(sub, subId, top, id);
listOfHandlers.add(handler);
top.addDeletedBySid(id);
}
}
else if (replacement.isSetPortRef())
{
CompModelPlugin subModel = (CompModelPlugin) submodel.getExtension("comp");
Port port = subModel.getListOfPorts().get(replacement.getPortRef());
String subId = port.getIdRef();
handler = new ReplacementHandler(sub, subId, top, id);
listOfHandlers.add(handler);
top.addDeletedBySid(id);
}
return handler;
}
private static void setupReplacedElement(ReplacedElement element, String id, String prefix, HierarchicalModel top, CompModelPlugin topCompModel, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
String subModelId = prefix + element.getSubmodelRef();
int subIndex = mapOfModels.get(subModelId);
HierarchicalModel sub = listOfModules.get(subIndex);
Model submodel = listOfModels.get(subIndex);
CompModelPlugin compModel = (CompModelPlugin) submodel.getExtension("comp");
String subModelId = element.getSubmodelRef();
HierarchicalModel top = container.getHierarchicalModel();
HierarchicalModel sub = top.getSubmodel(subModelId);
CompModelPlugin compModel = container.getChild(subModelId).getCompModel();
if (element.isSetIdRef())
{
String tmp = subModelId + "__" + element.getIdRef();
if (mapOfModels.containsKey(tmp))
if (sub.containsSubmodel(element.getIdRef()))
{
subIndex = mapOfModels.get(tmp);
sub = listOfModules.get(subIndex);
submodel = listOfModels.get(subIndex);
sub = sub.getSubmodel(element.getMetaIdRef());
}
if (element.isSetSBaseRef())
{
SBaseRef ref = element.getSBaseRef();
while (ref.isSetSBaseRef())
{
tmp = tmp + "__" + ref.getIdRef();
ref = ref.getSBaseRef();
subIndex = mapOfModels.get(tmp);
sub = listOfModules.get(subIndex);
sub = sub.getSubmodel(element.getMetaIdRef());
}
String subId = ref.getIdRef();
listOfHandlers.add(new ReplacementHandler(top, id, sub, subId));
String subId = ref.getMetaIdRef();
sub.addDeletedBySid(subId);
}
else
{
String subId = element.getIdRef();
listOfHandlers.add(new ReplacementHandler(top, id, sub, subId));
sub.addDeletedBySid(subId);
}
}
else if (element.isSetPortRef())
{
Port port = compModel.getListOfPorts().get(element.getPortRef());
String subId = port.getIdRef();
listOfHandlers.add(new ReplacementHandler(top, id, sub, subId));
sub.addDeletedBySid(subId);
}
}
private static void setupReplacedBy(ReplacedBy replacement, String prefix, HierarchicalModel top, CompModelPlugin topCompModel, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
String subModelId = prefix + replacement.getSubmodelRef();
int subIndex = mapOfModels.get(subModelId);
if (replacement.isSetIdRef())
{
String tmp = subModelId + "__" + replacement.getIdRef();
if (mapOfModels.containsKey(tmp) && replacement.isSetSBaseRef())
{
subIndex = mapOfModels.get(tmp);
listOfModules.get(subIndex);
listOfModels.get(subIndex);
}
String subId = replacement.getSBaseRef().getMetaIdRef();
top.addDeletedBySid(subId);
}
else if (replacement.isSetMetaIdRef())
{
String subId = replacement.getMetaIdRef();
top.addDeletedByMetaId(subId);
}
else if (replacement.isSetPortRef())
{
Port port = topCompModel.getListOfPorts().get(replacement.getPortRef());
String subId = port.getMetaIdRef();
top.addDeletedByMetaId(subId);
}
}
private static void setupReplacedElement(ReplacedElement element, String prefix, HierarchicalModel top, CompModelPlugin topCompModel, List<ReplacementHandler> listOfHandlers, List<HierarchicalModel> listOfModules, List<Model> listOfModels, Map<String, Integer> mapOfModels)
{
String subModelId = prefix + element.getSubmodelRef();
int subIndex = mapOfModels.get(subModelId);
HierarchicalModel sub = listOfModules.get(subIndex);
Model submodel = listOfModels.get(subIndex);
CompModelPlugin compModel = (CompModelPlugin) submodel.getExtension("comp");
if (element.isSetIdRef())
{
String tmp = subModelId + "__" + element.getIdRef();
if (mapOfModels.containsKey(tmp) && element.isSetSBaseRef())
{
subIndex = mapOfModels.get(tmp);
sub = listOfModules.get(subIndex);
submodel = listOfModels.get(subIndex);
String subId = element.getSBaseRef().getMetaIdRef();
sub.addDeletedByMetaId(subId);
}
}
@ -422,4 +304,44 @@ public class ReplacementSetup
}
}
private static void setupReplacedBy(ReplacedBy element, ModelContainer container)
{
String subModelId = element.getSubmodelRef();
HierarchicalModel top = container.getHierarchicalModel();
HierarchicalModel sub = top.getSubmodel(subModelId);
CompModelPlugin compModel = container.getChild(subModelId).getCompModel();
if (element.isSetIdRef())
{
if (sub.containsSubmodel(element.getIdRef()))
{
sub = sub.getSubmodel(element.getIdRef());
}
if (element.isSetSBaseRef())
{
SBaseRef ref = element.getSBaseRef();
while (ref.isSetSBaseRef())
{
sub = sub.getSubmodel(element.getIdRef());
}
String subId = ref.getMetaIdRef();
top.addDeletedByMetaId(subId);
}
}
else if(element.isSetMetaId())
{
String subId = element.getMetaIdRef();
top.addDeletedBySid(subId);
}
else if (element.isSetPortRef())
{
Port port = compModel.getListOfPorts().get(element.getPortRef());
String subId = port.getMetaIdRef();
top.addDeletedByMetaId(subId);
}
}
}

View file

@ -1,84 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import java.util.Map;
import org.sbml.jsbml.ASTNode;
import org.sbml.jsbml.AssignmentRule;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.RateRule;
import org.sbml.jsbml.Rule;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.HierarchicalUtilities;
import edu.utah.ece.async.analysis.simulation.hierarchical.util.interpreter.MathInterpreter;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class RuleSetup
{
public static void setupRules(HierarchicalModel modelstate, Model model)
{
for (Rule rule : model.getListOfRules())
{
if (rule.isSetMetaId() && modelstate.isDeletedByMetaId(rule.getMetaId()) || !rule.isSetMath())
{
continue;
}
if (rule.isAssignment())
{
AssignmentRule assignRule = (AssignmentRule) rule;
setupSingleAssignmentRule(modelstate, assignRule.getVariable(), assignRule.getMath(), model, modelstate.getVariableToNodeMap());
}
else if (rule.isRate())
{
RateRule rateRule = (RateRule) rule;
setupSingleRateRule(modelstate, rateRule.getVariable(), rateRule.getMath(), model, modelstate.getVariableToNodeMap());
}
}
}
public static void setupSingleAssignmentRule(HierarchicalModel modelstate, String variable, ASTNode math, Model model, Map<String, VariableNode> variableToNodes)
{
math = HierarchicalUtilities.inlineFormula(modelstate, math, model);
VariableNode variableNode = variableToNodes.get(variable);
HierarchicalNode assignmentRule = MathInterpreter.parseASTNode(math, variableToNodes, variableNode);
FunctionNode node = new FunctionNode(variableNode, assignmentRule);
modelstate.addAssignRule(node);
variableNode.setHasRule(true);
}
public static void setupSingleRateRule(HierarchicalModel modelstate, String variable, ASTNode math, Model model, Map<String, VariableNode> variableToNodes)
{
//TODO: fix
math = HierarchicalUtilities.inlineFormula(modelstate, math, model);
VariableNode variableNode = variableToNodes.get(variable);
HierarchicalNode rateRule = MathInterpreter.parseASTNode(math, variableToNodes);
variableNode.setRateRule(rateRule);
}
}

View file

@ -1,129 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import org.sbml.jsbml.SpeciesReference;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.ReactionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesReferenceNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class SpeciesReferenceSetup
{
public static void setupSingleProduct(HierarchicalModel modelstate, ReactionNode reaction, String productID, SpeciesReference product, StateType type, VectorWrapper wrapper)
{
if (product.isSetId() && modelstate.isDeletedBySId(product.getId()))
{
return;
}
if (product.isSetMetaId() && modelstate.isDeletedByMetaId(product.getMetaId()))
{
return;
}
double stoichiometryValue = Double.isNaN(product.getStoichiometry()) ? 1 : product.getStoichiometry();
SpeciesReferenceNode speciesReferenceNode = new SpeciesReferenceNode();
if(!product.isConstant())
{
speciesReferenceNode.createState(type, wrapper);
}
else
{
speciesReferenceNode.createState(StateType.SCALAR, wrapper);
}
speciesReferenceNode.setValue(modelstate.getIndex(), stoichiometryValue);
SpeciesNode species = (SpeciesNode) modelstate.getNode(productID);
speciesReferenceNode.setSpecies(species);
reaction.addProduct(speciesReferenceNode);
if (product.isSetId() && product.getId().length() > 0)
{
speciesReferenceNode.setName(product.getId());
if (!product.getConstant())
{
modelstate.addVariable(speciesReferenceNode);
speciesReferenceNode.setIsVariableConstant(false);
}
else
{
modelstate.addMappingNode(product.getId(), speciesReferenceNode);
}
}
species.addODERate(reaction, speciesReferenceNode);
}
public static void setupSingleReactant(HierarchicalModel modelstate, ReactionNode reaction, String reactantID, SpeciesReference reactant, StateType type, VectorWrapper wrapper)
{
if (reactant.isSetId() && modelstate.isDeletedBySId(reactant.getId()))
{
return;
}
if (reactant.isSetMetaId() && modelstate.isDeletedByMetaId(reactant.getMetaId()))
{
return;
}
double stoichiometryValue = Double.isNaN(reactant.getStoichiometry()) ? 1 : reactant.getStoichiometry();
SpeciesReferenceNode speciesReferenceNode = new SpeciesReferenceNode();
if(!reactant.isConstant())
{
speciesReferenceNode.createState(type, wrapper);
}
else
{
speciesReferenceNode.createState(StateType.SCALAR, wrapper);
}
speciesReferenceNode.setValue(modelstate.getIndex(), stoichiometryValue);
SpeciesNode species = (SpeciesNode) modelstate.getNode(reactantID);
speciesReferenceNode.setSpecies(species);
reaction.addReactant(speciesReferenceNode);
if (reactant.isSetId() && reactant.getId().length() > 0)
{
speciesReferenceNode.setName(reactant.getId());
if (!reactant.getConstant())
{
modelstate.addVariable(speciesReferenceNode);
speciesReferenceNode.setIsVariableConstant(false);
}
else
{
modelstate.addMappingNode(reactant.getId(), speciesReferenceNode);
}
}
species.subtractODERate(reaction, speciesReferenceNode);
}
}

View file

@ -1,121 +0,0 @@
/*******************************************************************************
*
* This file is part of iBioSim. Please visit <http://www.async.ece.utah.edu/ibiosim>
* for the latest version of iBioSim.
*
* Copyright (C) 2017 University of Utah
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the Apache License. A copy of the license agreement is provided
* in the file named "LICENSE.txt" included with this software distribution
* and also available online at <http://www.async.ece.utah.edu/ibiosim/License>.
*
*******************************************************************************/
package edu.utah.ece.async.analysis.simulation.hierarchical.util.setup;
import java.io.IOException;
import org.sbml.jsbml.Model;
import org.sbml.jsbml.Species;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.FunctionNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.HierarchicalNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.SpeciesNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.VariableNode;
import edu.utah.ece.async.analysis.simulation.hierarchical.math.AbstractHierarchicalNode.Type;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel;
import edu.utah.ece.async.analysis.simulation.hierarchical.model.HierarchicalModel.ModelType;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.VectorWrapper;
import edu.utah.ece.async.analysis.simulation.hierarchical.states.HierarchicalState.StateType;
/**
*
*
* @author Leandro Watanabe
* @author Chris Myers
* @author <a href="http://www.async.ece.utah.edu/ibiosim#Credits"> iBioSim Contributors </a>
* @version %I%
*/
public class SpeciesSetup
{
/**
* sets up a single species
*
* @param species
* @param speciesID
*/
private static void setupSingleSpecies(HierarchicalModel modelstate, Species species, Model model, StateType type, VectorWrapper wrapper)
{
SpeciesNode node = createSpeciesNode(species, type, modelstate.getIndex(), wrapper);
VariableNode compartment = modelstate.getNode(species.getCompartment());
node.setCompartment(compartment);
if (species.isSetInitialAmount())
{
node.setValue(modelstate.getIndex(), species.getInitialAmount());
}
else if (species.isSetInitialConcentration())
{
HierarchicalNode initConcentration = new HierarchicalNode(Type.TIMES);
initConcentration.addChild(new HierarchicalNode(species.getInitialConcentration()));
initConcentration.addChild(compartment);
FunctionNode functionNode = new FunctionNode(node, initConcentration);
modelstate.addInitAssignment(functionNode);
functionNode.setIsInitAssignment(true);
}
if (species.getConstant())
{
modelstate.addMappingNode(species.getId(), node);
}
else
{
modelstate.addVariable(node);
}
}
/**
* puts species-related information into data structures
*
* @throws IOException
*/
public static void setupSpecies(HierarchicalModel modelstate, StateType type, Model model, VectorWrapper wrapper)
{
for (Species species : model.getListOfSpecies())
{
if (modelstate.isDeletedBySId(species.getId()))
{
continue;
}
if (ArraysSetup.checkArray(species))
{
continue;
}
setupSingleSpecies(modelstate, species, model, type, wrapper);
}
}
private static SpeciesNode createSpeciesNode(Species species, StateType type, int index, VectorWrapper wrapper)
{
SpeciesNode node = new SpeciesNode(species.getId());
node.createSpeciesTemplate(index);
if(species.getConstant())
{
node.createState(StateType.SCALAR, wrapper);
}
else
{
node.createState(type, wrapper);
}
node.setValue(index, 0);
node.setBoundaryCondition(species.getBoundaryCondition(), index);
node.setHasOnlySubstance(species.getHasOnlySubstanceUnits(), index);
node.setIsVariableConstant(species.getConstant());
return node;
}
}

View file

@ -196,7 +196,7 @@ public class MovieContainer extends JPanel implements ActionListener {
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}});
return filenames;
return filenames;
}
/**

View file

@ -20,6 +20,7 @@ import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@ -1458,15 +1459,22 @@ public class LearnGCM extends JPanel implements ActionListener, Runnable
}
else if (methods.getSelectedItem().equals("GeneNet (Java)"))
{
if(Run.run(learnFile, directory))
{
try {
if(Run.run(learnFile, directory))
{
opendot(Runtime.getRuntime(), new File(directory));
}
else
{
JOptionPane.showMessageDialog(Gui.frame, "Something went wrong and could not learn model.", "Error in learning.", JOptionPane.ERROR_MESSAGE);
}
opendot(Runtime.getRuntime(), new File(directory));
}
else
{
JOptionPane.showMessageDialog(Gui.frame, "Something went wrong and could not learn model.", "Error in learning.", JOptionPane.ERROR_MESSAGE);
}
} catch (HeadlessException e) {
e.printStackTrace();
} catch (BioSimException e) {
JOptionPane.showMessageDialog(Gui.frame, e.getMessage(), e.getTitle(), JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
if (estimator.getSelection().equals("SRES"))

View file

@ -29,6 +29,7 @@ import java.util.Map;
import java.util.Set;
import edu.utah.ece.async.dataModels.util.GlobalConstants;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
*
@ -147,7 +148,7 @@ public class Learn
}
}
public void learnNetwork(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L)
public void learnNetwork(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L) throws BioSimException
{
EncodeExpts(S, E, C, T, L);
@ -165,12 +166,17 @@ public class Learn
}
}
private void EncodeExpts(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L)
private void EncodeExpts(SpeciesCollection S, Experiments E, NetCon C, Thresholds T, Encodings L) throws BioSimException
{
for (int i = 0; i < S.size(); i++)
{
getDiscreteLevels(S.getInterestingSpecies(i), S, E, L, bins);
getBinAssign(S.getInterestingSpecies(i), S, E, L, bins);
String species = S.getInterestingSpecies(i);
if(!S.containsSpeciesData(species))
{
throw new BioSimException("There is no data for " + species + ". Check if species ids in the target model match the ones from the data.", "Error in learning.");
}
getDiscreteLevels(species, S, E, L, bins);
getBinAssign(species, S, E, L, bins);
}
}
@ -623,7 +629,7 @@ public class Learn
}
public void getDotFile(String filename, String directory, SpeciesCollection collection, NetCon network)
public void getDotFile(String filename, String directory, SpeciesCollection collection, NetCon network) throws BioSimException
{
Map<String, String> speciesToNode;
File fout = new File(directory + GlobalConstants.separator + filename);
@ -666,11 +672,11 @@ public class Learn
}
catch (FileNotFoundException e)
{
System.out.println("Could not write dot file. File could not be found.");
throw new BioSimException("Could not write dot file. File could not be found.", "Error in Learning");
}
catch (IOException e)
{
System.out.println("Error when writing dot file.");
throw new BioSimException("Error when writing dot file.", "Error in Learning");
}
finally
{
@ -683,7 +689,7 @@ public class Learn
}
catch (IOException e)
{
System.out.println("Failed to close writer");
throw new BioSimException("Failed to close writer", "Error in Learning");
}
try
@ -695,7 +701,7 @@ public class Learn
}
catch (IOException e)
{
System.out.println("Failed to close outputstream");
throw new BioSimException("Failed to close outputstream", "Error in Learning");
}
}

View file

@ -27,6 +27,8 @@ import org.sbml.jsbml.SBMLDocument;
import org.sbml.jsbml.SBMLReader;
import org.sbml.jsbml.Species;
import edu.utah.ece.async.dataModels.util.exceptions.BioSimException;
/**
*
*
@ -38,242 +40,242 @@ import org.sbml.jsbml.Species;
public class Run
{
private static int experiment;
private static int experiment;
public static boolean run(String filename, String directory)
{
experiment = 0;
SpeciesCollection S = new SpeciesCollection();
Experiments E = new Experiments();
Encodings L = new Encodings();
Thresholds T = new Thresholds();
NetCon C = new NetCon();
init(filename, S);
loadExperiments(directory, S, E);
if(experiment < 1)
{
return false;
}
Learn learn = new Learn(3);
learn.learnNetwork(S, E, C, T, L);
learn.getDotFile("method.gcm", directory, S, C);
learn.getDotFile("method.dot", directory, S, C);
return true;
}
public static boolean run(String filename, String directory) throws BioSimException
{
experiment = 0;
SpeciesCollection S = new SpeciesCollection();
Experiments E = new Experiments();
Encodings L = new Encodings();
Thresholds T = new Thresholds();
NetCon C = new NetCon();
init(filename, S);
loadExperiments(directory, S, E);
if(experiment < 1)
{
return false;
}
Learn learn = new Learn(3);
learn.learnNetwork(S, E, C, T, L);
learn.getDotFile("method.gcm", directory, S, C);
learn.getDotFile("method.dot", directory, S, C);
public static void loadExperiments(String directory, SpeciesCollection S, Experiments E)
{
File path = new File(directory);
return true;
}
for (File file : path.listFiles())
{
String name = file.getAbsolutePath();
if (name.endsWith(".tsd"))
{
parse(name, S, E);
experiment++;
}
else if (name.endsWith(".csv"))
{
parseCSV(name, S, E);
experiment++;
}
}
}
public static void loadExperiments(String directory, SpeciesCollection S, Experiments E) throws BioSimException
{
File path = new File(directory);
public static void init(String filename, SpeciesCollection S)
{
try
{
SBMLDocument doc = SBMLReader.read(new File(filename));
for (File file : path.listFiles())
{
String name = file.getAbsolutePath();
if (name.endsWith(".tsd"))
{
parse(name, S, E);
experiment++;
}
else if (name.endsWith(".csv"))
{
parseCSV(name, S, E);
experiment++;
}
}
}
Model model = doc.getModel();
public static void init(String filename, SpeciesCollection S)
{
try
{
SBMLDocument doc = SBMLReader.read(new File(filename));
for (Species species : model.getListOfSpecies())
{
S.addInterestingSpecies(species.getId());
}
}
Model model = doc.getModel();
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
for (Species species : model.getListOfSpecies())
{
S.addInterestingSpecies(species.getId());
}
}
private static void parseCSV(String filename, SpeciesCollection S, Experiments E)
{
Scanner scan = null;
boolean isFirst = true;
try
{
scan = new Scanner(new File(filename));
int row = 0;
while (scan.hasNextLine())
{
String line = scan.nextLine();
catch (XMLStreamException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
String[] values = line.split(",");
private static void parseCSV(String filename, SpeciesCollection S, Experiments E)
{
Scanner scan = null;
boolean isFirst = true;
try
{
scan = new Scanner(new File(filename));
int row = 0;
while (scan.hasNextLine())
{
String line = scan.nextLine();
if (isFirst)
{
for (int i = 0; i < values.length; i++)
{
S.addSpecies(values[i], i);
}
isFirst = false;
}
else
{
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
row++;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find the file!");
}
finally
{
if (scan != null)
{
scan.close();
}
String[] values = line.split(",");
}
}
if (isFirst)
{
for (int i = 0; i < values.length; i++)
{
S.addSpecies(values[i], i);
}
isFirst = false;
}
else
{
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
row++;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find the file!");
}
finally
{
if (scan != null)
{
scan.close();
}
private static void parse(String filename, SpeciesCollection S, Experiments E)
{
InputStream input = null;
}
}
try
{
private static void parse(String filename, SpeciesCollection S, Experiments E) throws BioSimException
{
InputStream input = null;
String buffer = "";
char state = 1;
char read = 0;
int row = 0;
input = new FileInputStream(filename);
try
{
int data = input.read();
while (data != -1)
{
data = input.read();
read = (char) data;
String buffer = "";
char state = 1;
char read = 0;
int row = 0;
input = new FileInputStream(filename);
if (read == ' ' || read == '\n')
{
continue;
}
int data = input.read();
while (data != -1)
{
data = input.read();
read = (char) data;
switch (state)
{
case 1:
if (read == '(')
{
state = 2;
buffer = "";
break;
}
else
{
return;
}
case 2:
if (read == ')')
{
state = 3;
if (read == ' ' || read == '\n')
{
continue;
}
row = 0;
String[] ids = buffer.split(",");
switch (state)
{
case 1:
if (read == '(')
{
state = 2;
buffer = "";
break;
}
else
{
return;
}
case 2:
if (read == ')')
{
state = 3;
if (experiment == 0)
{
for (int i = 0; i < ids.length; i++)
{
S.addSpecies(ids[i].substring(1, ids[i].length() - 1), i);
}
}
row = 0;
String[] ids = buffer.split(",");
break;
}
else
{
buffer += read;
if (experiment == 0)
{
for (int i = 0; i < ids.length; i++)
{
S.addSpecies(ids[i].substring(1, ids[i].length() - 1), i);
}
}
break;
}
case 3:
if (read == '(')
{
state = 4;
buffer = "";
break;
}
if (read == ',')
{
break;
}
if (read == ')')
{
return;
}
else
{
return;
}
default:
if (read == ')')
{
state = 3;
String[] values = buffer.replace(" ", "").split(",");
break;
}
else
{
buffer += read;
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
break;
}
case 3:
if (read == '(')
{
state = 4;
buffer = "";
break;
}
if (read == ',')
{
break;
}
if (read == ')')
{
return;
}
else
{
return;
}
default:
if (read == ')')
{
state = 3;
String[] values = buffer.replace(" ", "").split(",");
row++;
}
else
{
buffer += read;
}
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find the file!");
}
catch (IOException e)
{
System.out.println("There was a problem when reading the file!");
}
finally
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException e)
{
System.out.println("Failed to close input stream");
}
for (int i = 0; i < values.length; i++)
{
E.addExperiment(experiment, row, i, Double.parseDouble(values[i]));
}
}
}
row++;
}
else
{
buffer += read;
}
}
}
}
catch (FileNotFoundException e)
{
throw new BioSimException("Could not find the file!", "Error in Learning");
}
catch (IOException e)
{
throw new BioSimException("There was a problem when reading the file!", "Error in Learning");
}
finally
{
try
{
if (input != null)
{
input.close();
}
}
catch (IOException e)
{
throw new BioSimException("Failed to close input stream", "Error in Learning");
}
}
}
}

View file

@ -71,4 +71,8 @@ public class SpeciesCollection
return interestingSpecies;
}
public boolean containsSpeciesData(String species)
{
return speciesColumn.containsKey(species);
}
}