use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class ModelTest method getExample_GlobalParams.
/**
* This method was created by a SmartGuide.
*/
public static Model getExample_GlobalParams() throws Exception {
double A_init = 10.0;
double B_init = 20.0;
double C_init = 30.0;
double D_init = 40.0;
double A_diff = 11.0;
double B_diff = 22.0;
double C_diff = 33.0;
double D_diff = 44.0;
Model model = new Model("model1");
model.addSpecies(new Species("A", "A"));
Species A = model.getSpecies("A");
model.addSpecies(new Species("B", "B"));
Species B = model.getSpecies("B");
model.addSpecies(new Species("C", "C"));
Species C = model.getSpecies("C");
model.addSpecies(new Species("D", "D"));
Species D = model.getSpecies("D");
model.addFeature("Cytosol");
Feature cytosol = (Feature) model.getStructure("Cytosol");
model.addSpeciesContext(A, cytosol);
SpeciesContext A_cyt = model.getSpeciesContext(A, cytosol);
model.addSpeciesContext(B, cytosol);
SpeciesContext B_cyt = model.getSpeciesContext(B, cytosol);
model.addSpeciesContext(C, cytosol);
SpeciesContext C_cyt = model.getSpeciesContext(C, cytosol);
model.addSpeciesContext(D, cytosol);
SpeciesContext D_cyt = model.getSpeciesContext(D, cytosol);
// add global parameters to the model
VCUnitDefinition volumeReactionRateUnit = model.getUnitSystem().getVolumeReactionRateUnit();
ModelParameter gp1 = model.new ModelParameter("Kon_1", new Expression(3.0), Model.ROLE_UserDefined, volumeReactionRateUnit);
gp1.setDescription("first global parameter");
model.addModelParameter(gp1);
ModelParameter gp2 = model.new ModelParameter("Koff_1", new Expression(4.0), Model.ROLE_UserDefined, volumeReactionRateUnit);
gp2.setDescription("second global parameter");
model.addModelParameter(gp2);
SimpleReaction sr;
//
// CYTOSOL REACTIONS
//
double K1 = 1.0;
double K2 = 2.0;
double K3 = 3.0;
double K4 = 4.0;
sr = new SimpleReaction(model, cytosol, "SIMPLE_REACTION_ABC", true);
sr.setModel(model);
sr.addReactant(A_cyt, 1);
sr.addReactant(B_cyt, 1);
sr.addProduct(C_cyt, 1);
MassActionKinetics massAct = new MassActionKinetics(sr);
massAct.setParameterValue(massAct.getForwardRateParameter(), new Expression(K1));
massAct.setParameterValue(massAct.getReverseRateParameter(), new Expression(K2));
massAct.renameParameter(massAct.getForwardRateParameter().getName(), "K1");
massAct.renameParameter(massAct.getReverseRateParameter().getName(), "K2");
sr.setKinetics(massAct);
model.addReactionStep(sr);
sr = new SimpleReaction(model, cytosol, "SIMPLE_REACION_CDA", true);
sr.setModel(model);
sr.addReactant(C_cyt, 1);
sr.addReactant(D_cyt, 1);
sr.addProduct(A_cyt, 1);
massAct = new MassActionKinetics(sr);
massAct.setParameterValue(massAct.getForwardRateParameter(), new Expression(K3));
massAct.setParameterValue(massAct.getReverseRateParameter(), new Expression(K4));
massAct.renameParameter(massAct.getForwardRateParameter().getName(), "K3");
massAct.renameParameter(massAct.getReverseRateParameter().getName(), "K4");
sr.setKinetics(massAct);
model.addReactionStep(sr);
Diagram diagram = model.getDiagram(cytosol);
String diagramFile = " { " + " SpeciesContextSpec A_cyt 100 100 " + " SpeciesContextSpec B_cyt 50 200 " + " SpeciesContextSpec C_cyt 200 200 " + " SpeciesContextSpec D_cyt 200 50 " + " SimpleReaction SIMPLE_REACTION_ABC 75 150 " + " SimpleReaction SIMPLE_REACION_CDA 200 125 " + "} ";
org.vcell.util.CommentStringTokenizer st = new org.vcell.util.CommentStringTokenizer(diagramFile);
diagram.fromTokens(st);
return model;
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class ModelTest method getExampleForFluorescenceIndicatorProtocol.
/**
* This method was created by a SmartGuide.
*/
public static Model getExampleForFluorescenceIndicatorProtocol() throws Exception {
double A_init = 10.0;
double B_init = 20.0;
double C_init = 30.0;
double D_init = 40.0;
double E_init = 35.0;
double I_init = 50.0;
double A_diff = 11.0;
double B_diff = 22.0;
double C_diff = 33.0;
double D_diff = 44.0;
double E_diff = 55.0;
double I_diff = 66.0;
Model model = new Model("model1");
model.addSpecies(new Species("A", "A"));
Species A = model.getSpecies("A");
model.addSpecies(new Species("B", "B"));
Species B = model.getSpecies("B");
model.addSpecies(new Species("C", "C"));
Species C = model.getSpecies("C");
model.addSpecies(new Species("D", "D"));
Species D = model.getSpecies("D");
model.addSpecies(new Species("E", "E"));
Species E = model.getSpecies("E");
model.addSpecies(new Species("I", "I"));
Species I = model.getSpecies("I");
model.addFeature("Cytosol");
Feature cytosol = (Feature) model.getStructure("Cytosol");
model.addSpeciesContext(A, cytosol);
SpeciesContext A_cyt = model.getSpeciesContext(A, cytosol);
// A_cyt.setInitialValue(A_init);
// A_cyt.setDiffusionRate(A_diff);
model.addSpeciesContext(B, cytosol);
SpeciesContext B_cyt = model.getSpeciesContext(B, cytosol);
// B_cyt.setInitialValue(B_init);
// B_cyt.setDiffusionRate(B_diff);
model.addSpeciesContext(C, cytosol);
SpeciesContext C_cyt = model.getSpeciesContext(C, cytosol);
// C_cyt.setInitialValue(C_init);
// C_cyt.setDiffusionRate(C_diff);
model.addSpeciesContext(D, cytosol);
SpeciesContext D_cyt = model.getSpeciesContext(D, cytosol);
// D_cyt.setInitialValue(D_init);
// D_cyt.setDiffusionRate(D_diff);
model.addSpeciesContext(E, cytosol);
SpeciesContext E_cyt = model.getSpeciesContext(E, cytosol);
// E_cyt.setInitialValue(E_init);
// E_cyt.setDiffusionRate(E_diff);
model.addSpeciesContext(I, cytosol);
SpeciesContext I_cyt = model.getSpeciesContext(I, cytosol);
// I_cyt.setInitialValue(I_init);
// I_cyt.setDiffusionRate(I_diff);
SimpleReaction sr;
//
// CYTOSOL REACTIONS
//
double K1 = 1.0;
double K2 = 2.0;
double K3 = 3.0;
double K4 = 4.0;
sr = new SimpleReaction(model, cytosol, "SIMPLE_REACTION_ABC", true);
sr.addReactant(A_cyt, 1);
sr.addReactant(B_cyt, 1);
sr.addProduct(C_cyt, 1);
MassActionKinetics massAct = new MassActionKinetics(sr);
massAct.setParameterValue(massAct.getForwardRateParameter(), new Expression(K1));
massAct.setParameterValue(massAct.getReverseRateParameter(), new Expression(K2));
massAct.renameParameter(massAct.getForwardRateParameter().getName(), "K1");
massAct.renameParameter(massAct.getReverseRateParameter().getName(), "K2");
sr.setKinetics(massAct);
model.addReactionStep(sr);
sr = new SimpleReaction(model, cytosol, "SIMPLE_REACION_CDE", true);
sr.addReactant(C_cyt, 1);
sr.addReactant(D_cyt, 1);
sr.addProduct(E_cyt, 1);
massAct = new MassActionKinetics(sr);
massAct.setParameterValue(massAct.getForwardRateParameter(), new Expression(K3));
massAct.setParameterValue(massAct.getReverseRateParameter(), new Expression(K4));
massAct.renameParameter(massAct.getForwardRateParameter().getName(), "K3");
massAct.renameParameter(massAct.getReverseRateParameter().getName(), "K4");
sr.setKinetics(massAct);
model.addReactionStep(sr);
return model;
}
use of cbit.vcell.parser.Expression 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_MODEL = "SedMLModel";
final String BNG_UNIT_SYSTEM = "bngUnitSystem";
/* 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);
// 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());
hashTable.put(SEDML_MODEL, sedml);
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));
SEDMLDocument doc = ac.getSedmlDocument();
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());
}
AbstractTask chosenTask = SEDMLChooserPanel.chooseTask(sedml, requester.getComponent(), file.getName());
hashTable.put(SEDML_MODEL, sedml);
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;
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);
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} 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, mathmodel or geometry.
Element modelElement = childElementList.get(0);
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);
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)) {
doc = XmlHelper.sedmlToBioModel(transLogger, externalDocInfo, (SedML) hashTable.get(SEDML_MODEL), (AbstractTask) hashTable.get(SEDML_TASK));
} 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) {
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("doc", doc);
}
};
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) {
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);
// if (windowManager instanceof BioModelWindowManager) {
// ((BioModelWindowManager)windowManager).preloadApps();
// }
} 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);
}
} 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 {
// TODO Auto-generated method stub
if (documentInfo instanceof ExternalDocInfo) {
ExternalDocInfo externalDocInfo = (ExternalDocInfo) documentInfo;
if (externalDocInfo.isBioModelsNet()) {
DocumentWindowManager windowManager = (DocumentWindowManager) hashTable.get(WIN_MGR_KEY);
if (windowManager instanceof BioModelWindowManager) {
((BioModelWindowManager) windowManager).specialLayout();
}
}
}
}
};
AsynchClientTask task4 = new AsynchClientTaskFunction(ClientRequestManager::setWindowFocus, "Set window focus", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false, false);
ClientTaskDispatcher.dispatch(requester.getComponent(), hashTable, new AsynchClientTask[] { task0, task1, task2, task3, task4 }, false);
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class XmlReader method getSpeciesContextSpecs.
/**
* This method returns a SpeciesContextSpec object from a XML representation.
* Creation date: (4/26/2001 4:14:01 PM)
* @return cbit.vcell.mapping.SpeciesContextSpec
* @param param org.jdom.Element
*/
private void getSpeciesContextSpecs(List<Element> scsChildren, ReactionContext rxnContext, Model model) throws XmlParseException {
for (int i = 0; i < scsChildren.size(); i++) {
Element scsElement = scsChildren.get(i);
SpeciesContextSpec specspec = null;
// Get Atributes
String speccontname = unMangle(scsElement.getAttributeValue(XMLTags.SpeciesContextRefAttrTag));
boolean constant = Boolean.valueOf(scsElement.getAttributeValue(XMLTags.ForceConstantAttrTag)).booleanValue();
// boolean enabledif = Boolean.valueOf(scsElement.getAttributeValue(XMLTags.EnableDiffusionAttrTag)).booleanValue();
String spatialStr = scsElement.getAttributeValue(XMLTags.SpatialAttrTag);
Boolean spatial = null;
if (spatialStr != null) {
spatial = Boolean.valueOf(spatialStr);
}
String bWellMixedStr = scsElement.getAttributeValue(XMLTags.WellMixedAttrTag);
Boolean bWellMixed = null;
if (bWellMixedStr != null) {
bWellMixed = Boolean.valueOf(bWellMixedStr);
}
String bForceContinuousStr = scsElement.getAttributeValue(XMLTags.ForceContinuousAttrTag);
Boolean bForceContinuous = null;
if (bForceContinuousStr != null) {
bForceContinuous = Boolean.valueOf(bForceContinuousStr);
}
// Retrieve reference
SpeciesContext specref = model.getSpeciesContext(speccontname);
if (specref == null) {
throw new XmlParseException("The SpeciesContext " + speccontname + " refrence could not be resolved!");
}
// get SpeciesContextSpec from reactionContext & specRef
specspec = rxnContext.getSpeciesContextSpec(specref);
// set attributes
specspec.setConstant(constant);
// }
if (spatial != null) {
specspec.setWellMixed(!spatial);
}
if (bWellMixed != null) {
specspec.setWellMixed(bWellMixed);
}
if (bForceContinuous != null) {
specspec.setForceContinuous(bForceContinuous);
}
// set expressions
// Initial
String tempCon = scsElement.getChildText(XMLTags.InitialConcentrationTag, vcNamespace);
String tempAmt = scsElement.getChildText(XMLTags.InitialAmountTag, vcNamespace);
String temp = scsElement.getChildText(XMLTags.InitialTag, vcNamespace);
try {
if (// old model
temp != null) {
Expression expression = unMangleExpression(temp);
specspec.getInitialConcentrationParameter().setExpression(expression);
specspec.getInitialCountParameter().setExpression(null);
} else // new model
{
if (// use concentration as initial condition
tempCon != null) {
Expression expression = unMangleExpression(tempCon);
specspec.getInitialConcentrationParameter().setExpression(expression);
specspec.getInitialCountParameter().setExpression(null);
} else if (// use number of particles as initial condition
tempAmt != null) {
Expression expression = unMangleExpression(tempAmt);
specspec.getInitialCountParameter().setExpression(expression);
specspec.getInitialConcentrationParameter().setExpression(null);
} else {
throw new XmlParseException("Unrecognizable initial condition when parsing VCML file.");
}
}
// Expression expression = unMangleExpression(temp);
// specspec.getInitialConditionParameter().setExpression(expression);
} catch (ExpressionException e) {
e.printStackTrace();
throw new XmlParseException("An expressionException was fired when setting the InitilaconditionExpression " + temp + ", for a SpeciesContextSpec!", e);
}
// diffusion (if there is no diffusion information skip it)
Element xmlDiffusionElement = scsElement.getChild(XMLTags.DiffusionTag, vcNamespace);
if (xmlDiffusionElement != null) {
temp = xmlDiffusionElement.getText();
try {
Expression expression = unMangleExpression(temp);
specspec.getDiffusionParameter().setExpression(expression);
} catch (ExpressionException e) {
e.printStackTrace();
throw new XmlParseException("An ExpressionException was fired when setting the diffusionExpression " + temp + " to a SpeciesContextSpec!", e);
}
}
// Get Boundaries if any
Element tempElement = scsElement.getChild(XMLTags.BoundariesTag, vcNamespace);
if (tempElement != null) {
try {
// Xm
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueXm);
if (temp != null) {
specspec.getBoundaryXmParameter().setExpression(unMangleExpression(temp));
}
// Xp
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueXp);
if (temp != null) {
specspec.getBoundaryXpParameter().setExpression(unMangleExpression(temp));
}
// Ym
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueYm);
if (temp != null) {
specspec.getBoundaryYmParameter().setExpression(unMangleExpression(temp));
}
// Yp
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueYp);
if (temp != null) {
specspec.getBoundaryYpParameter().setExpression(unMangleExpression(temp));
}
// Zm
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueZm);
if (temp != null) {
specspec.getBoundaryZmParameter().setExpression(unMangleExpression(temp));
}
// Zp
temp = tempElement.getAttributeValue(XMLTags.BoundaryAttrValueZp);
if (temp != null) {
specspec.getBoundaryZpParameter().setExpression(unMangleExpression(temp));
}
} catch (ExpressionException e) {
e.printStackTrace();
throw new XmlParseException("An ExpressionException was fired when Setting the boundary Expression: " + unMangle(temp), e);
}
}
// Get Velocities if any
Element velocityE = scsElement.getChild(XMLTags.VelocityTag, vcNamespace);
if (velocityE != null) {
String tempStr = null;
boolean dummyVel = true;
try {
tempStr = velocityE.getAttributeValue(XMLTags.XAttrTag);
if (tempStr != null) {
// all velocity dimensions are optional.
specspec.getVelocityXParameter().setExpression(unMangleExpression(tempStr));
if (dummyVel) {
dummyVel = false;
}
}
tempStr = velocityE.getAttributeValue(XMLTags.YAttrTag);
if (tempStr != null) {
specspec.getVelocityYParameter().setExpression(unMangleExpression(tempStr));
if (dummyVel) {
dummyVel = false;
}
}
tempStr = velocityE.getAttributeValue(XMLTags.ZAttrTag);
if (tempStr != null) {
specspec.getVelocityZParameter().setExpression(unMangleExpression(tempStr));
if (dummyVel) {
dummyVel = false;
}
}
} catch (ExpressionException e) {
e.printStackTrace();
throw new XmlParseException("Error setting Velocity parameter for '" + specspec.getSpeciesContext().getName(), e);
}
if (dummyVel) {
throw new XmlParseException("Void Velocity element found under PDE for: " + specspec.getSpeciesContext().getName());
}
}
}
}
use of cbit.vcell.parser.Expression in project vcell by virtualcell.
the class XmlReader method getBioEvents.
public BioEvent[] getBioEvents(SimulationContext simContext, Element bioEventsElement) throws XmlParseException {
Iterator<Element> bioEventsIterator = bioEventsElement.getChildren(XMLTags.BioEventTag, vcNamespace).iterator();
Vector<BioEvent> bioEventsVector = new Vector<BioEvent>();
while (bioEventsIterator.hasNext()) {
Element bEventElement = (Element) bioEventsIterator.next();
BioEvent newBioEvent = null;
String name = unMangle(bEventElement.getAttributeValue(XMLTags.NameAttrTag));
Element triggerElement = bEventElement.getChild(XMLTags.TriggerTag, vcNamespace);
if (triggerElement != null && triggerElement.getText().length() > 0) {
//
// read legacy VCell 5.3 style trigger and delay elements
//
// <Trigger>(t>3.0)</Trigger>
// <Delay UseValuesFromTriggerTime="true">3.0</Delay> [optional]
//
Expression triggerExpression = unMangleExpression(triggerElement.getText());
// read <Delay>
Expression delayDurationExpression = null;
boolean useValuesFromTriggerTime = true;
Element delayElement = bEventElement.getChild(XMLTags.DelayTag, vcNamespace);
if (delayElement != null) {
useValuesFromTriggerTime = Boolean.valueOf(delayElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag)).booleanValue();
delayDurationExpression = unMangleExpression((delayElement.getText()));
}
newBioEvent = new BioEvent(name, TriggerType.GeneralTrigger, useValuesFromTriggerTime, simContext);
try {
newBioEvent.setParameterValue(BioEventParameterType.GeneralTriggerFunction, triggerExpression);
if (delayDurationExpression != null) {
newBioEvent.setParameterValue(BioEventParameterType.TriggerDelay, delayDurationExpression);
}
} catch (ExpressionBindingException | PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("failed to read trigger or delay expressions in bioEvent " + name + ": " + e.getMessage(), e);
}
} else if (triggerElement != null && triggerElement.getText().length() == 0) {
//
// read legacy first-pass VCell 5.4 style trigger and delay elements
//
// <Trigger>
// <TriggerParameters triggerClass="TriggerGeneral">
// (t > 500.0)
// </TriggerParameters>
// </Trigger>
// <Delay UseValuesFromTriggerTime="true">3.0</Delay> [optional]
//
final String TriggerParametersTag = "TriggerParameters";
final String TriggerClassAttrTag = "triggerClass";
final String TriggerClassAttrValue_TriggerGeneral = "TriggerGeneral";
Element triggerParametersElement = triggerElement.getChild(TriggerParametersTag, vcNamespace);
Expression triggerExpression = null;
String triggerClass = triggerParametersElement.getAttributeValue(TriggerClassAttrTag);
if (triggerClass.equals(TriggerClassAttrValue_TriggerGeneral)) {
triggerExpression = unMangleExpression(triggerParametersElement.getText());
} else {
// not general trigger (just make it never happen, user will have to edit "t > -1")
triggerExpression = Expression.relational(">", new Expression(simContext.getModel().getTIME(), simContext.getModel().getNameScope()), new Expression(-1.0));
}
// read <Delay>
Expression delayDurationExpression = null;
boolean useValuesFromTriggerTime = true;
Element delayElement = bEventElement.getChild(XMLTags.DelayTag, vcNamespace);
if (delayElement != null) {
useValuesFromTriggerTime = Boolean.valueOf(delayElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag)).booleanValue();
delayDurationExpression = unMangleExpression((delayElement.getText()));
}
newBioEvent = new BioEvent(name, TriggerType.GeneralTrigger, useValuesFromTriggerTime, simContext);
try {
newBioEvent.setParameterValue(BioEventParameterType.GeneralTriggerFunction, triggerExpression);
if (delayDurationExpression != null) {
newBioEvent.setParameterValue(BioEventParameterType.TriggerDelay, delayDurationExpression);
}
} catch (ExpressionBindingException | PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("failed to read trigger or delay expressions in bioEvent " + name + ": " + e.getMessage(), e);
}
} else {
//
// VCell 5.4 style bioevent parameters
//
//
TriggerType triggerType = TriggerType.fromXmlName(bEventElement.getAttributeValue(XMLTags.BioEventTriggerTypeAttrTag));
boolean bUseValuesFromTriggerTime = Boolean.parseBoolean(bEventElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag));
newBioEvent = new BioEvent(name, triggerType, bUseValuesFromTriggerTime, simContext);
Iterator<Element> paramElementIter = bEventElement.getChildren(XMLTags.ParameterTag, vcNamespace).iterator();
ArrayList<LocalParameter> parameters = new ArrayList<LocalParameter>();
boolean bHasGeneralTriggerParam = false;
while (paramElementIter.hasNext()) {
Element paramElement = paramElementIter.next();
// Get parameter attributes
String paramName = paramElement.getAttributeValue(XMLTags.NameAttrTag);
Expression exp = unMangleExpression(paramElement.getText());
String roleStr = paramElement.getAttributeValue(XMLTags.ParamRoleAttrTag);
BioEventParameterType parameterType = BioEventParameterType.fromRoleXmlName(roleStr);
if (parameterType == BioEventParameterType.GeneralTriggerFunction) {
bHasGeneralTriggerParam = true;
}
VCUnitDefinition unit = simContext.getModel().getUnitSystem().getInstance_TBD();
String unitSymbol = paramElement.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
if (unitSymbol != null) {
unit = simContext.getModel().getUnitSystem().getInstance(unitSymbol);
}
parameters.add(newBioEvent.createNewParameter(paramName, parameterType, exp, unit));
}
if (!bHasGeneralTriggerParam) {
parameters.add(newBioEvent.createNewParameter(BioEventParameterType.GeneralTriggerFunction.getDefaultName(), BioEventParameterType.GeneralTriggerFunction, // computed as needed
null, simContext.getModel().getUnitSystem().getInstance_DIMENSIONLESS()));
}
try {
newBioEvent.setParameters(parameters.toArray(new LocalParameter[0]));
} catch (PropertyVetoException | ExpressionBindingException e) {
e.printStackTrace();
throw new XmlParseException("failed to read parameters in bioEvent " + name + ": " + e.getMessage(), e);
}
}
ArrayList<BioEvent.EventAssignment> eventAssignmentList = new ArrayList<BioEvent.EventAssignment>();
Iterator<Element> iter = bEventElement.getChildren(XMLTags.EventAssignmentTag, vcNamespace).iterator();
while (iter.hasNext()) {
Element eventAssignmentElement = iter.next();
try {
String varname = eventAssignmentElement.getAttributeValue(XMLTags.EventAssignmentVariableAttrTag);
Expression assignExp = unMangleExpression(eventAssignmentElement.getText());
SymbolTableEntry target = simContext.getEntry(varname);
BioEvent.EventAssignment eventAssignment = newBioEvent.new EventAssignment(target, assignExp);
eventAssignmentList.add(eventAssignment);
} catch (ExpressionException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
}
try {
newBioEvent.setEventAssignmentsList(eventAssignmentList);
} catch (PropertyVetoException e1) {
e1.printStackTrace(System.out);
throw new XmlParseException(e1);
}
try {
newBioEvent.bind();
} catch (ExpressionBindingException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
bioEventsVector.add(newBioEvent);
}
return ((BioEvent[]) BeanUtils.getArray(bioEventsVector, BioEvent.class));
}
Aggregations