use of org.vcell.model.bngl.ASTModel 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 org.vcell.model.bngl.ASTModel in project vcell by virtualcell.
the class VCMLHandler method convertVcmlToVcDocument.
public static VCDocument convertVcmlToVcDocument(File vcmlFilePath) throws Exception {
ExternalDocInfo documentInfo = new ExternalDocInfo(vcmlFilePath, true);
File file = documentInfo.getFile();
if (file != null && !file.getName().isEmpty() && file.getName().endsWith("bngl")) {
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitSystem.BngUnitOrigin.DEFAULT);
String fileText;
try {
fileText = BeanUtils.readBytesFromFile(file, null);
} catch (IOException e1) {
e1.printStackTrace();
return null;
}
Reader reader = documentInfo.getReader();
boolean bException = true;
while (bException) {
try {
BioModel bioModel = createDefaultBioModelDocument(bngUnitSystem);
SimulationContext ruleBasedSimContext = bioModel.addNewSimulationContext("temp NFSim app", SimulationContext.Application.RULE_BASED_STOCHASTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(ruleBasedSimContext);
Model.RbmModelContainer rbmModelContainer = bioModel.getModel().getRbmModelContainer();
RbmUtils.reactionRuleLabelIndex = 0;
RbmUtils.reactionRuleNames.clear();
ASTModel astModel = RbmUtils.importBnglFile(reader);
if (astModel.hasUnitSystem()) {
bngUnitSystem = astModel.getUnitSystem();
}
if (astModel.hasCompartments()) {
Structure struct = bioModel.getModel().getStructure(0);
if (struct != null) {
bioModel.getModel().removeStructure(struct);
}
}
RbmUtils.BnglObjectConstructionVisitor constructionVisitor = null;
if (!astModel.hasMolecularDefinitions()) {
System.out.println("Molecular Definition Block missing.");
constructionVisitor = new RbmUtils.BnglObjectConstructionVisitor(bioModel.getModel(), appList, bngUnitSystem, false);
} else {
constructionVisitor = new RbmUtils.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);
// inserting <potentially> corrected DocumentInfo
fileText = panel.getText();
}
}
}
VCDocument doc = null;
XMLSource xmlSource = documentInfo.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();
// TODO: Check for all child elements
// 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);
}
return doc;
}
use of org.vcell.model.bngl.ASTModel in project vcell by virtualcell.
the class BNGExecutorServiceMultipass method preprocessInput.
// parse the compartmental bngl file and produce the "trick"
// where each molecule has an extra Site with the compartments as possible States
// a reserved name will be used for this Site
//
private String preprocessInput(String cBngInputString) throws ParseException, PropertyVetoException, ExpressionBindingException {
// take the cBNGL file (as string), parse it to recover the rules (we'll need them later)
// and create the bngl string with the extra, fake site for the compartments
BioModel bioModel = new BioModel(null);
bioModel.setName("BngBioModel");
model = new Model("model");
bioModel.setModel(model);
model.createFeature();
simContext = bioModel.addNewSimulationContext("BioNetGen app", SimulationContext.Application.NETWORK_DETERMINISTIC);
List<SimulationContext> appList = new ArrayList<SimulationContext>();
appList.add(simContext);
// set convention for initial conditions in generated application for seed species (concentration or count)
BngUnitSystem bngUnitSystem = new BngUnitSystem(BngUnitOrigin.DEFAULT);
InputStream is = new ByteArrayInputStream(cBngInputString.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
ASTModel astModel = RbmUtils.importBnglFile(br);
if (astModel.hasCompartments()) {
Structure struct = model.getStructure(0);
if (struct != null) {
try {
model.removeStructure(struct);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
}
BnglObjectConstructionVisitor constructionVisitor = null;
constructionVisitor = new BnglObjectConstructionVisitor(model, appList, bngUnitSystem, true);
astModel.jjtAccept(constructionVisitor, model.getRbmModelContainer());
int numCompartments = model.getStructures().length;
if (numCompartments == 0) {
throw new RuntimeException("No structure present in the bngl file.");
} else if (numCompartments == 1) {
// for single compartment we don't need the 'trick'
compartmentMode = CompartmentMode.hide;
} else {
compartmentMode = CompartmentMode.asSite;
}
// extract all polymer observables for special treatment at the end
for (RbmObservable oo : model.getRbmModelContainer().getObservableList()) {
if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthEqual) {
polymerEqualObservables.add(oo);
} else if (oo.getSequence() == RbmObservable.Sequence.PolymerLengthGreater) {
polymerGreaterObservables.add(oo);
}
}
for (RbmObservable oo : polymerEqualObservables) {
model.getRbmModelContainer().removeObservable(oo);
}
for (RbmObservable oo : polymerGreaterObservables) {
model.getRbmModelContainer().removeObservable(oo);
}
// replace all reversible rules with 2 direct rules
List<ReactionRule> newRRList = new ArrayList<>();
for (ReactionRule rr : model.getRbmModelContainer().getReactionRuleList()) {
if (rr.isReversible()) {
ReactionRule rr1 = ReactionRule.deriveDirectRule(rr);
newRRList.add(rr1);
ReactionRule rr2 = ReactionRule.deriveInverseRule(rr);
newRRList.add(rr2);
} else {
newRRList.add(rr);
}
model.getRbmModelContainer().removeReactionRule(rr);
}
// model.getRbmModelContainer().getReactionRuleList().clear();
model.getRbmModelContainer().setReactionRules(newRRList);
StringWriter bnglStringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(bnglStringWriter);
writer.println(RbmNetworkGenerator.BEGIN_MODEL);
writer.println();
// RbmNetworkGenerator.writeCompartments(writer, model, null);
RbmNetworkGenerator.writeParameters(writer, model.getRbmModelContainer(), false);
RbmNetworkGenerator.writeMolecularTypes(writer, model, compartmentMode);
RbmNetworkGenerator.writeSpeciesSortedAlphabetically(writer, model, simContext, compartmentMode);
RbmNetworkGenerator.writeObservables(writer, model.getRbmModelContainer(), compartmentMode);
// RbmNetworkGenerator.writeFunctions(writer, rbmModelContainer, ignoreFunctions);
RbmNetworkGenerator.writeReactions(writer, model.getRbmModelContainer(), null, false, compartmentMode);
writer.println(RbmNetworkGenerator.END_MODEL);
writer.println();
// we parse the real numbers from the bngl file provided by the caller, the nc in the simContext has the default ones
NetworkConstraints realNC = extractNetworkConstraints(cBngInputString);
String maxStoichiometry = extractMaxStoichiometry(cBngInputString);
simContext.getNetworkConstraints().setMaxMoleculesPerSpecies(realNC.getMaxMoleculesPerSpecies());
simContext.getNetworkConstraints().setMaxIteration(realNC.getMaxIteration());
ModelParameter speciesLimitParam = model.getModelParameter(NetworkConstraints.SPECIES_LIMIT_PARAMETER);
if (speciesLimitParam != null) {
// if it's not there we are already using the default
String s = speciesLimitParam.getExpression().infix();
// extract speciesLimit
simContext.getNetworkConstraints().setSpeciesLimit((int) Float.parseFloat(s));
}
ModelParameter reactionsLimitParam = model.getModelParameter(NetworkConstraints.REACTIONS_LIMIT_PARAMETER);
if (reactionsLimitParam != null) {
String r = reactionsLimitParam.getExpression().infix();
// extract reactionsLimit
simContext.getNetworkConstraints().setReactionsLimit((int) Float.parseFloat(r));
}
simContext.getNetworkConstraints().setTestConstraints(simContext.getNetworkConstraints().getMaxIteration(), simContext.getNetworkConstraints().getMaxMoleculesPerSpecies(), simContext.getNetworkConstraints().getSpeciesLimit(), simContext.getNetworkConstraints().getReactionsLimit(), // we don't need a testMaxStoichiometryMap (I guess)
null);
// RbmNetworkGenerator.generateNetworkEx(1, simContext.getNetworkConstraints().getMaxMoleculesPerSpecies(), false, writer, model.getRbmModelContainer(), simContext, NetworkGenerationRequirements.AllowTruncatedStandardTimeout);
generateNetworkLocal(1, simContext.getNetworkConstraints().getMaxMoleculesPerSpecies(), maxStoichiometry, writer);
String sInputString = bnglStringWriter.toString();
return sInputString;
}
use of org.vcell.model.bngl.ASTModel in project vcell by virtualcell.
the class RbmUtils method importBnglFile.
public static ASTModel importBnglFile(BufferedReader br) throws ParseException {
try {
// remove all the comments
reactionRuleNames.clear();
// just the prologue
StringBuilder sPrologBuilder = new StringBuilder();
StringBuilder sb = new StringBuilder();
ArrayList<BnglComment> comments = new ArrayList<BnglComment>();
int lineNumber = 0;
boolean bEscapingExpressionBegin = false;
boolean inProlog = true;
BnglLocation location = BnglLocation.OutsideBlock;
Set<String> compartments = new HashSet<>();
Map<String, String> anchors = new HashMap<>();
while (true) {
String line = br.readLine();
if (line == null) {
break;
}
line = line.trim();
line = applySyntaxCorrections(line);
// we capture all the prologue and insert in in the BioModel notes
if (line.startsWith("begin model") || line.startsWith("begin parameters")) {
inProlog = false;
}
if (inProlog == true) {
sPrologBuilder.append(line);
sPrologBuilder.append("\n");
sb.append("\n");
lineNumber++;
continue;
}
if (line.startsWith("version")) {
// we include the version in the prologue even if it shows up later in the code
sPrologBuilder.append(line);
sPrologBuilder.append("\n");
sb.append("\n");
lineNumber++;
continue;
}
if (line.length() == 0 || line.charAt(0) == '#') {
if (line.length() > 0 && line.charAt(0) == '#') {
BnglComment bc = new BnglComment("empty", lineNumber, location, line);
comments.add(bc);
}
sb.append("\n");
lineNumber++;
continue;
}
if (line.endsWith(":\\")) {
// we'll try to treat single line labels as comments
sb.append("\n");
lineNumber++;
continue;
} else if (line.endsWith("\\")) {
// concatenation with next line, we make one single continuous line
String line2 = br.readLine();
if (line2 == null) {
break;
}
line2 = line2.trim();
// we don't try to get too fancy here, we'll just assume there are 2 lines of code somewhere
// within a block and we simply concatenate them; if it's more than 2 we're out of luck
int concatenationTokenIndex = line.lastIndexOf("\\");
line = line.substring(0, concatenationTokenIndex);
if (line.endsWith(" ")) {
line = line + line2;
} else {
line = line + " " + line2;
}
// we add an empty line so that the total number of lines in the document won't change
sb.append("\n");
lineNumber++;
}
if (line.startsWith("end parameters") || line.startsWith("end seed species")) {
// TODO: position sensitive, do not move this 'if' down
bEscapingExpressionBegin = false;
}
// remove comments which follow some code
int commentIndex = line.indexOf('#');
if (commentIndex >= 0) {
BnglComment bc = new BnglComment("item ", lineNumber, location, line.substring(commentIndex));
comments.add(bc);
line = line.substring(0, commentIndex);
}
int labelEndIndex = line.indexOf(":");
if (labelEndIndex > 0 && line.substring(0, labelEndIndex).contains("@")) {
// this is not a label, is a compartment
;
} else {
if (labelEndIndex == -1) {
// there may still be a label present, just without the ":"
StringTokenizer st = new StringTokenizer(line);
String nextToken = st.nextToken();
String prefix = "";
if (nextToken.matches("[0-9]+")) {
// we transform them in proper labels by adding a letter prefix and the ":" suffix
if (location == BnglLocation.ReactionRule) {
// labels can't start with a number, so we add "r" as a prefix
prefix = "r";
} else {
// this just for consistency, below we'll actually remove all labels except the reaction rule ones
prefix = "l";
}
line = line.replaceFirst(nextToken, prefix + nextToken + ":");
labelEndIndex = line.indexOf(":");
}
}
// remove labels except for reaction rule labels
if (labelEndIndex >= 0 && line.length() > labelEndIndex) {
// we're certain they cannot be inside a comment since comments were removed already (above)
if (location == BnglLocation.ReactionRule) {
String reactionRuleName = line.substring(0, labelEndIndex);
if (reactionRuleNames.indexOf(reactionRuleName) != -1) {
// already in use
line = line.substring(labelEndIndex);
reactionRuleName = reactionRuleName + "_" + lineNumber;
line = reactionRuleName + line;
}
reactionRuleNames.add(reactionRuleName);
} else {
line = line.substring(labelEndIndex + 1);
}
}
}
// there may be some blanks hanging around
line = line.trim();
if (line.length() == 0) {
// line may be empty now
sb.append("\n");
lineNumber++;
continue;
}
if (bEscapingExpressionBegin) {
StringTokenizer st = new StringTokenizer(line);
String nextToken = st.nextToken();
if (Character.isDigit(nextToken.charAt(0))) {
sb.append(nextToken + " ");
nextToken = st.nextToken();
}
sb.append(nextToken);
sb.append(" {");
while (st.hasMoreTokens()) {
sb.append(st.nextToken());
}
sb.append("}");
sb.append("\n");
} else {
sb.append(line + "\n");
if (location == BnglLocation.Compartment) {
// make a list with all the compartment names, we'll need them during phase 2 to remove the "containing
// compartment" (which we can't deal with) and to build the escape expression for the volume using the { }
StringTokenizer st = new StringTokenizer(line);
// first token is compartment name
String firstToken = st.nextToken();
if (!compartments.add(firstToken)) {
System.out.println("BnglPreprocessor: Duplicate compartment name!" + firstToken);
}
}
}
if (line.startsWith("begin parameters") || line.startsWith("begin seed species")) {
// TODO: position sensitive, do not move this 'if' up
bEscapingExpressionBegin = true;
}
location = markBlock(location, line);
lineNumber++;
}
br.close();
ListIterator<BnglComment> it = comments.listIterator();
while (it.hasNext()) {
BnglComment bc = it.next();
System.out.println(bc.entityName + " " + bc.location + " " + bc.comment);
}
// pass 2, deal with comments and labels
String cleanedBngl = sb.toString();
// System.out.println(cleanedBngl);
br = new BufferedReader(new StringReader(cleanedBngl));
sb = new StringBuilder();
lineNumber = 0;
location = BnglLocation.OutsideBlock;
while (true) {
String line = br.readLine();
if (line == null) {
// end of document
break;
}
if (line.isEmpty()) {
sb.append("\n");
lineNumber++;
continue;
}
BnglLocation newLocation = markBlock(location, line);
if ((newLocation == BnglLocation.ReactionRule) && (location == BnglLocation.ReactionRule)) {
int labelEndIndex = line.indexOf(":");
if (labelEndIndex == -1) {
// no label on this reaction rule, so we make one
String reactionRuleName = generateReactionRuleName();
if (reactionRuleNames.indexOf(reactionRuleName) != -1) {
// already in use
reactionRuleName = reactionRuleName + "_" + lineNumber;
}
reactionRuleNames.add(reactionRuleName);
line = reactionRuleName + ":" + line;
sb.append(line + "\n");
} else {
// rule has label, we keep it as it is
sb.append(line + "\n");
}
} else if ((newLocation == BnglLocation.Compartment) && (location == BnglLocation.Compartment)) {
// remove the optional "containing compartment" if specified
System.out.println(line);
StringTokenizer st = new StringTokenizer(line);
String lastToken = "";
while (st.hasMoreTokens()) {
lastToken = st.nextToken();
}
if (compartments.contains(lastToken)) {
line = line.substring(0, line.lastIndexOf(lastToken));
}
line = line.trim();
// start again and add the { } around the expression of volume
st = new StringTokenizer(line);
// name
String nextToken = st.nextToken();
sb.append(nextToken + " ");
// dimension
nextToken = st.nextToken();
sb.append(nextToken + " ");
sb.append("{");
while (st.hasMoreTokens()) {
sb.append(st.nextToken());
}
sb.append("}");
sb.append("\n");
} else {
// all other cases nothing special to do
sb.append(line + "\n");
}
location = newLocation;
lineNumber++;
}
br.close();
cleanedBngl = sb.toString();
// System.out.println(cleanedBngl);
// BufferedWriter writer = null;
// try {
// writer = new BufferedWriter( new FileWriter( "c:\\TEMP\\workRules.bngl"));
// writer.write( cleanedBngl);
// }
// catch ( IOException e) {
// }
// finally {
// try {
// if ( writer != null)
// writer.close( );
// }
// catch ( IOException e) {
// }
// }
// BufferedReader br1 = new BufferedReader(new FileReader("c:\\TEMP\\workRules.bngl"));
// try {
// StringBuilder sb1 = new StringBuilder();
// String line = br1.readLine();
// while (line != null) {
// sb1.append(line);
// sb1.append("\n");
// line = br1.readLine();
// }
// cleanedBngl = sb1.toString();
// } finally {
// br.close();
// }
// System.out.println(cleanedBngl);
BNGLParser parser = new BNGLParser(new StringReader(cleanedBngl));
ASTModel astModel = parser.Model();
String prologString = sPrologBuilder.toString();
astModel.setProlog(prologString);
return astModel;
// BnglObjectConstructionVisitor constructionVisitor = new BnglObjectConstructionVisitor(rbmModelContainer);
// astModel.jjtAccept(constructionVisitor, rbmModelContainer);
} catch (Throwable ex) {
// ex.printStackTrace();
if (ex instanceof ParseException) {
ParseException pe = (ParseException) ex;
throw pe;
} else {
throw new ParseException(ex.getMessage());
}
}
}
Aggregations