use of cbit.vcell.solver.OutputFunctionContext in project vcell by virtualcell.
the class OutputFunctionsListTableModel method propertyChange.
/**
* This method gets called when a bound property is changed.
* @param evt A PropertyChangeEvent object describing the event source
* and the property that has changed.
*/
public void propertyChange(java.beans.PropertyChangeEvent evt) {
OutputFunctionContext fc = getOutputFunctionContext();
SimulationOwner so = null;
if (fc != null) {
so = fc.getSimulationOwner();
}
if (evt.getSource() == fc && evt.getPropertyName().equals(OutputFunctionContext.PROPERTY_OUTPUT_FUNCTIONS)) {
setData(outputFunctionContext.getOutputFunctionsList());
}
if (evt.getSource() instanceof SimulationContext && evt.getSource() == so && evt.getPropertyName().equals(Model.PROPERTY_NAME_MODEL_ENTITY_NAME)) {
SimulationContext simulationContext = (SimulationContext) so;
if (fc.getOutputFunctionsList() == null || fc.getOutputFunctionsList().isEmpty()) {
return;
}
Hashtable<String, Object> hashTable = new Hashtable<String, Object>();
//
// WARNING: this should NOT be used under any circumstance for batch renaming
// MathDescription, MathMapping, expressions are NOT thread safe
//
AsynchClientTask task0 = new AsynchClientTask("Renaming Functions", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) {
@Override
public void run(Hashtable<String, Object> hashTable) throws Exception {
MathMappingCallback callback = new MathMappingCallback() {
@Override
public void setProgressFraction(float fractionDone) {
}
@Override
public void setMessage(String message) {
}
@Override
public boolean isInterrupted() {
return false;
}
};
MathMapping mathMapping = simulationContext.createNewMathMapping(callback, NetworkGenerationRequirements.ComputeFullNoTimeout);
MathDescription mathDesc = null;
try {
mathDesc = mathMapping.getMathDescription(callback);
} catch (MappingException | MathException | MatrixException | ExpressionException | ModelException e1) {
e1.printStackTrace();
}
String oldName = (String) evt.getOldValue();
String newName = (String) evt.getNewValue();
ArrayList<AnnotatedFunction> afList = fc.getOutputFunctionsList();
List<Expression> changedExpressions = new ArrayList<>();
for (AnnotatedFunction af : afList) {
if (af == null) {
continue;
}
Expression exp = af.getExpression();
if (exp == null || exp.getSymbols() == null || exp.getSymbols().length == 0) {
continue;
}
String errMsg = "Failed to rename symbol '" + oldName + "' with '" + newName + "' in the Expression of Function '" + af.getName() + "'.";
for (String symbol : exp.getSymbols()) {
if (symbol.contentEquals(oldName)) {
try {
exp.substituteInPlace(new Expression(oldName), new Expression(newName));
changedExpressions.add(exp);
} catch (ExpressionException e) {
e.printStackTrace();
throw new RuntimeException(errMsg);
}
}
}
}
if (changedExpressions.size() > 0) {
try {
simulationContext.setMathDescription(mathDesc);
for (Expression exp : changedExpressions) {
exp.bindExpression(outputFunctionContext);
}
} catch (ExpressionException | PropertyVetoException e) {
e.printStackTrace();
}
}
}
};
ClientTaskDispatcher.dispatch(ownerTable, hashTable, new AsynchClientTask[] { task0 }, false);
}
if (evt.getPropertyName().equals(GeometryOwner.PROPERTY_NAME_GEOMETRY)) {
Geometry oldGeometry = (Geometry) evt.getOldValue();
Geometry newGeometry = (Geometry) evt.getNewValue();
// changing from ode to pde
if (oldGeometry.getDimension() == 0 && newGeometry.getDimension() > 0) {
fireTableStructureChanged();
setData(getOutputFunctionContext().getOutputFunctionsList());
}
}
}
use of cbit.vcell.solver.OutputFunctionContext in project vcell by virtualcell.
the class OutputFunctionsPanel method setOutputFunctionContext.
private void setOutputFunctionContext(OutputFunctionContext argOutputFnContext) {
OutputFunctionContext oldValue = this.outputFunctionContext;
this.outputFunctionContext = argOutputFnContext;
firePropertyChange("outputFunctionContext", oldValue, argOutputFnContext);
}
use of cbit.vcell.solver.OutputFunctionContext in project vcell by virtualcell.
the class XmlReader method getMathModel.
/*
public RateRuleVariable[] getRateRuleVariables(Element rateRuleVarsElement, Model model) throws XmlParseException {
Iterator<Element> rateRuleVarsIterator = rateRuleVarsElement.getChildren(XMLTags.RateRuleVariableTag, vcNamespace).iterator();
Vector<RateRuleVariable> rateRuleVarsVector = new Vector<RateRuleVariable>();
while (rateRuleVarsIterator.hasNext()) {
Element rrvElement = (Element) rateRuleVarsIterator.next();
RateRuleVariable newRateRuleVar = null;
try {
String rrvName = unMangle(rrvElement.getAttributeValue(XMLTags.NameAttrTag));
String rrvStructureName = unMangle(rrvElement.getAttributeValue(XMLTags.StructureAttrTag));
// structure can be null
Structure rrvStructure = null;
if (rrvStructureName != null) {
rrvStructure = (Structure) model.getStructure(rrvStructureName);
}
// if (structureref == null) {
// throw new XmlParseException("The structure " + rrvStructureName + "could not be resolved!");
// }
String rrvRoleStr = rrvElement.getAttributeValue(XMLTags.ParamRoleAttrTag);
int rrvRole = RateRuleVariable.getParamRoleFromDesc(rrvRoleStr);
Element rrvParamElement = rrvElement.getChild(XMLTags.ParameterTag, vcNamespace);
ModelParameter rrvParameter = getModelParameter(rrvParamElement, model);
newRateRuleVar = new RateRuleVariable(rrvName, rrvStructure, rrvParameter, rrvRole);
newRateRuleVar.bind();
} catch (ExpressionBindingException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e.getMessage());
}
if (newRateRuleVar != null) {
rateRuleVarsVector.add(newRateRuleVar);
}
}
return ((RateRuleVariable[])BeanUtils.getArray(rateRuleVarsVector, RateRuleVariable.class));
}
*/
/**
* This method returns a MathModel object from a XML Element.
* Creation date: (3/13/2001 12:35:00 PM)
* @return cbit.vcell.mathmodel.MathModel
* @param param org.jdom.Element
*/
public MathModel getMathModel(Element param) throws XmlParseException {
// Create it
// set Metadata (version), if any
Version versionObject = getVersion(param.getChild(XMLTags.VersionTag, vcNamespace));
MathModel mathmodel = new MathModel(versionObject);
// Set attributes
String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
try {
mathmodel.setName(name);
// String annotation = param.getAttributeValue(XMLTags.AnnotationAttrTag);
// if (annotation!=null) {
// mathmodel.setDescription(unMangle(annotation));
// }
// Add annotation
String annotationText = param.getChildText(XMLTags.AnnotationTag, vcNamespace);
if (annotationText != null && annotationText.length() > 0) {
mathmodel.setDescription(unMangle(annotationText));
}
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("An error occurred while trying to set the name " + param.getAttributeValue(XMLTags.NameAttrTag) + "to a MathModel!", e);
}
// set Geometry (if any)
Element tempElem = param.getChild(XMLTags.GeometryTag, vcNamespace);
Geometry tempGeometry = getGeometry(tempElem);
// set MathDescription
tempElem = param.getChild(XMLTags.MathDescriptionTag, vcNamespace);
MathDescription mathDesc = getMathDescription(tempElem, tempGeometry);
if (tempElem != null) {
mathmodel.setMathDescription(mathDesc);
} else {
throw new XmlParseException("MathDescription missing in this MathModel!");
}
// set output functions (outputfunctionContext)
Element outputFunctionsElement = param.getChild(XMLTags.OutputFunctionsTag, vcNamespace);
if (outputFunctionsElement != null) {
ArrayList<AnnotatedFunction> outputFunctions = getOutputFunctions(outputFunctionsElement);
try {
// construct OutputFnContext from mathmodel and add output functions that were read in from XML.
OutputFunctionContext outputFnContext = mathmodel.getOutputFunctionContext();
for (AnnotatedFunction outputFunction : outputFunctions) {
outputFnContext.addOutputFunction(outputFunction);
}
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
}
// Set simulations contexts (if any)
List<Element> childList = param.getChildren(XMLTags.SimulationTag, vcNamespace);
Simulation[] simList = new Simulation[childList.size()];
int simCounter = 0;
for (Element simElement : childList) {
simList[simCounter] = getSimulation(simElement, mathDesc);
simCounter++;
}
try {
mathmodel.setSimulations(simList);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace();
throw new XmlParseException("A PropertyVetoException occurred when adding the Simulations to the MathModel " + name, e);
}
return mathmodel;
}
use of cbit.vcell.solver.OutputFunctionContext in project vcell by virtualcell.
the class IonItems method saveVCMLRemoveSimsWithNoData.
private static void saveVCMLRemoveSimsWithNoData(Connection con, File dirToSaveVCML, File usersDir, long startSimKey, long endSimKey) {
// select id from vc_biomodel where versionflag=3 and privacy=0;
String bmsql = "SELECT " + BioModelTable.table.id.getQualifiedColName() + " modelkey" + "," + UserTable.table.id.getQualifiedColName() + " userkey" + "," + UserTable.table.userid.getQualifiedColName() + " userid" + " FROM " + BioModelTable.table.getTableName() + "," + UserTable.table.getTableName() + " WHERE " + BioModelTable.table.versionFlag.getQualifiedColName() + "=" + VersionFlag.Published.getIntValue() + " AND " + BioModelTable.table.privacy.getQualifiedColName() + "=" + GroupAccess.GROUPACCESS_ALL.intValue() + " AND " + BioModelTable.table.ownerRef.getQualifiedColName() + "=" + UserTable.table.id.getQualifiedColName() + " AND " + BioModelTable.table.id.getQualifiedColName() + " IN " + "(SELECT " + PublicationModelLinkTable.table.bioModelRef.getQualifiedColName() + " FROM " + PublicationModelLinkTable.table.getTableName() + " WHERE " + PublicationModelLinkTable.table.bioModelRef.getQualifiedColName() + " IS NOT NULL)" + " ORDER BY modelKey";
String mmsql = "SELECT " + MathModelTable.table.id.getQualifiedColName() + " modelkey" + "," + UserTable.table.id.getQualifiedColName() + " userkey" + "," + UserTable.table.userid.getQualifiedColName() + " userid" + " FROM " + MathModelTable.table.getTableName() + "," + UserTable.table.getTableName() + " WHERE " + MathModelTable.table.versionFlag.getQualifiedColName() + "=" + VersionFlag.Published.getIntValue() + " AND " + MathModelTable.table.privacy.getQualifiedColName() + "=" + GroupAccess.GROUPACCESS_ALL.intValue() + " AND " + MathModelTable.table.ownerRef.getQualifiedColName() + "=" + UserTable.table.id.getQualifiedColName() + " AND " + MathModelTable.table.id.getQualifiedColName() + " IN " + // vc_publicationmodellink.biomodelref
"(SELECT " + PublicationModelLinkTable.table.mathModelRef.getQualifiedColName() + " FROM " + PublicationModelLinkTable.table.getTableName() + " WHERE " + PublicationModelLinkTable.table.mathModelRef.getQualifiedColName() + " IS NOT NULL)" + " ORDER BY modelKey";
Statement stmt = null;
try {
stmt = con.createStatement();
// ArrayList<VCDocument> successDocs = new ArrayList<VCDocument>();
DatabaseServerImpl databaseServerImpl = new DatabaseServerImpl(connFac, null);
// ServerDocumentManager serverDocManager = new ServerDocumentManager(databaseServerImpl);
// QueryHashtable qht = new QueryHashtable();
DataSetControllerImpl dsci = new DataSetControllerImpl(new Cachetable(Cachetable.minute * 3, 30000000L), usersDir, null);
ArrayList<Object[]> modeKeyAndUser = new ArrayList<Object[]>();
for (int i = 0; i < 2; i++) {
String sql = (i == 0 ? bmsql : mmsql);
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
BigDecimal modelKeyBigDecimal = rset.getBigDecimal("modelkey");
KeyValue modelKey = new KeyValue(modelKeyBigDecimal);
if (startSimKey == 0 || (modelKeyBigDecimal.longValue() >= startSimKey && modelKeyBigDecimal.longValue() <= endSimKey)) {
User user = new User(rset.getString("userid"), new KeyValue(rset.getBigDecimal("userkey")));
modeKeyAndUser.add(new Object[] { (i == 0 ? VCDocumentType.BIOMODEL_DOC : VCDocumentType.MATHMODEL_DOC), modelKey, user });
}
}
rset.close();
}
stmt.close();
VCDocument vcDoc = null;
for (int ii = 0; ii < modeKeyAndUser.size(); ii++) {
try {
VCDocumentType vcDocType = (VCDocumentType) modeKeyAndUser.get(ii)[0];
KeyValue modelKey = (KeyValue) modeKeyAndUser.get(ii)[1];
User user = (User) modeKeyAndUser.get(ii)[2];
// -----NOTE: (privacy, versionflag) may not match between xml and database (because privacy and versionflag can be set without saving model)
// some models regenerated from xml will not have same privacy and versionflag matched in query from database (the database values are correct, ignore the xml values)
BigString modelXML = (vcDocType == VCDocumentType.BIOMODEL_DOC ? databaseServerImpl.getBioModelXML(user, modelKey) : databaseServerImpl.getMathModelXML(user, modelKey));
Simulation[] sims = null;
vcDoc = null;
if (vcDocType == VCDocumentType.BIOMODEL_DOC) {
BioModel bm = cbit.vcell.xml.XmlHelper.XMLToBioModel(new XMLSource(modelXML.toString()));
bm.refreshDependencies();
sims = bm.getSimulations().clone();
vcDoc = bm;
} else {
MathModel mm = cbit.vcell.xml.XmlHelper.XMLToMathModel(new XMLSource(modelXML.toString()));
mm.refreshDependencies();
sims = mm.getSimulations().clone();
vcDoc = mm;
}
// if(true) {
// System.out.println(modelKey+" "+user+" "+vcDoc);
// continue;
// }
boolean bRemovedSims = false;
for (int j = 0; sims != null && j < sims.length; j++) {
try {
// public FoundSimDataInfo(long simID, int lastTaskID, int jobIndex, String userid) {
File foundLog = findSimLogFile(usersDir, new FoundSimDataInfo(Long.parseLong(sims[j].getKey().toString()), -1, 0, user.getName()), true, vcDocType);
if (foundLog == null) {
throw new Exception("Logfile not found for sim " + sims[j].getKey().toString());
} else {
VCSimulationIdentifier vcsi = new VCSimulationIdentifier(sims[j].getKey(), user);
VCSimulationDataIdentifier vcdID = new VCSimulationDataIdentifier(vcsi, 0);
OutputFunctionContext outputFunctionContext = sims[j].getSimulationOwner().getOutputFunctionContext();
OutputContext outputContext = new OutputContext(outputFunctionContext.getOutputFunctionsList().toArray(new AnnotatedFunction[0]));
DataIdentifier[] dataIdentifiers = dsci.getDataIdentifiers(outputContext, vcdID);
double[] dataSetTimes = dsci.getDataSetTimes(vcdID);
if (sims[j].getMathDescription().getGeometry().getDimension() == 0) {
ODEDataBlock odeDataBlock = dsci.getODEDataBlock(vcdID);
} else {
// for(int k=0;k<dataIdentifiers.length;k++){
SimDataBlock simDataBlock = dsci.getSimDataBlock(outputContext, vcdID, dataIdentifiers[0].getName(), dataSetTimes[dataSetTimes.length - 1]);
// }
}
}
} catch (Exception e) {
System.out.println("-----SIMERROR " + vcDoc.getVersion().getVersionKey() + "\n-----Sim=" + sims[j].getVersion());
e.printStackTrace();
if (e.getMessage().contains("HDF5")) {
return;
}
bRemovedSims = true;
if (vcDoc.getDocumentType() == VCDocument.VCDocumentType.BIOMODEL_DOC) {
((BioModel) vcDoc).removeSimulation(sims[j]);
} else {
((MathModel) vcDoc).removeSimulation(sims[j]);
}
}
}
String docXml = null;
if (vcDoc.getDocumentType() == VCDocument.VCDocumentType.BIOMODEL_DOC) {
docXml = XmlHelper.bioModelToXML(((BioModel) vcDoc));
} else {
docXml = XmlHelper.mathModelToXML(((MathModel) vcDoc));
}
PrintWriter pw = new PrintWriter(new File(dirToSaveVCML, vcDoc.getVersion().getVersionKey().toString() + "_" + (bRemovedSims) + ".xml"));
pw.write(docXml);
pw.close();
// }
} catch (Exception e) {
System.out.println("----------GENERALERROR " + vcDoc.getVersion().getVersionKey());
e.printStackTrace();
if (vcDoc != null) {
PrintWriter pw = new PrintWriter(new File(dirToSaveVCML, vcDoc.getVersion().getVersionKey().toString() + "_exception.xml"));
pw.write("");
pw.close();
}
}
}
// for(VCDocument successDoc:successDocs) {
// if(successDoc.getDocumentType() == VCDocument.VCDocumentType.BIOMODEL_DOC) {
// ((BioModel)vcDoc).removeSimulation(sims[i]);
// }else {
// ((MathModel)vcDoc).removeSimulation(sims[i]);
// }
//
// }
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
use of cbit.vcell.solver.OutputFunctionContext in project vcell by virtualcell.
the class XmlReader method getSimulationContext.
/**
* This method returns a SimulationContext from a XML representation.
* Creation date: (4/2/2001 3:19:01 PM)
* @return cbit.vcell.mapping.SimulationContext
* @param param org.jdom.Element
*/
private SimulationContext getSimulationContext(Element param, BioModel biomodel) throws XmlParseException {
// get the attributes
// name
String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
boolean bStoch = false;
boolean bRuleBased = false;
boolean bUseConcentration = true;
boolean bRandomizeInitCondition = false;
boolean bInsufficientIterations = false;
boolean bInsufficientMaxMolecules = false;
// default is true for now
boolean bMassConservationModelReduction = true;
NetworkConstraints nc = null;
Element ncElement = param.getChild(XMLTags.RbmNetworkConstraintsTag, vcNamespace);
if (ncElement != null) {
// one network constraint element
nc = getAppNetworkConstraints(ncElement, biomodel.getModel());
} else {
if (legacyNetworkConstraints != null) {
nc = legacyNetworkConstraints;
}
}
if ((param.getAttributeValue(XMLTags.StochAttrTag) != null) && (param.getAttributeValue(XMLTags.StochAttrTag).equals("true"))) {
bStoch = true;
}
if (bStoch) {
// stochastic and using concentration vs amount
if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
bUseConcentration = false;
}
// stochastic and randomizing initial conditions or not (for non-spatial)
if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
bRandomizeInitCondition = true;
}
}
if ((param.getAttributeValue(XMLTags.MassConservationModelReductionTag) != null) && (param.getAttributeValue(XMLTags.MassConservationModelReductionTag).equals("false"))) {
bMassConservationModelReduction = false;
}
if ((param.getAttributeValue(XMLTags.InsufficientIterationsTag) != null) && (param.getAttributeValue(XMLTags.InsufficientIterationsTag).equals("true"))) {
bInsufficientIterations = true;
}
if ((param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag) != null) && (param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag).equals("true"))) {
bInsufficientMaxMolecules = true;
}
if ((param.getAttributeValue(XMLTags.RuleBasedAttrTag) != null) && (param.getAttributeValue(XMLTags.RuleBasedAttrTag).equals("true"))) {
bRuleBased = true;
if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
bUseConcentration = false;
}
if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
// we propagate the flag but we don't use it for now
bRandomizeInitCondition = true;
}
}
// Retrieve Geometry
Geometry newgeometry = null;
try {
newgeometry = getGeometry(param.getChild(XMLTags.GeometryTag, vcNamespace));
} catch (Throwable e) {
e.printStackTrace();
String stackTrace = null;
try {
java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
java.io.PrintStream ps = new java.io.PrintStream(bos);
e.printStackTrace(ps);
ps.flush();
bos.flush();
stackTrace = new String(bos.toByteArray());
ps.close();
bos.close();
} catch (Exception e2) {
// do Nothing
}
throw new XmlParseException("A Problem occurred while retrieving the geometry for the simulationContext " + name, e);
}
// Retrieve MathDescription(if there is no MathDescription skip it)
MathDescription newmathdesc = null;
Element xmlMathDescription = param.getChild(XMLTags.MathDescriptionTag, vcNamespace);
if (xmlMathDescription != null) {
newmathdesc = getMathDescription(xmlMathDescription, newgeometry);
if (biomodel.getVersion() != null && biomodel.getVersion().getVersionKey() != null) {
Long lpcBMKey = Long.valueOf(biomodel.getVersion().getVersionKey().toString());
// MathDescription.originalHasLowPrecisionConstants.remove(lpcBMKey);
try {
Enumeration<Constant> myenum = newmathdesc.getConstants();
while (myenum.hasMoreElements()) {
Constant nextElement = myenum.nextElement();
String name2 = nextElement.getName();
ReservedSymbol reservedSymbolByName = biomodel.getModel().getReservedSymbolByName(name2);
if (reservedSymbolByName != null && nextElement.getExpression() != null && reservedSymbolByName.getExpression() != null) {
// System.out.println(name2);
boolean equals = nextElement.getExpression().infix().equals(reservedSymbolByName.getExpression().infix());
// System.out.println("--"+" "+nextElement.getExpression().infix() +" "+reservedSymbolByName.getExpression().infix()+" "+equals);
if (!equals) {
TreeSet<String> treeSet = MathDescription.originalHasLowPrecisionConstants.get(lpcBMKey);
if (treeSet == null) {
treeSet = new TreeSet<>();
MathDescription.originalHasLowPrecisionConstants.put(lpcBMKey, treeSet);
}
treeSet.add(newmathdesc.getVersion().getVersionKey().toString());
break;
}
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// Retrieve Version (Metada)
Version version = getVersion(param.getChild(XMLTags.VersionTag, vcNamespace));
// ------ Create SimContext ------
SimulationContext newsimcontext = null;
try {
newsimcontext = new SimulationContext(biomodel.getModel(), newgeometry, newmathdesc, version, bStoch, bRuleBased);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A propertyveto exception was generated when creating the new SimulationContext " + name, e);
}
// set attributes
try {
newsimcontext.setName(name);
// Add annotation
String annotation = param.getChildText(XMLTags.AnnotationTag, vcNamespace);
if (annotation != null) /* && annotation.length()>0*/
{
newsimcontext.setDescription(unMangle(annotation));
}
// set if using concentration
newsimcontext.setUsingConcentration(bUseConcentration);
// set mass conservation model reduction flag
newsimcontext.setUsingMassConservationModelReduction(bMassConservationModelReduction);
// set if randomizing init condition or not (for stochastic applications
if (bStoch) {
newsimcontext.setRandomizeInitConditions(bRandomizeInitCondition);
}
if (bInsufficientIterations) {
newsimcontext.setInsufficientIterations(bInsufficientIterations);
}
if (bInsufficientMaxMolecules) {
newsimcontext.setInsufficientMaxMolecules(bInsufficientMaxMolecules);
}
if (nc != null) {
newsimcontext.setNetworkConstraints(nc);
}
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("Exception", e);
}
String tempchar = param.getAttributeValue(XMLTags.CharacteristicSizeTag);
if (tempchar != null) {
try {
newsimcontext.setCharacteristicSize(Double.valueOf(tempchar));
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A PropertyVetoException was fired when setting the CharacteristicSize " + tempchar, e);
}
}
// Retrieve DataContext
Element dataContextElement = param.getChild(XMLTags.DataContextTag, vcNamespace);
if (dataContextElement != null) {
DataContext dataContext = newsimcontext.getDataContext();
ArrayList<DataSymbol> dataSymbols = getDataSymbols(dataContextElement, dataContext, newsimcontext.getModel().getUnitSystem());
for (int i = 0; i < dataSymbols.size(); i++) {
dataContext.addDataSymbol(dataSymbols.get(i));
}
}
// Retrieve spatialObjects and add to simContext
Element spatialObjectsElement = param.getChild(XMLTags.SpatialObjectsTag, vcNamespace);
if (spatialObjectsElement != null) {
SpatialObject[] spatialObjects = getSpatialObjects(newsimcontext, spatialObjectsElement);
try {
newsimcontext.setSpatialObjects(spatialObjects);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding spatialObjects to simulationContext", e);
}
}
// Retrieve application parameters and add to simContext
Element appParamsElement = param.getChild(XMLTags.ApplicationParametersTag, vcNamespace);
if (appParamsElement != null) {
SimulationContextParameter[] appParameters = getSimulationContextParams(appParamsElement, newsimcontext);
try {
newsimcontext.setSimulationContextParameters(appParameters);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding application parameters to simulationContext", e);
}
}
//
// -Process the GeometryContext-
//
Element tempelement = param.getChild(XMLTags.GeometryContextTag, vcNamespace);
LinkedList<StructureMapping> maplist = new LinkedList<StructureMapping>();
// Retrieve FeatureMappings
Iterator<Element> iterator = tempelement.getChildren(XMLTags.FeatureMappingTag, vcNamespace).iterator();
while (iterator.hasNext()) {
maplist.add(getFeatureMapping((Element) (iterator.next()), newsimcontext));
}
// Retrieve MembraneMappings
iterator = tempelement.getChildren(XMLTags.MembraneMappingTag, vcNamespace).iterator();
while (iterator.hasNext()) {
maplist.add(getMembraneMapping((Element) (iterator.next()), newsimcontext));
}
// Add these mappings to the internal geometryContext of this simcontext
StructureMapping[] structarray = new StructureMapping[maplist.size()];
maplist.toArray(structarray);
try {
newsimcontext.getGeometryContext().setStructureMappings(structarray);
newsimcontext.getGeometryContext().refreshStructureMappings();
newsimcontext.refreshSpatialObjects();
} catch (MappingException e) {
e.printStackTrace();
throw new XmlParseException("A MappingException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A PopertyVetoException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
}
//
// -Process the ReactionContext-
//
tempelement = param.getChild(XMLTags.ReactionContextTag, vcNamespace);
// Retrieve ReactionSpecs
List<Element> children = tempelement.getChildren(XMLTags.ReactionSpecTag, vcNamespace);
if (children.size() != 0) {
if (children.size() != biomodel.getModel().getReactionSteps().length) {
throw new XmlParseException("The number of reactions is not consistent.\n" + "Model reactions=" + biomodel.getModel().getReactionSteps().length + ", Reaction specs=" + children.size());
}
// *NOTE: Importing a model from other languages does not generates reaction specs.
// A more robust code will read the reactions in the source file and replace the ones created by the default by the VirtualCell framework.
ReactionSpec[] reactionSpecs = new ReactionSpec[children.size()];
int rSpecCounter = 0;
for (Element rsElement : children) {
reactionSpecs[rSpecCounter] = getReactionSpec(rsElement, newsimcontext);
rSpecCounter++;
}
try {
newsimcontext.getReactionContext().setReactionSpecs(reactionSpecs);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionSpecs to the SimContext " + name, e);
}
}
// Retrieve ReactionRuleSpecs
Element reactionRuleSpecsElement = tempelement.getChild(XMLTags.ReactionRuleSpecsTag, vcNamespace);
if (reactionRuleSpecsElement != null) {
ReactionRuleSpec[] reactionRuleSpecs = getReactionRuleSpecs(newsimcontext, reactionRuleSpecsElement);
try {
newsimcontext.getReactionContext().setReactionRuleSpecs(reactionRuleSpecs);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionRuleSpecs to the SimContext " + name, e);
}
}
children = tempelement.getChildren(XMLTags.SpeciesContextSpecTag, vcNamespace);
getSpeciesContextSpecs(children, newsimcontext.getReactionContext(), biomodel.getModel());
// Retrieve output functions
Element outputFunctionsElement = param.getChild(XMLTags.OutputFunctionsTag, vcNamespace);
if (outputFunctionsElement != null) {
ArrayList<AnnotatedFunction> outputFunctions = getOutputFunctions(outputFunctionsElement);
try {
// construct OutputFnContext from mathDesc in newSimContext and add output functions that were read in from XML.
OutputFunctionContext outputFnContext = newsimcontext.getOutputFunctionContext();
for (AnnotatedFunction outputFunction : outputFunctions) {
outputFnContext.addOutputFunction(outputFunction);
}
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
}
// Retrieve Electrical context
org.jdom.Element electElem = param.getChild(XMLTags.ElectricalContextTag, vcNamespace);
// this information is optional!
if (electElem != null) {
if (electElem.getChild(XMLTags.ClampTag, vcNamespace) != null) {
// read clamp
ElectricalStimulus[] electArray = new ElectricalStimulus[1];
electArray[0] = getElectricalStimulus(electElem.getChild(XMLTags.ClampTag, vcNamespace), newsimcontext);
try {
newsimcontext.setElectricalStimuli(electArray);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
}
// read ground electrode
if (electElem.getChild(XMLTags.ElectrodeTag, vcNamespace) != null) {
Electrode groundElectrode = getElectrode(electElem.getChild(XMLTags.ElectrodeTag, vcNamespace), newsimcontext);
try {
newsimcontext.setGroundElectrode(groundElectrode);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException(e);
}
}
}
// Retrieve (bio)events and add to simContext
tempelement = param.getChild(XMLTags.BioEventsTag, vcNamespace);
if (tempelement != null) {
BioEvent[] bioEvents = getBioEvents(newsimcontext, tempelement);
try {
newsimcontext.setBioEvents(bioEvents);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding events to simulationContext", e);
}
}
// Retrieve spatialProcesses and add to simContext
tempelement = param.getChild(XMLTags.SpatialProcessesTag, vcNamespace);
if (tempelement != null) {
SpatialProcess[] spatialProcesses = getSpatialProcesses(newsimcontext, tempelement);
try {
newsimcontext.setSpatialProcesses(spatialProcesses);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding spatialProcesses to simulationContext", e);
}
}
// Retrieve rate rules and add to simContext
tempelement = param.getChild(XMLTags.RateRulesTag, vcNamespace);
if (tempelement != null) {
RateRule[] rateRules = getRateRules(newsimcontext, tempelement);
try {
newsimcontext.setRateRules(rateRules);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding rate rules to simulationContext", e);
}
}
tempelement = param.getChild(XMLTags.AssignmentRulesTag, vcNamespace);
if (tempelement != null) {
AssignmentRule[] assignmentRules = getAssignmentRules(newsimcontext, tempelement);
try {
newsimcontext.setAssignmentRules(assignmentRules);
} catch (PropertyVetoException e) {
e.printStackTrace(System.out);
throw new RuntimeException("Error adding assignment rules to simulationContext", e);
}
}
org.jdom.Element analysisTaskListElement = param.getChild(XMLTags.AnalysisTaskListTag, vcNamespace);
if (analysisTaskListElement != null) {
children = analysisTaskListElement.getChildren(XMLTags.ParameterEstimationTaskTag, vcNamespace);
if (children.size() != 0) {
Vector<ParameterEstimationTask> analysisTaskList = new Vector<ParameterEstimationTask>();
for (Element parameterEstimationTaskElement : children) {
try {
ParameterEstimationTask parameterEstimationTask = ParameterEstimationTaskXMLPersistence.getParameterEstimationTask(parameterEstimationTaskElement, newsimcontext);
analysisTaskList.add(parameterEstimationTask);
} catch (Exception e) {
e.printStackTrace(System.out);
throw new XmlParseException("An Exception occurred when parsing AnalysisTasks of SimContext " + name, e);
}
}
try {
AnalysisTask[] analysisTasks = (AnalysisTask[]) BeanUtils.getArray(analysisTaskList, AnalysisTask.class);
newsimcontext.setAnalysisTasks(analysisTasks);
} catch (java.beans.PropertyVetoException e) {
e.printStackTrace(System.out);
throw new XmlParseException("A PropertyVetoException occurred when setting the AnalysisTasks of the SimContext " + name, e);
}
}
}
// Microscope Measurement
org.jdom.Element element = param.getChild(XMLTags.MicroscopeMeasurement, vcNamespace);
if (element != null) {
getMicroscopeMeasurement(element, newsimcontext);
}
for (GeometryClass gc : newsimcontext.getGeometry().getGeometryClasses()) {
try {
StructureSizeSolver.updateUnitStructureSizes(newsimcontext, gc);
} catch (Exception e) {
e.printStackTrace();
}
}
newsimcontext.getGeometryContext().enforceHierarchicalBoundaryConditions(newsimcontext.getModel().getStructureTopology());
return newsimcontext;
}
Aggregations