Search in sources :

Example 6 with AnnotatedFunction

use of cbit.vcell.solver.AnnotatedFunction 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;
}
Also used : MathModel(cbit.vcell.mathmodel.MathModel) MathDescription(cbit.vcell.math.MathDescription) Element(org.jdom.Element) PropertyVetoException(java.beans.PropertyVetoException) Geometry(cbit.vcell.geometry.Geometry) OutputFunctionContext(cbit.vcell.solver.OutputFunctionContext) PropertyVetoException(java.beans.PropertyVetoException) Simulation(cbit.vcell.solver.Simulation) Version(org.vcell.util.document.Version) RedistributionVersion(cbit.vcell.solvers.mb.MovingBoundarySolverOptions.RedistributionVersion) SimulationVersion(org.vcell.util.document.SimulationVersion) VCellSoftwareVersion(org.vcell.util.document.VCellSoftwareVersion) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Example 7 with AnnotatedFunction

use of cbit.vcell.solver.AnnotatedFunction in project vcell by virtualcell.

the class XmlReader method getOutputFunctions.

public ArrayList<AnnotatedFunction> getOutputFunctions(Element outputFunctionsElement) throws XmlParseException {
    Iterator<Element> outputFnsIterator = outputFunctionsElement.getChildren(XMLTags.AnnotatedFunctionTag, vcNamespace).iterator();
    ArrayList<AnnotatedFunction> outputFunctions = new ArrayList<AnnotatedFunction>();
    while (outputFnsIterator.hasNext()) {
        org.jdom.Element observableElement = (Element) outputFnsIterator.next();
        AnnotatedFunction func = getOutputFunction(observableElement);
        outputFunctions.add(func);
    }
    return (outputFunctions);
}
Also used : Element(org.jdom.Element) ArrayList(java.util.ArrayList) Element(org.jdom.Element) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Example 8 with AnnotatedFunction

use of cbit.vcell.solver.AnnotatedFunction 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;
    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.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);
    }
    // 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 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);
        }
    }
    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;
}
Also used : MathDescription(cbit.vcell.math.MathDescription) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) Version(org.vcell.util.document.Version) RedistributionVersion(cbit.vcell.solvers.mb.MovingBoundarySolverOptions.RedistributionVersion) SimulationVersion(org.vcell.util.document.SimulationVersion) VCellSoftwareVersion(org.vcell.util.document.VCellSoftwareVersion) SpatialProcess(cbit.vcell.mapping.spatial.processes.SpatialProcess) RateRule(cbit.vcell.mapping.RateRule) Vector(java.util.Vector) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Electrode(cbit.vcell.mapping.Electrode) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ReactionRuleSpec(cbit.vcell.mapping.ReactionRuleSpec) LinkedList(java.util.LinkedList) PropertyVetoException(java.beans.PropertyVetoException) OutputFunctionContext(cbit.vcell.solver.OutputFunctionContext) FieldDataSymbol(cbit.vcell.data.FieldDataSymbol) DataSymbol(cbit.vcell.data.DataSymbol) ParameterEstimationTask(cbit.vcell.modelopt.ParameterEstimationTask) AnalysisTask(cbit.vcell.modelopt.AnalysisTask) NetworkConstraints(org.vcell.model.rbm.NetworkConstraints) GeometryClass(cbit.vcell.geometry.GeometryClass) Element(org.jdom.Element) StructureMapping(cbit.vcell.mapping.StructureMapping) SpatialObject(cbit.vcell.mapping.spatial.SpatialObject) DataContext(cbit.vcell.data.DataContext) SimulationContext(cbit.vcell.mapping.SimulationContext) SimulationContextParameter(cbit.vcell.mapping.SimulationContext.SimulationContextParameter) GeometryException(cbit.vcell.geometry.GeometryException) MathFormatException(cbit.vcell.math.MathFormatException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) DataConversionException(org.jdom.DataConversionException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) Geometry(cbit.vcell.geometry.Geometry) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) BioEvent(cbit.vcell.mapping.BioEvent) Element(org.jdom.Element)

Example 9 with AnnotatedFunction

use of cbit.vcell.solver.AnnotatedFunction in project vcell by virtualcell.

the class Xmlproducer method getXML.

/**
 * This method returns a XML representation of a SimulationContext object.
 * Creation date: (2/22/2001 2:15:14 PM)
 * @return Element
 * @param param cbit.vcell.mapping.SimulationContext
 */
public Element getXML(SimulationContext param, BioModel bioModel) throws XmlParseException {
    SimulationContext.Application applicationType = param.getApplicationType();
    Element simulationcontext = new Element(XMLTags.SimulationSpecTag);
    // add attributes
    String name = mangle(param.getName());
    simulationcontext.setAttribute(XMLTags.NameAttrTag, name);
    // set isStoch, isUsingConcentration attributes
    if (applicationType == Application.NETWORK_STOCHASTIC) {
        simulationcontext.setAttribute(XMLTags.StochAttrTag, "true");
        setBooleanAttribute(simulationcontext, XMLTags.ConcentrationAttrTag, param.isUsingConcentration());
        // write out 'randomizeInitConditin' flag only if non-spatial stochastic simContext
        if (param.getGeometry().getDimension() == 0) {
            setBooleanAttribute(simulationcontext, XMLTags.RandomizeInitConditionTag, param.isRandomizeInitCondition());
        }
    } else {
        simulationcontext.setAttribute(XMLTags.StochAttrTag, "false");
        simulationcontext.setAttribute(XMLTags.ConcentrationAttrTag, "true");
    }
    final boolean ruleBased = param.getApplicationType() == SimulationContext.Application.RULE_BASED_STOCHASTIC;
    setBooleanAttribute(simulationcontext, XMLTags.RuleBasedAttrTag, ruleBased);
    if (ruleBased) {
        setBooleanAttribute(simulationcontext, XMLTags.ConcentrationAttrTag, param.isUsingConcentration());
        if (param.getGeometry().getDimension() == 0) {
            // we don't use it yet but we do propagate it
            setBooleanAttribute(simulationcontext, XMLTags.RandomizeInitConditionTag, param.isRandomizeInitCondition());
        }
    }
    setBooleanAttribute(simulationcontext, XMLTags.InsufficientIterationsTag, param.isInsufficientIterations());
    setBooleanAttribute(simulationcontext, XMLTags.InsufficientMaxMoleculesTag, param.isInsufficientMaxMolecules());
    NetworkConstraints constraints = param.getNetworkConstraints();
    if (constraints != null) {
        simulationcontext.addContent(getXML(constraints));
    }
    // add annotation
    if (param.getDescription() != null && param.getDescription().length() > 0) {
        Element annotationElem = new Element(XMLTags.AnnotationTag);
        annotationElem.setText(mangle(param.getDescription()));
        simulationcontext.addContent(annotationElem);
    }
    if (param.getCharacteristicSize() != null) {
        simulationcontext.setAttribute(XMLTags.CharacteristicSizeTag, param.getCharacteristicSize().toString());
    }
    // write Geometry (or GeometryRef???)
    try {
        simulationcontext.addContent(getXML(param.getGeometryContext().getGeometry()));
    } catch (XmlParseException e) {
        e.printStackTrace();
        throw new XmlParseException("A problem occurred when trying to process the geometry for the simulationContext " + name, e);
    }
    // write GeometryContext (geometric mapping)
    simulationcontext.addContent(getXML(param.getGeometryContext()));
    // write ReactionContext (parameter/variable mapping)
    simulationcontext.addContent(getXML(param.getReactionContext()));
    // check if there is anything to write first for the electrical context
    if (param.getElectricalStimuli().length == 1 || param.getGroundElectrode() != null) {
        // create ElectricalContext
        Element electricalElement = new Element(XMLTags.ElectricalContextTag);
        // Write the electrical stimuli
        if (param.getElectricalStimuli().length == 1) {
            // write clamp
            electricalElement.addContent(getXML(param.getElectricalStimuli(0)));
        // Element clampElem = new Element(XMLTags.ClampTag);
        // clampElem.addContent(getXML(param.getElectricalStimuli(0)));
        // if (param.getElectricalStimuli()[0] instanceof VoltageClampStimulus) {
        // //this is a VOLTAGE clamp
        // clampElem.setAttribute(XMLTags.TypeAttrTag, XMLTags.VoltageClampTag);
        // clampElem.setAttribute( XMLTags.NameAttrTag, this.mangle((param.getElectricalStimuli()[0]).getName()) );
        // String tempExp = this.mangleExpression( ((VoltageClampStimulus)param.getElectricalStimuli()[0]).getVoltageParameter().getExpression() );
        // clampElem.setAttribute(XMLTags.ExpressionAttrTag, tempExp);
        // //add probe-electrode
        // clampElem.addContent(getXML(param.getElectricalStimuli()[0].getElectrode()));
        // } else {
        // //this is a CURRENT clamp
        // clampElem.setAttribute(XMLTags.TypeAttrTag, XMLTags.CurrentClampTag);
        // clampElem.setAttribute( XMLTags.NameAttrTag, this.mangle((param.getElectricalStimuli()[0]).getName()) );
        // String tempExp = this.mangleExpression( ((CurrentClampStimulus)param.getElectricalStimuli()[0]).getCurrentParameter().getExpression() );
        // clampElem.setAttribute(XMLTags.ExpressionAttrTag, tempExp);
        // //add probe-electrode
        // clampElem.addContent(getXML(param.getElectricalStimuli()[0].getElectrode()));
        // }
        // electricalElement.addContent(clampElem);
        // 
        } else if (param.getElectricalStimuli().length > 1) {
            // **ONLY ONE ELECTRODE IS SUPPORTED RIGHT NOW!
            throw new IllegalArgumentException("More than one electrode is not supported!");
        }
        // Process the Ground electrode
        if (param.getGroundElectrode() != null) {
            // write the ground electrode
            electricalElement.addContent(getXML(param.getGroundElectrode()));
        }
        simulationcontext.addContent(electricalElement);
    }
    // Add Mathdescription (if present)
    if (param.getMathDescription() != null) {
        simulationcontext.addContent(getXML(param.getMathDescription()));
    }
    if (param.getOutputFunctionContext() != null) {
        ArrayList<AnnotatedFunction> outputFunctions = param.getOutputFunctionContext().getOutputFunctionsList();
        if (outputFunctions != null && outputFunctions.size() > 0) {
            // get output functions
            simulationcontext.addContent(getXML(outputFunctions));
        }
    }
    // Add Simulations to the simulationSpec
    if (bioModel != null) {
        cbit.vcell.solver.Simulation[] simulations = bioModel.getSimulations(param);
        for (int i = 0; simulations != null && i < simulations.length; i++) {
            simulationcontext.addContent(getXML(simulations[i]));
        }
    }
    // Add AnalysisTasks
    if (param.getAnalysisTasks() != null && param.getAnalysisTasks().length > 0) {
        // if the task is empty (no parameters set up, no reference data), we shall not save it
        if (param.getAnalysisTasks().length == 1) {
            AnalysisTask task = param.getAnalysisTasks()[0];
            if (task instanceof ParameterEstimationTask) {
                if (!((ParameterEstimationTask) task).isEmpty()) {
                    simulationcontext.addContent(getXML(param.getAnalysisTasks()));
                }
            }
        } else // have more than one analysis task
        {
            simulationcontext.addContent(getXML(param.getAnalysisTasks()));
        }
    }
    // Add (Bio)events
    BioEvent[] bioEvents = param.getBioEvents();
    if (bioEvents != null && bioEvents.length > 0) {
        simulationcontext.addContent(getXML(bioEvents));
    }
    SimulationContextParameter[] appParams = param.getSimulationContextParameters();
    if (appParams != null && appParams.length > 0) {
        simulationcontext.addContent(getXML(appParams));
    }
    SpatialObject[] spatialObjects = param.getSpatialObjects();
    if (spatialObjects != null && spatialObjects.length > 0) {
        simulationcontext.addContent(getXML(spatialObjects));
    }
    SpatialProcess[] spatialProcesses = param.getSpatialProcesses();
    if (spatialProcesses != null && spatialProcesses.length > 0) {
        simulationcontext.addContent(getXML(spatialProcesses));
    }
    // Add rate rules
    RateRule[] rateRules = param.getRateRules();
    if (param.getRateRules() != null && rateRules.length > 0) {
        simulationcontext.addContent(getXML(rateRules));
    }
    // Add Datacontext
    if (param.getDataContext() != null && param.getDataContext().getDataSymbols().length > 0) {
        simulationcontext.addContent(getXML(param.getDataContext(), param.getModel().getUnitSystem()));
    }
    // Add Metadata (if any)
    if (param.getVersion() != null) {
        simulationcontext.addContent(getXML(param.getVersion(), param));
    }
    // Add microscope measurements
    simulationcontext.addContent(getXML(param.getMicroscopeMeasurement()));
    return simulationcontext;
}
Also used : Element(org.jdom.Element) SpatialObject(cbit.vcell.mapping.spatial.SpatialObject) SpatialProcess(cbit.vcell.mapping.spatial.processes.SpatialProcess) RateRule(cbit.vcell.mapping.RateRule) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Application(cbit.vcell.mapping.SimulationContext.Application) SimulationContext(cbit.vcell.mapping.SimulationContext) SimulationContextParameter(cbit.vcell.mapping.SimulationContext.SimulationContextParameter) ParameterEstimationTask(cbit.vcell.modelopt.ParameterEstimationTask) Simulation(cbit.vcell.solver.Simulation) AnalysisTask(cbit.vcell.modelopt.AnalysisTask) BioEvent(cbit.vcell.mapping.BioEvent) NetworkConstraints(org.vcell.model.rbm.NetworkConstraints)

Example 10 with AnnotatedFunction

use of cbit.vcell.solver.AnnotatedFunction in project vcell by virtualcell.

the class DataSetControllerImpl method adjustMembraneAdjacentVolumeValues.

private void adjustMembraneAdjacentVolumeValues(OutputContext outputContext, double[][] dataToAdjust, boolean bTimeFormat, SimDataBlock fullDataValueSource, int[] volumeDataIndexes, int[] membraneIndexesInOut, VCDataIdentifier vcdID, String varName, CartesianMesh mesh, TimeInfo timeInfo) throws Exception {
    if (membraneIndexesInOut == null || membraneIndexesInOut.length == 0) {
        return;
    }
    if (bTimeFormat) {
        if (dataToAdjust.length != volumeDataIndexes.length + 1 || dataToAdjust[0].length != timeInfo.desiredTimeValues.length) {
            throw new IllegalArgumentException(this.getClass().getName() + ".adjustMembraneAdjacentVolumeValues array format wrong for time flag=" + bTimeFormat);
        }
    } else {
        if (dataToAdjust.length != timeInfo.desiredTimeValues.length || dataToAdjust[0].length != volumeDataIndexes.length) {
            throw new IllegalArgumentException(this.getClass().getName() + ".adjustMembraneAdjacentVolumeValues array format wrong for time flag=" + bTimeFormat);
        }
    }
    boolean bIsSpecial = false;
    AnnotatedFunction insideFunction = null;
    AnnotatedFunction outsideFunction = null;
    VCData vcData = getVCData(vcdID);
    DataIdentifier[] myDataIdentifers = getDataIdentifiers(outputContext, vcdID);
    for (int i = 0; i < myDataIdentifers.length; i++) {
        if (myDataIdentifers[i].getName().equals(varName)) {
            if (myDataIdentifers[i].getVariableType().equals(VariableType.MEMBRANE)) {
                throw new IllegalArgumentException(this.getClass().getName() + ".adjustMembraneAdjacentVolumeValues Not for Membrane Variables");
            }
            Expression insideExp = null;
            Expression outsideExp = null;
            if (myDataIdentifers[i].isFunction()) {
                AnnotatedFunction sourceFunction = null;
                AnnotatedFunction[] functionsArr = getFunctions(outputContext, vcdID);
                for (int j = 0; j < functionsArr.length; j++) {
                    if (functionsArr[j].getName().equals(varName)) {
                        // need to subsitute and flatten the expression since we no longer store simplified expression.
                        if (vcData instanceof SimulationData) {
                            sourceFunction = ((SimulationData) vcData).simplifyFunction(functionsArr[j]);
                        } else {
                            throw new Exception("DataSetControllerImpl::getTimeSeriesValues_private(): has to be SimulationData to get time plot.");
                        }
                        break;
                    }
                }
                Vector<DataSetIdentifier> dependencyList = identifyDataDependencies(sourceFunction);
                insideExp = new Expression(sourceFunction.getExpression());
                outsideExp = new Expression(sourceFunction.getExpression());
                for (int j = 0; j < dependencyList.size(); j++) {
                    insideExp.substituteInPlace(new Expression(dependencyList.elementAt(j).getName()), new Expression(dependencyList.elementAt(j).getName() + InsideVariable.INSIDE_VARIABLE_SUFFIX));
                    outsideExp.substituteInPlace(new Expression(dependencyList.elementAt(j).getName()), new Expression(dependencyList.elementAt(j).getName() + OutsideVariable.OUTSIDE_VARIABLE_SUFFIX));
                }
            } else {
                insideExp = new Expression(varName + InsideVariable.INSIDE_VARIABLE_SUFFIX);
                outsideExp = new Expression(varName + OutsideVariable.OUTSIDE_VARIABLE_SUFFIX);
            }
            if (insideExp != null && outsideExp != null) {
                insideExp.bindExpression(vcData);
                outsideExp.bindExpression(vcData);
                // TODO domain
                Domain domain = null;
                insideFunction = new AnnotatedFunction("", insideExp, domain, "", VariableType.MEMBRANE, FunctionCategory.PREDEFINED);
                outsideFunction = new AnnotatedFunction("", outsideExp, domain, "", VariableType.MEMBRANE, FunctionCategory.PREDEFINED);
                insideFunction.setExpression(insideExp.flatten());
                outsideFunction.setExpression(outsideExp.flatten());
                FieldFunctionArguments[] insideExpFieldFunctionArgs = FieldUtilities.getFieldFunctionArguments(insideExp);
                FieldFunctionArguments[] outsideExpFieldFunctionArgs = FieldUtilities.getFieldFunctionArguments(outsideExp);
                bIsSpecial = !isAllowOptimizedTimeDataRetrieval() || hasGradient(insideExp) || hasGradient(outsideExp) || (insideExpFieldFunctionArgs != null && insideExpFieldFunctionArgs.length > 0) || (outsideExpFieldFunctionArgs != null && outsideExpFieldFunctionArgs.length > 0);
                if (bIsSpecial && fullDataValueSource == null) {
                    throw new IllegalArgumentException(this.getClass().getName() + ".adjustMembraneAdjacentVolumeValues: special values need SimDataBlock");
                }
            }
            break;
        }
    }
    int crossingCount = 0;
    for (int j = 0; j < membraneIndexesInOut.length; j++) {
        if (membraneIndexesInOut[j] != -1) {
            crossingCount += 1;
        }
    }
    if (crossingCount > 0) {
        int[] crossingCondensedIndexes = new int[crossingCount];
        int[] crossingCondensedOrigLocation = new int[crossingCount];
        crossingCount = 0;
        for (int j = 0; j < membraneIndexesInOut.length; j++) {
            if (membraneIndexesInOut[j] != -1) {
                crossingCondensedOrigLocation[crossingCount] = j;
                crossingCondensedIndexes[crossingCount] = membraneIndexesInOut[j];
                crossingCount += 1;
            }
        }
        MultiFunctionIndexes mfi_inside = null;
        MultiFunctionIndexes mfi_outside = null;
        for (int j = 0; j < crossingCount; j++) {
            double specialInsideVal = (bIsSpecial ? interpolateVolDataValToMemb(mesh, crossingCondensedIndexes[j], fullDataValueSource, true, false) : 0);
            double specialOutsideVal = (bIsSpecial ? interpolateVolDataValToMemb(mesh, crossingCondensedIndexes[j], fullDataValueSource, false, false) : 0);
            VolumeIndexNearFar vinf_inside = interpolateFindNearFarIndex(mesh, crossingCondensedIndexes[j], true, false);
            VolumeIndexNearFar vinf_outside = interpolateFindNearFarIndex(mesh, crossingCondensedIndexes[j], false, false);
            if (vinf_inside.volIndexNear == volumeDataIndexes[crossingCondensedOrigLocation[j]]) {
                if (!bIsSpecial && mfi_inside == null) {
                    mfi_inside = new MultiFunctionIndexes(vcdID, insideFunction, crossingCondensedIndexes, timeInfo.wantsTheseTimes, null, outputContext);
                }
                for (int k = 0; k < timeInfo.desiredTimeValues.length; k++) {
                    if (bTimeFormat) {
                        dataToAdjust[crossingCondensedOrigLocation[j] + 1][k] = (bIsSpecial ? specialInsideVal : mfi_inside.evaluateTimeFunction(outputContext, k, j));
                    } else {
                        dataToAdjust[k][crossingCondensedOrigLocation[j]] = (bIsSpecial ? specialInsideVal : mfi_inside.evaluateTimeFunction(outputContext, k, j));
                    }
                }
            } else if (vinf_outside.volIndexNear == volumeDataIndexes[crossingCondensedOrigLocation[j]]) {
                if (!bIsSpecial && mfi_outside == null) {
                    mfi_outside = new MultiFunctionIndexes(vcdID, outsideFunction, crossingCondensedIndexes, timeInfo.wantsTheseTimes, null, outputContext);
                }
                for (int k = 0; k < timeInfo.desiredTimeValues.length; k++) {
                    if (bTimeFormat) {
                        dataToAdjust[crossingCondensedOrigLocation[j] + 1][k] = (bIsSpecial ? specialOutsideVal : mfi_outside.evaluateTimeFunction(outputContext, k, j));
                    } else {
                        dataToAdjust[k][crossingCondensedOrigLocation[j]] = (bIsSpecial ? specialOutsideVal : mfi_outside.evaluateTimeFunction(outputContext, k, j));
                    }
                }
            } else {
                throw new Exception("couldn't match 'near' indexes");
            }
        }
    } else {
        throw new IllegalArgumentException("No non-null membrane crossing indexes found");
    }
}
Also used : VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) CacheException(org.vcell.util.CacheException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) FileNotFoundException(java.io.FileNotFoundException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) Expression(cbit.vcell.parser.Expression) VariableDomain(cbit.vcell.math.VariableType.VariableDomain) Domain(cbit.vcell.math.Variable.Domain) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction)

Aggregations

AnnotatedFunction (cbit.vcell.solver.AnnotatedFunction)61 DataAccessException (org.vcell.util.DataAccessException)21 ExpressionException (cbit.vcell.parser.ExpressionException)20 Expression (cbit.vcell.parser.Expression)17 ArrayList (java.util.ArrayList)17 Simulation (cbit.vcell.solver.Simulation)15 IOException (java.io.IOException)15 OutputContext (cbit.vcell.simdata.OutputContext)14 MathException (cbit.vcell.math.MathException)12 VCDataIdentifier (org.vcell.util.document.VCDataIdentifier)12 SimulationContext (cbit.vcell.mapping.SimulationContext)11 ExpressionBindingException (cbit.vcell.parser.ExpressionBindingException)10 DataIdentifier (cbit.vcell.simdata.DataIdentifier)9 VCSimulationDataIdentifier (cbit.vcell.solver.VCSimulationDataIdentifier)9 FileNotFoundException (java.io.FileNotFoundException)8 Domain (cbit.vcell.math.Variable.Domain)7 VariableType (cbit.vcell.math.VariableType)7 XmlParseException (cbit.vcell.xml.XmlParseException)7 PropertyVetoException (java.beans.PropertyVetoException)7 File (java.io.File)7