use of cbit.vcell.math.MathDescription in project vcell by virtualcell.
the class MatlabOdeFileCoder method write_V6_MFile.
/**
* Insert the method's description here.
* Creation date: (3/8/00 10:31:52 PM)
*/
public void write_V6_MFile(java.io.PrintWriter pw, String functionName) throws MathException, ExpressionException {
MathDescription mathDesc = simulation.getMathDescription();
if (!mathDesc.isValid()) {
throw new MathException("invalid math description\n" + mathDesc.getWarning());
}
if (mathDesc.isSpatial()) {
throw new MathException("spatial math description, cannot create ode file");
}
if (mathDesc.hasFastSystems()) {
throw new MathException("math description contains algebraic constraints, cannot create .m file");
}
//
// print function declaration
//
pw.println("function [T,Y,yinit,param, allNames, allValues] = " + functionName + "(argTimeSpan,argYinit,argParam)");
pw.println("% [T,Y,yinit,param] = " + functionName + "(argTimeSpan,argYinit,argParam)");
pw.println("%");
pw.println("% input:");
pw.println("% argTimeSpan is a vector of start and stop times (e.g. timeSpan = [0 10.0])");
pw.println("% argYinit is a vector of initial conditions for the state variables (optional)");
pw.println("% argParam is a vector of values for the parameters (optional)");
pw.println("%");
pw.println("% output:");
pw.println("% T is the vector of times");
pw.println("% Y is the vector of state variables");
pw.println("% yinit is the initial conditions that were used");
pw.println("% param is the parameter vector that was used");
pw.println("% allNames is the output solution variable names");
pw.println("% allValues is the output solution variable values corresponding to the names");
pw.println("%");
pw.println("% example of running this file: [T,Y,yinit,param,allNames,allValues] = myMatlabFunc; <-(your main function name)");
pw.println("%");
VariableHash varHash = new VariableHash();
for (Variable var : simulationSymbolTable.getVariables()) {
varHash.addVariable(var);
}
Variable[] variables = varHash.getTopologicallyReorderedVariables();
CompartmentSubDomain subDomain = (CompartmentSubDomain) mathDesc.getSubDomains().nextElement();
//
// collect "true" constants (Constants without identifiers)
//
//
// collect "variables" (VolVariables only)
//
//
// collect "functions" (Functions and Constants with identifiers)
//
Vector<Constant> constantList = new Vector<Constant>();
Vector<VolVariable> volVarList = new Vector<VolVariable>();
Vector<Variable> functionList = new Vector<Variable>();
for (int i = 0; i < variables.length; i++) {
if (variables[i] instanceof Constant) {
Constant constant = (Constant) variables[i];
String[] symbols = constant.getExpression().getSymbols();
if (symbols == null || symbols.length == 0) {
constantList.addElement(constant);
} else {
functionList.add(constant);
}
} else if (variables[i] instanceof VolVariable) {
volVarList.addElement((VolVariable) variables[i]);
} else if (variables[i] instanceof Function) {
functionList.addElement(variables[i]);
}
}
Constant[] constants = (Constant[]) BeanUtils.getArray(constantList, Constant.class);
VolVariable[] volVars = (VolVariable[]) BeanUtils.getArray(volVarList, VolVariable.class);
Variable[] functions = (Variable[]) BeanUtils.getArray(functionList, Variable.class);
int numVars = volVarList.size() + functionList.size();
String varNamesForStringArray = "";
String varNamesForValueArray = "";
for (Variable var : volVarList) {
varNamesForStringArray = varNamesForStringArray + "'" + var.getName() + "';";
varNamesForValueArray = varNamesForValueArray + var.getName() + " ";
}
for (Variable func : functionList) {
varNamesForStringArray = varNamesForStringArray + "'" + func.getName() + "';";
varNamesForValueArray = varNamesForValueArray + func.getName() + " ";
}
pw.println("");
pw.println("%");
pw.println("% Default time span");
pw.println("%");
double beginTime = 0.0;
double endTime = simulation.getSolverTaskDescription().getTimeBounds().getEndingTime();
pw.println("timeSpan = [" + beginTime + " " + endTime + "];");
pw.println("");
pw.println("% output variable lengh and names");
pw.println("numVars = " + numVars + ";");
pw.println("allNames = {" + varNamesForStringArray + "};");
pw.println("");
pw.println("if nargin >= 1");
pw.println("\tif length(argTimeSpan) > 0");
pw.println("\t\t%");
pw.println("\t\t% TimeSpan overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\ttimeSpan = argTimeSpan;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% Default Initial Conditions");
pw.println("%");
pw.println("yinit = [");
for (int j = 0; j < volVars.length; j++) {
Expression initial = subDomain.getEquation(volVars[j]).getInitialExpression();
double defaultInitialCondition = 0;
try {
initial.bindExpression(mathDesc);
defaultInitialCondition = initial.evaluateConstant();
pw.println("\t" + defaultInitialCondition + ";\t\t% yinit(" + (j + 1) + ") is the initial condition for '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[j].getName()) + "'");
} catch (ExpressionException e) {
e.printStackTrace(System.out);
pw.println("\t" + initial.infix_Matlab() + ";\t\t% yinit(" + (j + 1) + ") is the initial condition for '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[j].getName()) + "'");
// throw new RuntimeException("error evaluating initial condition for variable "+volVars[j].getName());
}
}
pw.println("];");
pw.println("if nargin >= 2");
pw.println("\tif length(argYinit) > 0");
pw.println("\t\t%");
pw.println("\t\t% initial conditions overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\tyinit = argYinit;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% Default Parameters");
pw.println("% constants are only those \"Constants\" from the Math Description that are just floating point numbers (no identifiers)");
pw.println("% note: constants of the form \"A_init\" are really initial conditions and are treated in \"yinit\"");
pw.println("%");
pw.println("param = [");
int paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + constants[i].getExpression().infix_Matlab() + ";\t\t% param(" + (paramIndex + 1) + ") is '" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + "'");
paramIndex++;
}
pw.println("];");
pw.println("if nargin >= 3");
pw.println("\tif length(argParam) > 0");
pw.println("\t\t%");
pw.println("\t\t% parameter values overridden by function arguments");
pw.println("\t\t%");
pw.println("\t\tparam = argParam;");
pw.println("\tend");
pw.println("end");
pw.println("%");
pw.println("% invoke the integrator");
pw.println("%");
pw.println("[T,Y] = ode15s(@f,timeSpan,yinit,odeset('OutputFcn',@odeplot),param,yinit);");
pw.println("");
pw.println("% get the solution");
pw.println("all = zeros(size(T), numVars);");
pw.println("for i = 1:size(T)");
pw.println("\tall(i,:) = getRow(T(i), Y(i,:), yinit, param);");
pw.println("end");
pw.println("");
pw.println("allValues = all;");
pw.println("end");
// get row data for solution
pw.println("");
pw.println("% -------------------------------------------------------");
pw.println("% get row data");
pw.println("function rowValue = getRow(t,y,y0,p)");
//
// print volVariables (in order and assign to var vector)
//
pw.println("\t% State Variables");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()) + " = y(" + (i + 1) + ");");
}
//
// print constants
//
pw.println("\t% Constants");
paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + " = p(" + (paramIndex + 1) + ");");
paramIndex++;
}
//
// print variables
//
pw.println("\t% Functions");
for (int i = 0; i < functions.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(functions[i].getName()) + " = " + functions[i].getExpression().infix_Matlab() + ";");
}
pw.println("");
pw.println("\trowValue = [" + varNamesForValueArray + "];");
pw.println("end");
//
// print ode-rate
//
pw.println("");
pw.println("% -------------------------------------------------------");
pw.println("% ode rate");
pw.println("function dydt = f(t,y,p,y0)");
//
// print volVariables (in order and assign to var vector)
//
pw.println("\t% State Variables");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()) + " = y(" + (i + 1) + ");");
}
//
// print constants
//
pw.println("\t% Constants");
paramIndex = 0;
for (int i = 0; i < constants.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(constants[i].getName()) + " = p(" + (paramIndex + 1) + ");");
paramIndex++;
}
//
// print variables
//
pw.println("\t% Functions");
for (int i = 0; i < functions.length; i++) {
pw.println("\t" + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(functions[i].getName()) + " = " + functions[i].getExpression().infix_Matlab() + ";");
}
pw.println("\t% Rates");
pw.println("\tdydt = [");
for (int i = 0; i < volVars.length; i++) {
pw.println("\t\t" + subDomain.getEquation(volVars[i]).getRateExpression().infix_Matlab() + "; % rate for " + cbit.vcell.parser.SymbolUtils.getEscapedTokenMatlab(volVars[i].getName()));
}
pw.println("\t];");
pw.println("end");
}
use of cbit.vcell.math.MathDescription in project vcell by virtualcell.
the class ClientRequestManager method createMathModel.
/**
* Insert the method's description here. Creation date: (5/24/2004 12:22:11 PM)
*
* @param windowID java.lang.String
*/
private MathModel createMathModel(String name, Geometry geometry) {
MathModel mathModel = new MathModel(null);
MathDescription mathDesc = mathModel.getMathDescription();
try {
mathDesc.setGeometry(geometry);
if (geometry.getDimension() == 0) {
mathDesc.addSubDomain(new CompartmentSubDomain("Compartment", CompartmentSubDomain.NON_SPATIAL_PRIORITY));
} else {
try {
if (geometry.getDimension() > 0 && geometry.getGeometrySurfaceDescription().getGeometricRegions() == null) {
geometry.getGeometrySurfaceDescription().updateAll();
}
} catch (ImageException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
} catch (GeometryException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Geometric surface generation error: \n" + e.getMessage());
}
SubVolume[] subVolumes = geometry.getGeometrySpec().getSubVolumes();
for (int i = 0; i < subVolumes.length; i++) {
mathDesc.addSubDomain(new CompartmentSubDomain(subVolumes[i].getName(), subVolumes[i].getHandle()));
}
//
// add only those MembraneSubDomains corresponding to surfaces that acutally
// exist in geometry.
//
GeometricRegion[] regions = geometry.getGeometrySurfaceDescription().getGeometricRegions();
for (int i = 0; i < regions.length; i++) {
if (regions[i] instanceof SurfaceGeometricRegion) {
SurfaceGeometricRegion surfaceRegion = (SurfaceGeometricRegion) regions[i];
SubVolume subVolume1 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[0]).getSubVolume();
SubVolume subVolume2 = ((VolumeGeometricRegion) surfaceRegion.getAdjacentGeometricRegions()[1]).getSubVolume();
CompartmentSubDomain compartment1 = mathDesc.getCompartmentSubDomain(subVolume1.getName());
CompartmentSubDomain compartment2 = mathDesc.getCompartmentSubDomain(subVolume2.getName());
MembraneSubDomain membraneSubDomain = mathDesc.getMembraneSubDomain(compartment1, compartment2);
if (membraneSubDomain == null) {
SurfaceClass surfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(subVolume1, subVolume2);
membraneSubDomain = new MembraneSubDomain(compartment1, compartment2, surfaceClass.getName());
mathDesc.addSubDomain(membraneSubDomain);
}
}
}
}
mathDesc.isValid();
mathModel.setName(name);
} catch (Exception e) {
e.printStackTrace(System.out);
}
return mathModel;
}
use of cbit.vcell.math.MathDescription in project vcell by virtualcell.
the class ClientRequestManager method openAfterChecking.
private void openAfterChecking(VCDocumentInfo documentInfo, final TopLevelWindowManager requester, final boolean inNewWindow) {
final String DOCUMENT_INFO = "documentInfo";
final String SEDML_TASK = "SedMLTask";
final String SEDML_MODELS = "SedMLModels";
final String BNG_UNIT_SYSTEM = "bngUnitSystem";
final String BMDB_DEFAULT_APPLICATION = "Deterministic";
/* asynchronous and not blocking any window */
bOpening = true;
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
// may want to insert corrected VCDocumentInfo later if our import debugger
// corrects it (BNGL Debugger).
hashTable.put(DOCUMENT_INFO, documentInfo);
hashTable.put("isBMDB", false);
hashTable.put("isSEDML", false);
// start a thread that gets it and updates the GUI by creating a new document
// desktop
String taskName = null;
if (documentInfo instanceof ExternalDocInfo) {
taskName = "Importing document";
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
String fileText;
String originalFileText;
try {
fileText = BeanUtils.readBytesFromFile(file, null);
originalFileText = new String(fileText);
} catch (IOException e1) {
e1.printStackTrace();
DialogUtils.showErrorDialog(requester.getComponent(), "<html>Error reading file " + file.getPath() + "</html>");
return;
}
Reader reader = externalDocInfo.getReader();
boolean bException = true;
while (bException) {
try {
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
boolean bStochastic = true;
boolean bRuleBased = true;
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
ASTModel astModel = RbmUtils.importBnglFile(reader);
// for now, hasUnitSystem() always returns false
if (astModel.hasUnitSystem()) {
bngUnitSystem = astModel.getUnitSystem();
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
bException = false;
} catch (final Exception e) {
e.printStackTrace(System.out);
BNGLDebuggerPanel panel = new BNGLDebuggerPanel(fileText, e);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, "Bngl Debugger: " + file.getName());
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
throw new UserCancelException("Canceling Import");
}
// inserting <potentially> corrected DocumentInfo
fileText = panel.getText();
externalDocInfo = new ExternalDocInfo(panel.getText());
reader = externalDocInfo.getReader();
hashTable.put(DOCUMENT_INFO, externalDocInfo);
}
}
if (!originalFileText.equals(fileText)) {
// file has been modified
String message = "Importing <b>" + file.getName() + "</b> into vCell. <br>Overwrite the file on the disk?<br>";
message = "<html>" + message + "</html>";
Object[] options = { "Overwrite and Import", "Import Only", "Cancel" };
int returnCode = JOptionPane.showOptionDialog(requester.getComponent(), message, "Bngl Debugger", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[2]);
if (returnCode == JOptionPane.YES_OPTION) {
try {
FileWriter fw = new FileWriter(file);
fw.write(fileText);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (returnCode == JOptionPane.CANCEL_OPTION || returnCode == JOptionPane.CLOSED_OPTION) {
return;
}
}
if (!(bngUnitSystem.getOrigin() == BngUnitOrigin.PARSER)) {
BNGLUnitsPanel panel = new BNGLUnitsPanel(bngUnitSystem);
int oKCancel = DialogUtils.showComponentOKCancelDialog(requester.getComponent(), panel, " Bngl Units Selector", null, false);
if (oKCancel == JOptionPane.CANCEL_OPTION || oKCancel == JOptionPane.DEFAULT_OPTION) {
// TODO: or do nothing and continue with default values?
return;
} else {
bngUnitSystem = panel.getUnits();
}
}
hashTable.put(BNG_UNIT_SYSTEM, bngUnitSystem);
} else if (file != null && !file.getName().isEmpty() && file.getName().toLowerCase().endsWith(".sedml")) {
try {
XMLSource xmlSource = externalDocInfo.createXMLSource();
File sedmlFile = xmlSource.getXmlFile();
SedML sedml = Libsedml.readDocument(sedmlFile).getSedMLModel();
if (sedml == null || sedml.getModels().isEmpty()) {
return;
}
// AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(),
// file.getName());
List<SedML> sedmls = new ArrayList<>();
sedmls.add(sedml);
hashTable.put(SEDML_MODELS, sedmls);
// hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read document: " + e.getMessage(), e);
}
} else if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
try {
ArchiveComponents ac = null;
ac = Libsedml.readSEDMLArchive(new FileInputStream(file));
List<SEDMLDocument> docs = ac.getSedmlDocuments();
List<SedML> sedmls = new ArrayList<>();
for (SEDMLDocument doc : docs) {
SedML sedml = doc.getSedMLModel();
if (sedml == null) {
throw new RuntimeException("Failed importing " + file.getName());
}
if (sedml.getModels().isEmpty()) {
throw new RuntimeException("Unable to find any model in " + file.getName());
}
sedmls.add(sedml);
}
// AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(),
// file.getName());
hashTable.put(SEDML_MODELS, sedmls);
// hashTable.put(SEDML_TASK, chosenTask);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("failed to read archive: " + e.getMessage(), e);
}
}
} else {
taskName = "Loading document '" + documentInfo.getVersion().getName() + "' from database";
}
AsynchClientTask task0 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (!inNewWindow) {
// request was to replace the document in an existing window
getMdiManager().blockWindow(requester.getManagerID());
}
}
};
AsynchClientTask task1 = new AsynchClientTask(taskName, AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = null;
List<VCDocument> docs = new ArrayList<>();
boolean isBMDB = false;
boolean isSEDML = false;
VCDocumentInfo documentInfo = (VCDocumentInfo) hashTable.get(DOCUMENT_INFO);
if (documentInfo instanceof BioModelInfo) {
BioModelInfo bmi = (BioModelInfo) documentInfo;
doc = getDocumentManager().getBioModel(bmi);
} else if (documentInfo instanceof MathModelInfo) {
MathModelInfo mmi = (MathModelInfo) documentInfo;
doc = getDocumentManager().getMathModel(mmi);
} else if (documentInfo instanceof GeometryInfo) {
GeometryInfo gmi = (GeometryInfo) documentInfo;
doc = getDocumentManager().getGeometry(gmi);
} else if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
File file = externalDocInfo.getFile();
if (file != null && !file.getName().isEmpty() && (file.getName().toLowerCase().endsWith(".sedx") || file.getName().toLowerCase().endsWith(".omex"))) {
TranslationLogger transLogger = new TranslationLogger(requester);
// iterate through one or more SEDML objects
List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
for (SedML sedml : sedmls) {
// default to import all tasks
List<VCDocument> vcdocs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, null, false);
for (VCDocument vcdoc : vcdocs) {
docs.add(vcdoc);
}
}
// treat the same since OMEX is just and archive with SED-ML file(s)
isSEDML = true;
} else if (!externalDocInfo.isXML()) {
if (hashTable.containsKey(BNG_UNIT_SYSTEM)) {
// not XML, look for BNGL etc.
// we use the BngUnitSystem already created during the 1st pass
BngUnitSystem bngUnitSystem = (BngUnitSystem) hashTable.get(BNG_UNIT_SYSTEM);
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
SimulationContext odeSimContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
appList.add(odeSimContext);
// set convention for initial conditions in generated application for seed
// species (concentration or count)
ruleBasedSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
odeSimContext.setUsingConcentration(bngUnitSystem.isConcentration());
RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
Reader reader = externalDocInfo.getReader();
ASTModel astModel = RbmUtils.importBnglFile(reader);
if (bioModel.getModel() != null && bioModel.getModel().getVcMetaData() != null) {
VCMetaData vcMetaData = bioModel.getModel().getVcMetaData();
vcMetaData.setFreeTextAnnotation(bioModel, astModel.getProlog());
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing. Extracting it from Species, Reactions, Obserbables.");
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, true);
}
// we'll convert the kinetic parameters to BngUnitSystem inside the
// visit(ASTKineticsParameter...)
astModel.jjtAccept(constructionVisitor, rbmModelContainer);
// set the volume in the newly created application to
// BngUnitSystem.bnglModelVolume
// TODO: set the right values if we import compartments from the bngl file!
// if(!bngUnitSystem.isConcentration()) {
Expression sizeExpression = new Expression(bngUnitSystem.getVolume());
ruleBasedSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
odeSimContext.getGeometryContext().getStructureMapping(0).getSizeParameter().setExpression(sizeExpression);
// }
// we remove the NFSim application if any seed species is clamped because NFSim
// doesn't know what to do with it
boolean bClamped = false;
for (SpeciesContextSpec scs : ruleBasedSimContext.getReactionContext().getSpeciesContextSpecs()) {
if (scs.isConstant()) {
bClamped = true;
break;
}
}
if (bClamped) {
bioModel.removeSimulationContext(ruleBasedSimContext);
}
// // TODO: DON'T delete this code
// // the code below is needed if we also want to create simulations, example for 1 rule based simulation
// // it is rule-based so it wont have to flatten, should be fast.
// MathMappingCallback callback = new MathMappingCallbackTaskAdapter(getClientTaskStatusSupport());
// NetworkGenerationRequirements networkGenerationRequirements = null; // network generation should not be executed.
// ruleBasedSimContext.refreshMathDescription(callback,networkGenerationRequirements);
// Simulation sim = ruleBasedSimContext.addNewSimulation(SimulationOwner.DEFAULT_SIM_NAME_PREFIX,callback,networkGenerationRequirements);
doc = bioModel;
}
} else {
// is XML
try (TranslationLogger transLogger = new TranslationLogger(requester)) {
XMLSource xmlSource = externalDocInfo.createXMLSource();
org.jdom.Element rootElement = xmlSource.getXmlDoc().getRootElement();
String xmlType = rootElement.getName();
String modelXmlType = null;
if (xmlType.equals(XMLTags.VcmlRootNodeTag)) {
// For now, assuming that <vcml> element has only one child (biomodel, mathmodel
// or geometry).
// Will deal with multiple children of <vcml> Element when we get to model
// composition.
@SuppressWarnings("unchecked") List<Element> childElementList = rootElement.getChildren();
// assuming first child is the biomodel,
Element modelElement = childElementList.get(0);
// mathmodel or geometry.
modelXmlType = modelElement.getName();
}
if (xmlType.equals(XMLTags.BioModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.BioModelTag))) {
doc = XmlHelper.XMLToBioModel(xmlSource);
} else if (xmlType.equals(XMLTags.MathModelTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.MathModelTag))) {
doc = XmlHelper.XMLToMathModel(xmlSource);
} else if (xmlType.equals(XMLTags.GeometryTag) || (xmlType.equals(XMLTags.VcmlRootNodeTag) && modelXmlType.equals(XMLTags.GeometryTag))) {
doc = XmlHelper.XMLToGeometry(xmlSource);
} else if (xmlType.equals(XMLTags.SbmlRootNodeTag)) {
Namespace namespace = rootElement.getNamespace(XMLTags.SBML_SPATIAL_NS_PREFIX);
isBMDB = externalDocInfo.isBioModelsNet();
boolean bIsSpatial = (namespace == null) ? false : true;
doc = XmlHelper.importSBML(transLogger, xmlSource, bIsSpatial);
} else if (xmlType.equals(XMLTags.CellmlRootNodeTag)) {
if (requester instanceof BioModelWindowManager) {
doc = XmlHelper.importBioCellML(transLogger, xmlSource);
} else {
doc = XmlHelper.importMathCellML(transLogger, xmlSource);
}
} else if (xmlType.equals(MicroscopyXMLTags.FRAPStudyTag)) {
doc = VFrapXmlHelper.VFRAPToBioModel(hashTable, xmlSource, getDocumentManager(), requester);
} else if (xmlType.equals(XMLTags.SedMLTypeTag)) {
// we know it is a single SedML since it is an actual XML source
List<SedML> sedmls = (List<SedML>) hashTable.get(SEDML_MODELS);
SedML sedml = sedmls.get(0);
// default to import all tasks
docs = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, sedml, null, externalDocInfo.getFile().getAbsolutePath(), false);
isSEDML = true;
} else {
// unknown XML format
throw new RuntimeException("unsupported XML format, first element tag is <" + rootElement.getName() + ">");
}
if (externalDocInfo.getDefaultName() != null) {
doc.setName(externalDocInfo.getDefaultName());
}
}
}
if (doc == null && docs == null) {
File f = externalDocInfo.getFile();
if (f != null) {
throw new RuntimeException("Unable to determine type of file " + f.getCanonicalPath());
}
throw new ProgrammingException();
}
}
// create biopax objects using annotation
if (doc instanceof BioModel) {
BioModel bioModel = (BioModel) doc;
try {
bioModel.getVCMetaData().createBioPaxObjects(bioModel);
} catch (Exception e) {
e.printStackTrace();
}
}
requester.prepareDocumentToLoad(doc, inNewWindow);
hashTable.put("isBMDB", isBMDB);
hashTable.put("isSEDML", isSEDML);
if (!isSEDML) {
hashTable.put("doc", doc);
} else {
hashTable.put("docs", docs);
}
}
};
AsynchClientTask task2 = new AsynchClientTask("Showing document", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
try {
Throwable exc = (Throwable) hashTable.get(ClientTaskDispatcher.TASK_ABORTED_BY_ERROR);
if (exc == null) {
boolean isSEDML = (boolean) hashTable.get("isSEDML");
if (isSEDML) {
List<VCDocument> docs = (List<VCDocument>) hashTable.get("docs");
List<DocumentWindowManager> windowManagers = new ArrayList<DocumentWindowManager>();
for (VCDocument doc : docs) {
DocumentWindowManager windowManager = createDocumentWindowManager(doc);
getMdiManager().createNewDocumentWindow(windowManager);
windowManagers.add(windowManager);
}
hashTable.put("managers", windowManagers);
hashTable.put("docs", docs);
} else {
VCDocument doc = (VCDocument) hashTable.get("doc");
DocumentWindowManager windowManager = null;
if (inNewWindow) {
windowManager = createDocumentWindowManager(doc);
// request was to create a new top-level window with this doc
getMdiManager().createNewDocumentWindow(windowManager);
} else {
// request was to replace the document in an existing window
windowManager = (DocumentWindowManager) requester;
getMdiManager().setCanonicalTitle(requester.getManagerID());
windowManager.resetDocument(doc);
}
hashTable.put(WIN_MGR_KEY, windowManager);
hashTable.put("doc", doc);
}
}
} catch (Exception ex) {
ex.printStackTrace();
// TODO: check why getMdiManager().createNewDocumentWindow(windowManager) fails sometimes
} finally {
if (!inNewWindow) {
getMdiManager().unBlockWindow(requester.getManagerID());
}
bOpening = false;
}
}
};
AsynchClientTask task3 = new AsynchClientTask("Special Layout", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
boolean isSEDML = (boolean) hashTable.get("isSEDML");
if (externalDocInfo.isBioModelsNet() || externalDocInfo.isFromXmlFile() || !isSEDML) {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
if (windowManager instanceof BioModelWindowManager) {
((BioModelWindowManager) windowManager).specialLayout();
}
}
if (isSEDML) {
List<DocumentWindowManager> windowManagers = (List<DocumentWindowManager>) hashTable.get("managers");
if (windowManagers != null) {
for (DocumentWindowManager manager : windowManagers) {
((BioModelWindowManager) manager).specialLayout();
}
}
}
}
}
};
AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
AsynchClientTask task6 = new AsynchClientTask("Renaming, please wait...", // TASKTYPE_NONSWING_BLOCKING
AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, // TASKTYPE_NONSWING_BLOCKING
false, // TASKTYPE_NONSWING_BLOCKING
false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
VCDocument doc = (VCDocument) hashTable.get("doc");
if (!(doc instanceof BioModel)) {
return;
}
boolean isBMDB = (boolean) hashTable.get("isBMDB");
if (documentInfo instanceof ExternalDocInfo) {
if (isBMDB) {
idToNameConversion(doc);
}
}
if (isBMDB) {
BioModel bioModel = (BioModel) doc;
SimulationContext simulationContext = bioModel.getSimulationContext(0);
simulationContext.setName(BMDB_DEFAULT_APPLICATION);
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
MathDescription mathDesc = null;
try {
mathDesc = mathMapping.getMathDescription(callback);
simulationContext.setMathDescription(mathDesc);
Simulation sim = new Simulation(mathDesc);
sim.setName(simulationContext.getBioModel().getFreeSimulationName());
simulationContext.addSimulation(sim);
bioModel.refreshDependencies();
} catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
e1.printStackTrace();
}
hashTable.put("doc", doc);
}
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task6, task2, task3, task4 }, false);
}
use of cbit.vcell.math.MathDescription in project vcell by virtualcell.
the class OutputFunctionsListTableModel method propertyChange.
/**
* This method gets called when a bound property is changed.
* @param evt A PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
public void propertyChange(java.beans.PropertyChangeEvent evt) {
OutputFunctionContext fc = getOutputFunctionContext();
SimulationOwner so = null;
if (fc != null) {
so = fc.getSimulationOwner();
}
if (evt.getSource() == fc && evt.getPropertyName().equals(OutputFunctionContext.PROPERTY_OUTPUT_FUNCTIONS)) {
setData(outputFunctionContext.getOutputFunctionsList());
}
if (evt.getSource() instanceof SimulationContext && evt.getSource() == so && evt.getPropertyName().equals(Model.PROPERTY_NAME_MODEL_ENTITY_NAME)) {
SimulationContext simulationContext = (SimulationContext) so;
if (fc.getOutputFunctionsList() == null || fc.getOutputFunctionsList().isEmpty()) {
return;
}
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
//
// WARNING: this should NOT be used under any circumstance for batch renaming
// MathDescription, MathMapping, expressions are NOT thread safe
//
AsynchClientTask task0 = new AsynchClientTask("Renaming Functions", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
MathDescription mathDesc = null;
try {
mathDesc = mathMapping.getMathDescription(callback);
} catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
e1.printStackTrace();
}
String oldName = (String) evt.getOldValue();
String newName = (String) evt.getNewValue();
ArrayList<AnnotatedFunction> afList = fc.getOutputFunctionsList();
List<Expression> changedExpressions = new ArrayList<>();
for (AnnotatedFunction af : afList) {
if (af == null) {
continue;
}
Expression exp = af.getExpression();
if (exp == null || exp.getSymbols() == null || exp.getSymbols().length == 0) {
continue;
}
String errMsg = "Failed to rename symbol '" + oldName + "' with '" + newName + "' in the Expression of Function '" + af.getName() + "'.";
for (String symbol : exp.getSymbols()) {
if (symbol.contentEquals(oldName)) {
try {
exp.substituteInPlace(new Expression(oldName), new Expression(newName));
changedExpressions.add(exp);
} catch (ExpressionException e) {
e.printStackTrace();
throw new RuntimeException(errMsg);
}
}
}
}
if (changedExpressions.size() > 0) {
try {
simulationContext.setMathDescription(mathDesc);
for (Expression exp : changedExpressions) {
exp.bindExpression(outputFunctionContext);
}
} catch (ExpressionException | PropertyVetoException e) {
e.printStackTrace();
}
}
}
};
ClientTaskDispatcher.dispatch(ownerTable, hashTable, new AsynchClientTask[] { task0 }, false);
}
if (evt.getPropertyName().equals(GeometryOwner.PROPERTY_NAME_GEOMETRY)) {
Geometry oldGeometry = (Geometry) evt.getOldValue();
Geometry newGeometry = (Geometry) evt.getNewValue();
// changing from ode to pde
if (oldGeometry.getDimension() == 0 && newGeometry.getDimension() > 0) {
fireTableStructureChanged();
setData(getOutputFunctionContext().getOutputFunctionsList());
}
}
}
use of cbit.vcell.math.MathDescription in project vcell by virtualcell.
the class OutputFunctionsPanel method getPossibleGeometryClassesAndVariableTypes.
private ArrayList<Object> getPossibleGeometryClassesAndVariableTypes(Expression expr) throws ExpressionException, InconsistentDomainException {
SimulationOwner simulationOwner = getSimulationWorkspace().getSimulationOwner();
MathDescription mathDescription = simulationOwner.getMathDescription();
boolean bSpatial = simulationOwner.getGeometry().getDimension() > 0;
if (!bSpatial) {
return null;
}
// making sure that output function is not direct function of constant.
expr.bindExpression(outputFunctionContext);
// new expression itself to be function of constant.
try {
expr = MathUtilities.substituteFunctions(expr, outputFunctionContext).flatten();
} catch (ExpressionBindingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
expr = MathUtilities.substituteFunctions(expr, outputFunctionContext, true).flatten();
}
String[] symbols = expr.getSymbols();
// using bit operation to determine whether geometry classes for symbols in expression are vol, membrane or both. 01 => vol; 10 => membrane; 11 => both
int gatherFlag = 0;
Set<GeometryClass> geomClassSet = new HashSet<GeometryClass>();
ArrayList<Object> objectsList = new ArrayList<Object>();
boolean bHasVariable = false;
VariableType[] varTypes = null;
if (symbols != null && symbols.length > 0) {
// making sure that new expression is defined in the same domain
varTypes = new VariableType[symbols.length];
for (int i = 0; i < symbols.length; i++) {
if (ReservedMathSymbolEntries.getReservedVariableEntry(symbols[i]) != null) {
varTypes[i] = VariableType.VOLUME;
} else {
Variable var = mathDescription.getVariable(symbols[i]);
if (var == null) {
var = mathDescription.getPostProcessingBlock().getDataGenerator(symbols[i]);
}
varTypes[i] = VariableType.getVariableType(var);
bHasVariable = true;
if (var.getDomain() != null) {
GeometryClass varGeoClass = simulationOwner.getGeometry().getGeometryClass(var.getDomain().getName());
geomClassSet.add(varGeoClass);
if (varGeoClass instanceof SubVolume) {
gatherFlag |= 1;
} else if (varGeoClass instanceof SurfaceClass) {
gatherFlag |= 2;
}
}
if (varTypes[i].equals(VariableType.POSTPROCESSING)) {
gatherFlag |= 4;
}
}
}
}
if (gatherFlag > 4) {
throw new RuntimeException("cannot mix post processing variables with membrane or volume variables");
}
int numGeomClasses = geomClassSet.size();
if (numGeomClasses == 0) {
if (bHasVariable) {
// if there are no variables (like built in function, vcRegionArea), check with flattened expression to find out the variable type of the new expression
Function flattenedFunction = new Function(getFunctionNameTextField().getText(), expr, null);
flattenedFunction.bind(outputFunctionContext);
VariableType newVarType = SimulationSymbolTable.getFunctionVariableType(flattenedFunction, simulationOwner.getMathDescription(), symbols, varTypes, bSpatial);
objectsList.add(newVarType);
} else {
objectsList.add(VariableType.VOLUME);
objectsList.add(VariableType.MEMBRANE);
}
} else if (numGeomClasses == 1) {
objectsList.add(geomClassSet.iterator().next());
if (gatherFlag == 1) {
objectsList.add(VariableType.MEMBRANE);
}
} else if (gatherFlag == 1) {
// all volumes
if (numGeomClasses == 2) {
// all subvolumes, if there are only 2, check for adjacency.
GeometryClass[] geomClassesArray = geomClassSet.toArray(new GeometryClass[0]);
SurfaceClass sc = simulationOwner.getGeometry().getGeometrySurfaceDescription().getSurfaceClass((SubVolume) geomClassesArray[0], (SubVolume) geomClassesArray[1]);
if (sc != null) {
objectsList.add(sc);
}
}
objectsList.add(VariableType.VOLUME);
} else if (gatherFlag == 2) {
// all membranes
objectsList.add(VariableType.MEMBRANE);
} else if (gatherFlag == 3) {
// mixed - both vols and membranes
// add only membranes?
objectsList.add(VariableType.MEMBRANE);
}
return objectsList;
}
Aggregations