use of org.vcell.util.document.MathModelInfo in project vcell by virtualcell.
the class DatabaseWindowManager method accessPermissions.
/**
* Insert the method's description here.
* Creation date: (5/14/2004 5:35:55 PM)
*/
public void accessPermissions(final Component requester, final VersionInfo selectedVersionInfo) {
final GroupAccess groupAccess = selectedVersionInfo.getVersion().getGroupAccess();
final DocumentManager docManager = getRequestManager().getDocumentManager();
AsynchClientTask task1 = new AsynchClientTask("show dialog", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
getAclEditor().clearACLList();
getAclEditor().setACLState(new ACLEditor.ACLState(groupAccess));
Object choice = showAccessPermissionDialog(getAclEditor(), requester);
if (choice != null) {
hashTable.put("choice", choice);
}
}
};
AsynchClientTask task2 = new AsynchClientTask("access permission", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
Object choice = hashTable.get("choice");
if (choice != null && choice.equals("OK")) {
ACLEditor.ACLState aclState = getAclEditor().getACLState();
if (aclState != null) {
if (aclState.isAccessPrivate() || (aclState.getAccessList() != null && aclState.getAccessList().length == 0)) {
VersionInfo vInfo = null;
if (selectedVersionInfo instanceof BioModelInfo) {
vInfo = docManager.setGroupPrivate((BioModelInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof MathModelInfo) {
vInfo = docManager.setGroupPrivate((MathModelInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof GeometryInfo) {
vInfo = docManager.setGroupPrivate((GeometryInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof VCImageInfo) {
vInfo = docManager.setGroupPrivate((VCImageInfo) selectedVersionInfo);
}
} else if (aclState.isAccessPublic()) {
VersionInfo vInfo = null;
if (selectedVersionInfo instanceof BioModelInfo) {
vInfo = docManager.setGroupPublic((BioModelInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof MathModelInfo) {
vInfo = docManager.setGroupPublic((MathModelInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof GeometryInfo) {
vInfo = docManager.setGroupPublic((GeometryInfo) selectedVersionInfo);
} else if (selectedVersionInfo instanceof VCImageInfo) {
vInfo = docManager.setGroupPublic((VCImageInfo) selectedVersionInfo);
}
} else {
String[] aclUserNames = aclState.getAccessList();
String[] originalGroupAccesNames = new String[0];
// Turn User[] into String[]
if (groupAccess instanceof GroupAccessSome) {
GroupAccessSome gas = (GroupAccessSome) groupAccess;
User[] originalUsers = gas.getNormalGroupMembers();
for (int i = 0; i < originalUsers.length; i += 1) {
originalGroupAccesNames = (String[]) BeanUtils.addElement(originalGroupAccesNames, originalUsers[i].getName());
}
}
// Determine users needing adding
String[] needToAddUsers = new String[0];
for (int i = 0; i < aclUserNames.length; i += 1) {
if (!BeanUtils.arrayContains(originalGroupAccesNames, aclUserNames[i])) {
System.out.println("Added user=" + aclUserNames[i]);
needToAddUsers = (String[]) BeanUtils.addElement(needToAddUsers, aclUserNames[i]);
}
}
// Determine users needing removing
String[] needToRemoveUsers = new String[0];
for (int i = 0; i < originalGroupAccesNames.length; i += 1) {
if (!BeanUtils.arrayContains(aclUserNames, originalGroupAccesNames[i])) {
System.out.println("Removed user=" + originalGroupAccesNames[i]);
needToRemoveUsers = (String[]) BeanUtils.addElement(needToRemoveUsers, originalGroupAccesNames[i]);
}
}
VersionInfo vInfo = null;
String errorNames = "";
// Add Users to Group Access List
for (int i = 0; i < needToAddUsers.length; i++) {
try {
if (selectedVersionInfo instanceof BioModelInfo) {
vInfo = docManager.addUserToGroup((BioModelInfo) selectedVersionInfo, needToAddUsers[i]);
} else if (selectedVersionInfo instanceof MathModelInfo) {
vInfo = docManager.addUserToGroup((MathModelInfo) selectedVersionInfo, needToAddUsers[i]);
} else if (selectedVersionInfo instanceof GeometryInfo) {
vInfo = docManager.addUserToGroup((GeometryInfo) selectedVersionInfo, needToAddUsers[i]);
} else if (selectedVersionInfo instanceof VCImageInfo) {
vInfo = docManager.addUserToGroup((VCImageInfo) selectedVersionInfo, needToAddUsers[i]);
}
} catch (ObjectNotFoundException e) {
errorNames += "Error changing permissions.\n" + selectedVersionInfo.getVersionType().getTypeName() + " \"" + selectedVersionInfo.getVersion().getName() + "\" edition (" + selectedVersionInfo.getVersion().getDate() + ")\nnot found, " + "your model list may be out of date, please go to menu Server->Reconnect to refresh the model list" + "\n";
break;
} catch (DataAccessException e) {
errorNames += "Error adding user '" + needToAddUsers[i] + "' : " + e.getMessage() + "\n";
}
}
// Remove users from Group Access List
for (int i = 0; i < needToRemoveUsers.length; i++) {
try {
if (selectedVersionInfo instanceof BioModelInfo) {
vInfo = docManager.removeUserFromGroup((BioModelInfo) selectedVersionInfo, needToRemoveUsers[i]);
} else if (selectedVersionInfo instanceof MathModelInfo) {
vInfo = docManager.removeUserFromGroup((MathModelInfo) selectedVersionInfo, needToRemoveUsers[i]);
} else if (selectedVersionInfo instanceof GeometryInfo) {
vInfo = docManager.removeUserFromGroup((GeometryInfo) selectedVersionInfo, needToRemoveUsers[i]);
} else if (selectedVersionInfo instanceof VCImageInfo) {
vInfo = docManager.removeUserFromGroup((VCImageInfo) selectedVersionInfo, needToRemoveUsers[i]);
}
} catch (DataAccessException e) {
errorNames += "Error Removing user '" + needToRemoveUsers[i] + "'\n -----" + e.getMessage() + "\n";
}
}
if (errorNames.length() > 0) {
if (DatabaseWindowManager.this.getComponent() != null) {
PopupGenerator.showErrorDialog(DatabaseWindowManager.this, errorNames);
} else {
DialogUtils.showErrorDialog(requester, errorNames);
}
accessPermissions(requester, selectedVersionInfo);
}
}
}
}
}
};
ClientTaskDispatcher.dispatch(requester, new Hashtable<String, Object>(), new AsynchClientTask[] { task1, task2 });
}
use of org.vcell.util.document.MathModelInfo in project vcell by virtualcell.
the class VCComprehensiveStatistics method collectMathModelStats.
private void collectMathModelStats(long startDateInMs, long endDateInMs) throws DataAccessException {
retrieveUsers();
for (User user : userList) {
if (!userConstraintList.contains(user.getName())) {
continue;
}
if (!internalDeveloper.contains(user.getName())) {
boolean bInternal = internalUsers.contains(user.getName());
ModelStat modelStat = mathModelStats[bInternal ? 0 : 1];
MathModelInfo[] mathModelInfos = dbServerImpl.getMathModelInfos(user, false);
for (MathModelInfo mmi : mathModelInfos) {
Date createDate = mmi.getVersion().getDate();
long t = createDate.getTime();
// }
if (t < startDateInMs || t > endDateInMs) {
continue;
}
// modelStat.count_model ++;
try {
BigString mathModelXML = dbServerImpl.getMathModelXML(user, mmi.getVersion().getVersionKey());
MathModel mathModel = (MathModel) waitForModel(mathModelXML, true);
if (mathModel == null) {
System.out.println("---------- Skipped MathModel " + mmi.getVersion() + " ----------");
continue;
}
modelStat.count_model++;
boolean bHasCompletedSim = false;
for (Simulation sim : mathModel.getSimulations()) {
SimulationStatusPersistent ss = dbServerImpl.getSimulationStatus(sim.getKey());
for (int scan = 0; scan < sim.getScanCount(); scan++) {
SimulationJobStatusPersistent jobStatus = ss.getJobStatus(scan);
if (jobStatus != null) {
if (jobStatus.getSchedulerStatus() == SchedulerStatus.COMPLETED) {
bHasCompletedSim = true;
long elapsed = jobStatus.getEndDate().getTime() - jobStatus.getStartDate().getTime();
if (elapsed < 2 * MINUTE_IN_MS) {
modelStat.runningTimeHistogram[0]++;
} else if (elapsed < 5 * MINUTE_IN_MS) {
modelStat.runningTimeHistogram[1]++;
} else if (elapsed < 20 * MINUTE_IN_MS) {
modelStat.runningTimeHistogram[2]++;
} else if (elapsed < HOUR_IN_MS) {
modelStat.runningTimeHistogram[3]++;
} else if (elapsed < DAY_IN_MS) {
modelStat.runningTimeHistogram[4]++;
} else {
modelStat.runningTimeHistogram[5]++;
}
}
int dimension = sim.getMathDescription().getGeometry().getDimension();
modelStat.count_geoDimSim[dimension]++;
if (sim.getMathDescription().isNonSpatialStoch()) {
modelStat.count_sim_stochastic++;
} else {
modelStat.count_sim_deterministic++;
}
if (dimension > 0) {
if (sim.getSolverTaskDescription().getSolverDescription().isSemiImplicitPdeSolver()) {
modelStat.count_semiSim++;
} else {
modelStat.count_fullySim++;
}
}
}
}
}
if (bHasCompletedSim) {
modelStat.count_model_simcomplete++;
}
} catch (Exception e2) {
e2.printStackTrace(System.out);
}
}
}
}
itemCount++;
statOutputPW.println(itemCount + ". MathModel Statistics ");
statOutputPW.println("====================================================");
for (ModelStat modelStat : mathModelStats) {
statOutputPW.println("\t" + modelStat.title);
statOutputPW.println("========================================");
statOutputPW.println("number of mathmodels saved :\t" + modelStat.count_model);
statOutputPW.println("number of mathmodels that has at least 1 completed simulation :\t" + modelStat.count_model_simcomplete);
statOutputPW.println();
statOutputPW.println("Simulation statistics (including all simulations (stopped, failed, completed) :");
statOutputPW.println("number of run simulation ODE :\t" + modelStat.count_geoDimSim[0]);
statOutputPW.println("number of run simulation 1D :\t" + modelStat.count_geoDimSim[1]);
statOutputPW.println("number of run simulation 2D :\t" + modelStat.count_geoDimSim[2]);
statOutputPW.println("number of run simulation 3D :\t" + modelStat.count_geoDimSim[3]);
statOutputPW.println("number of run simulation Semi-Implicit :\t" + modelStat.count_semiSim);
statOutputPW.println("number of run simulation Fully-Implicit :\t" + modelStat.count_fullySim);
statOutputPW.println("number of run simulation stochastic :\t" + modelStat.count_sim_stochastic);
statOutputPW.println("number of run simulation deterministic :\t" + modelStat.count_sim_deterministic);
statOutputPW.println();
statOutputPW.println("Running time histogram for completed simulations only:");
statOutputPW.println("0 ~ 2min:\t" + modelStat.runningTimeHistogram[0]);
statOutputPW.println("2 ~ 5min:\t" + modelStat.runningTimeHistogram[1]);
statOutputPW.println("5 ~ 20min:\t" + modelStat.runningTimeHistogram[2]);
statOutputPW.println("20min ~ 1hr:\t" + modelStat.runningTimeHistogram[3]);
statOutputPW.println("1hr ~ 1day:\t" + modelStat.runningTimeHistogram[4]);
statOutputPW.println(">1day:\t" + modelStat.runningTimeHistogram[5]);
statOutputPW.println();
statOutputPW.println();
statOutputPW.flush();
}
}
use of org.vcell.util.document.MathModelInfo in project vcell by virtualcell.
the class ClientRequestManager method deleteDocument.
/**
* Insert the method's description here. Creation date: (6/22/2004 10:50:34 PM)
*
* @param documentInfo cbit.vcell.document.VCDocumentInfo
*/
public void deleteDocument(final VCDocumentInfo documentInfo, final TopLevelWindowManager requester, boolean bDontAsk) {
if (documentInfo != null) {
// see if we have this open
String documentID = documentInfo.getVersion().getVersionKey().toString();
if (getMdiManager().haveWindow(documentID)) {
// already open, refuse
PopupGenerator.showErrorDialog(requester, "Selected edition is open, cannot delete");
return;
} else {
// don't have it open, try to delete it
String confirm = UserMessage.OPTION_CANCEL;
if (bDontAsk) {
confirm = UserMessage.OPTION_DELETE;
} else {
SimpleDateFormat sdf = new SimpleDateFormat(BeanUtils.vcDateFormat);
confirm = PopupGenerator.showWarningDialog(requester, getUserPreferences(), UserMessage.warn_deleteDocument, documentInfo.getVersion().getName() + " " + sdf.format(documentInfo.getVersion().getDate()));
}
if (confirm.equals(UserMessage.OPTION_DELETE)) {
AsynchClientTask task1 = new AsynchClientTask("Deleting document...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
if (documentInfo instanceof BioModelInfo) {
getDocumentManager().delete((BioModelInfo) documentInfo);
} else if (documentInfo instanceof MathModelInfo) {
getDocumentManager().delete((MathModelInfo) documentInfo);
} else if (documentInfo instanceof GeometryInfo) {
getDocumentManager().delete((GeometryInfo) documentInfo);
} else {
throw new RuntimeException("delete not supported for VCDocumentInfo type " + documentInfo.getClass().getName());
}
}
};
ClientTaskDispatcher.dispatch(requester.getComponent(), new Hashtable<String, Object>(), new AsynchClientTask[] { task1 }, false);
} else {
// user canceled
return;
}
}
} else {
// nothing selected
return;
}
}
use of org.vcell.util.document.MathModelInfo in project vcell by virtualcell.
the class ClientRequestManager method accessPermissions.
public void accessPermissions(Component requester, VCDocument vcDoc) {
VersionInfo selectedVersionInfo = null;
switch(vcDoc.getDocumentType()) {
case BIOMODEL_DOC:
BioModelInfo[] bioModelInfos = getDocumentManager().getBioModelInfos();
for (BioModelInfo bioModelInfo : bioModelInfos) {
if (bioModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
selectedVersionInfo = bioModelInfo;
break;
}
}
break;
case MATHMODEL_DOC:
MathModelInfo[] mathModelInfos = getDocumentManager().getMathModelInfos();
for (MathModelInfo mathModelInfo : mathModelInfos) {
if (mathModelInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
selectedVersionInfo = mathModelInfo;
break;
}
}
break;
case GEOMETRY_DOC:
GeometryInfo[] geoInfos = getDocumentManager().getGeometryInfos();
for (GeometryInfo geoInfo : geoInfos) {
if (geoInfo.getVersion().getVersionKey().equals(vcDoc.getVersion().getVersionKey())) {
selectedVersionInfo = geoInfo;
break;
}
}
break;
}
getMdiManager().getDatabaseWindowManager().accessPermissions(requester, selectedVersionInfo, false);
}
use of org.vcell.util.document.MathModelInfo 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);
}
Aggregations