Search in sources :

Example 11 with VCUnitDefinition

use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.

the class VCUnitEvaluator method suggestUnitDefinitions.

public VCUnitDefinition[] suggestUnitDefinitions(SymbolTableEntry[] symbolTableEntries) throws ExpressionException, VCUnitException {
    // 
    // initialize to already known units
    // 
    UnitsHashMap unitsHashMap = new UnitsHashMap();
    for (int i = 0; i < symbolTableEntries.length; i++) {
        unitsHashMap.put(symbolTableEntries[i], symbolTableEntries[i].getUnitDefinition());
    }
    // 
    while (unitsHashMap.getDirty()) {
        unitsHashMap.clearDirty();
        for (int i = 0; i < symbolTableEntries.length; i++) {
            Expression exp = symbolTableEntries[i].getExpression();
            if (exp != null) {
                VCUnitDefinition vcUnitDefinition = (VCUnitDefinition) unitsHashMap.get(symbolTableEntries[i]);
                if (vcUnitDefinition == null) {
                    vcUnitDefinition = getUnitDefinition(exp.getRootNode(), unitsHashMap);
                    unitsHashMap.put(symbolTableEntries[i], vcUnitDefinition);
                }
                assignAndVerify(vcUnitDefinition, exp.flatten().getRootNode(), unitsHashMap);
            }
        }
    }
    // 
    // return array
    // 
    VCUnitDefinition[] unitDefinitions = new VCUnitDefinition[symbolTableEntries.length];
    for (int i = 0; i < symbolTableEntries.length; i++) {
        unitDefinitions[i] = unitsHashMap.get(symbolTableEntries[i]);
    }
    return unitDefinitions;
}
Also used : VCUnitDefinition(cbit.vcell.units.VCUnitDefinition)

Example 12 with VCUnitDefinition

use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.

the class VCUnitEvaluator method assignAndVerify.

private void assignAndVerify(VCUnitDefinition nodeUnit, SimpleNode node, UnitsHashMap unitsHashMap) throws ExpressionException {
    if (node == null) {
        throw new RuntimeException("VCUnitEvaluator.assignAndVerify(): node is null");
    }
    if (nodeUnit == null) {
        throw new RuntimeException("VCUnitEvaluator.assignAndVerify(): nodeUnit is null");
    }
    // 
    if (node instanceof ASTAndNode || node instanceof ASTOrNode || node instanceof ASTNotNode) {
        for (int i = 0; i < node.jjtGetNumChildren(); i++) {
            assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(i), unitsHashMap);
        }
    } else if (node instanceof ASTRelationalNode) {
        // 
        // if either child has known unit, then other must also be known
        // 
        SimpleNode child0 = (SimpleNode) node.jjtGetChild(0);
        SimpleNode child1 = (SimpleNode) node.jjtGetChild(1);
        VCUnitDefinition unit0 = getUnitDefinition(child0, unitsHashMap);
        VCUnitDefinition unit1 = getUnitDefinition(child1, unitsHashMap);
        if (unit0.isTBD() && unit1.isTBD()) {
            assignAndVerify(unitSystem.getInstance_TBD(), child0, unitsHashMap);
            assignAndVerify(unitSystem.getInstance_TBD(), child1, unitsHashMap);
            return;
        } else if (unit0.isTBD()) {
            assignAndVerify(unit1, child0, unitsHashMap);
            return;
        } else if (unit1.isTBD()) {
            assignAndVerify(unit0, child1, unitsHashMap);
            return;
        } else if (!unit0.isEquivalent(unit1)) {
            throw new RuntimeException("operands of a relational operator are not same [" + unit0.getSymbol() + "] and [" + unit1.getSymbol() + "]");
        } else {
            assignAndVerify(unit0, child0, unitsHashMap);
            assignAndVerify(unit0, child1, unitsHashMap);
        }
    } else if (node instanceof ASTAddNode || node instanceof ASTMinusTermNode) {
        for (int i = 0; i < node.jjtGetNumChildren(); i++) {
            assignAndVerify(nodeUnit, (SimpleNode) node.jjtGetChild(i), unitsHashMap);
        }
    } else if (node instanceof ASTMultNode) {
        if (node.jjtGetNumChildren() == 1) {
            assignAndVerify(nodeUnit, (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        } else {
            // 
            // product of children should be that of parent (tough one)
            // ... can only resolve if only one unknown
            // 
            SimpleNode unknownChildNode = null;
            int unknownChildCount = 0;
            int constantChildCount = 0;
            VCUnitDefinition accumUnit = nodeUnit;
            for (int i = 0; i < node.jjtGetNumChildren(); i++) {
                SimpleNode child = (SimpleNode) node.jjtGetChild(i);
                VCUnitDefinition childUnit = getUnitDefinition(child, unitsHashMap);
                assignAndVerify(childUnit, child, unitsHashMap);
                if (childUnit.isTBD()) {
                    // 
                    // ignore those that evaluate to a constant
                    // 
                    boolean bConstant = false;
                    try {
                        child.evaluateConstant();
                        bConstant = true;
                    } catch (ExpressionException e) {
                    }
                    if (!bConstant) {
                        unknownChildNode = child;
                        unknownChildCount++;
                    } else {
                        constantChildCount++;
                    }
                } else {
                    if (!accumUnit.isTBD()) {
                        accumUnit = accumUnit.divideBy(childUnit);
                    }
                }
            }
            if (unknownChildCount == 0 && constantChildCount == 0) {
                // should cancel to dimensionless, but if constant children (numbers...) are used in a product, then can assume appropriate units.
                if (!accumUnit.isEquivalent(unitSystem.getInstance_DIMENSIONLESS())) {
                    // accumUnit.compareEquals(unitSystem.getInstance_DIMENSIONLESS());
                    throw new RuntimeException("expression '" + node.infixString(SimpleNode.LANGUAGE_DEFAULT) + "' missing factor of '" + accumUnit.getSymbol() + "'");
                }
            } else if (unknownChildCount == 1) {
                // 
                if (!accumUnit.isTBD()) {
                    assignAndVerify(accumUnit, unknownChildNode, unitsHashMap);
                }
            }
        }
    } else if (node instanceof ASTInvertTermNode) {
        SimpleNode child = (SimpleNode) node.jjtGetChild(0);
        if (nodeUnit.isTBD()) {
            assignAndVerify(nodeUnit, child, unitsHashMap);
        } else {
            assignAndVerify(nodeUnit.getInverse(), child, unitsHashMap);
        }
    // } else if (node instanceof DerivativeNode) {
    // unit = getUnitDefinition((SimpleNode)node.jjtGetChild(1),unitsHashMap);
    // return getUnitDefinition((SimpleNode)node.jjtGetChild(0),unitsHashMap).divideBy(unit);
    // } else if (node instanceof ASTLaplacianNode) {
    // unit = ReservedSymbol.X.getUnitDefinition();
    // return getUnitDefinition((SimpleNode)node.jjtGetChild(0),unitsHashMap).divideBy(unit).divideBy(unit);
    } else if (node instanceof ASTFloatNode) {
    // return TBD instead of dimensionless.
    // do nothing
    } else if (node instanceof ASTFuncNode) {
        String functionName = ((ASTFuncNode) node).getName();
        if (functionName.equalsIgnoreCase("sqrt")) {
            // ?
            assignAndVerify(nodeUnit.raiseTo(new RationalNumber(2)), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        } else if (functionName.equalsIgnoreCase("exp")) {
            // ?
            assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        } else if (functionName.equalsIgnoreCase("pow")) {
            // later....
            // exponent should always be dimensionless
            assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(1), unitsHashMap);
            // 
            try {
                double exponentValue = ((SimpleNode) node.jjtGetChild(1)).evaluateConstant();
                if (!nodeUnit.isTBD()) {
                    RationalNumber rn = RationalNumber.getApproximateFraction(exponentValue);
                    // exponent should always be dimensionless
                    assignAndVerify(nodeUnit.raiseTo(rn.inverse()), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
                }
            } catch (ExpressionException e) {
                // 
                // a^b where b not constant, a must be non-dimensional
                // 
                // exponent should always be dimensionless
                assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
            }
        } else if (functionName.equalsIgnoreCase("abs") || functionName.equalsIgnoreCase("min") || functionName.equalsIgnoreCase("max")) {
            // 
            for (int i = 0; i < node.jjtGetNumChildren(); i++) {
                assignAndVerify(nodeUnit, (SimpleNode) node.jjtGetChild(i), unitsHashMap);
            }
        } else {
            if (!nodeUnit.isEquivalent(unitSystem.getInstance_DIMENSIONLESS())) {
                throw new RuntimeException("function '" + functionName + "' should be dimensionless, assignAndVerify trying to impose '" + nodeUnit.getSymbol());
            }
            // 
            // child should be dimensionless
            // 
            assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        }
    } else if (node instanceof ASTPowerNode) {
        // exponent should always be dimensionless
        assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(1), unitsHashMap);
        // 
        try {
            double exponentValue = ((SimpleNode) node.jjtGetChild(1)).evaluateConstant();
            RationalNumber rn = RationalNumber.getApproximateFraction(exponentValue);
            // exponent should always be dimensionless
            assignAndVerify(nodeUnit.raiseTo(rn.inverse()), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        } catch (ExpressionException e) {
            // 
            // a^b where b not constant, a must be non-dimensional
            // 
            // exponent should always be dimensionless
            assignAndVerify(unitSystem.getInstance_DIMENSIONLESS(), (SimpleNode) node.jjtGetChild(0), unitsHashMap);
        }
    } else if (node instanceof ASTIdNode) {
        if (!nodeUnit.isTBD()) {
            unitsHashMap.put(((ASTIdNode) node).symbolTableEntry, nodeUnit);
        }
    } else {
        throw new ExpressionException("node type " + node.getClass().toString() + " not supported yet");
    }
}
Also used : VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) RationalNumber(ucar.units_vcell.RationalNumber)

Example 13 with VCUnitDefinition

use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.

the class XmlReader method getBioEvents.

public BioEvent[] getBioEvents(SimulationContext simContext, Element bioEventsElement) throws XmlParseException {
    Iterator<Element> bioEventsIterator = bioEventsElement.getChildren(XMLTags.BioEventTag, vcNamespace).iterator();
    Vector<BioEvent> bioEventsVector = new Vector<BioEvent>();
    while (bioEventsIterator.hasNext()) {
        Element bEventElement = (Element) bioEventsIterator.next();
        BioEvent newBioEvent = null;
        String name = unMangle(bEventElement.getAttributeValue(XMLTags.NameAttrTag));
        Element triggerElement = bEventElement.getChild(XMLTags.TriggerTag, vcNamespace);
        if (triggerElement != null && triggerElement.getText().length() > 0) {
            // 
            // read legacy VCell 5.3 style trigger and delay elements
            // 
            // <Trigger>(t>3.0)</Trigger>
            // <Delay UseValuesFromTriggerTime="true">3.0</Delay>     [optional]
            // 
            Expression triggerExpression = unMangleExpression(triggerElement.getText());
            // read <Delay>
            Expression delayDurationExpression = null;
            boolean useValuesFromTriggerTime = true;
            Element delayElement = bEventElement.getChild(XMLTags.DelayTag, vcNamespace);
            if (delayElement != null) {
                useValuesFromTriggerTime = Boolean.valueOf(delayElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag)).booleanValue();
                delayDurationExpression = unMangleExpression((delayElement.getText()));
            }
            newBioEvent = new BioEvent(name, TriggerType.GeneralTrigger, useValuesFromTriggerTime, simContext);
            try {
                newBioEvent.setParameterValue(BioEventParameterType.GeneralTriggerFunction, triggerExpression);
                if (delayDurationExpression != null) {
                    newBioEvent.setParameterValue(BioEventParameterType.TriggerDelay, delayDurationExpression);
                }
            } catch (ExpressionBindingException | PropertyVetoException e) {
                e.printStackTrace();
                throw new XmlParseException("failed to read trigger or delay expressions in bioEvent " + name + ": " + e.getMessage(), e);
            }
        } else if (triggerElement != null && triggerElement.getText().length() == 0) {
            // 
            // read legacy first-pass VCell 5.4 style trigger and delay elements
            // 
            // <Trigger>
            // <TriggerParameters triggerClass="TriggerGeneral">
            // (t > 500.0)
            // </TriggerParameters>
            // </Trigger>
            // <Delay UseValuesFromTriggerTime="true">3.0</Delay>     [optional]
            // 
            final String TriggerParametersTag = "TriggerParameters";
            final String TriggerClassAttrTag = "triggerClass";
            final String TriggerClassAttrValue_TriggerGeneral = "TriggerGeneral";
            Element triggerParametersElement = triggerElement.getChild(TriggerParametersTag, vcNamespace);
            Expression triggerExpression = null;
            String triggerClass = triggerParametersElement.getAttributeValue(TriggerClassAttrTag);
            if (triggerClass.equals(TriggerClassAttrValue_TriggerGeneral)) {
                triggerExpression = unMangleExpression(triggerParametersElement.getText());
            } else {
                // not general trigger (just make it never happen, user will have to edit "t > -1")
                triggerExpression = Expression.relational(">", new Expression(simContext.getModel().getTIME(), simContext.getModel().getNameScope()), new Expression(-1.0));
            }
            // read <Delay>
            Expression delayDurationExpression = null;
            boolean useValuesFromTriggerTime = true;
            Element delayElement = bEventElement.getChild(XMLTags.DelayTag, vcNamespace);
            if (delayElement != null) {
                useValuesFromTriggerTime = Boolean.valueOf(delayElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag)).booleanValue();
                delayDurationExpression = unMangleExpression((delayElement.getText()));
            }
            newBioEvent = new BioEvent(name, TriggerType.GeneralTrigger, useValuesFromTriggerTime, simContext);
            try {
                newBioEvent.setParameterValue(BioEventParameterType.GeneralTriggerFunction, triggerExpression);
                if (delayDurationExpression != null) {
                    newBioEvent.setParameterValue(BioEventParameterType.TriggerDelay, delayDurationExpression);
                }
            } catch (ExpressionBindingException | PropertyVetoException e) {
                e.printStackTrace();
                throw new XmlParseException("failed to read trigger or delay expressions in bioEvent " + name + ": " + e.getMessage(), e);
            }
        } else {
            // 
            // VCell 5.4 style bioevent parameters
            // 
            // 
            TriggerType triggerType = TriggerType.fromXmlName(bEventElement.getAttributeValue(XMLTags.BioEventTriggerTypeAttrTag));
            boolean bUseValuesFromTriggerTime = Boolean.parseBoolean(bEventElement.getAttributeValue(XMLTags.UseValuesFromTriggerTimeAttrTag));
            newBioEvent = new BioEvent(name, triggerType, bUseValuesFromTriggerTime, simContext);
            Iterator<Element> paramElementIter = bEventElement.getChildren(XMLTags.ParameterTag, vcNamespace).iterator();
            ArrayList<LocalParameter> parameters = new ArrayList<LocalParameter>();
            boolean bHasGeneralTriggerParam = false;
            while (paramElementIter.hasNext()) {
                Element paramElement = paramElementIter.next();
                // Get parameter attributes
                String paramName = paramElement.getAttributeValue(XMLTags.NameAttrTag);
                Expression exp = unMangleExpression(paramElement.getText());
                String roleStr = paramElement.getAttributeValue(XMLTags.ParamRoleAttrTag);
                BioEventParameterType parameterType = BioEventParameterType.fromRoleXmlName(roleStr);
                if (parameterType == BioEventParameterType.GeneralTriggerFunction) {
                    bHasGeneralTriggerParam = true;
                }
                VCUnitDefinition unit = simContext.getModel().getUnitSystem().getInstance_TBD();
                String unitSymbol = paramElement.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
                if (unitSymbol != null) {
                    unit = simContext.getModel().getUnitSystem().getInstance(unitSymbol);
                }
                parameters.add(newBioEvent.createNewParameter(paramName, parameterType, exp, unit));
            }
            if (!bHasGeneralTriggerParam) {
                parameters.add(newBioEvent.createNewParameter(BioEventParameterType.GeneralTriggerFunction.getDefaultName(), BioEventParameterType.GeneralTriggerFunction, // computed as needed
                null, simContext.getModel().getUnitSystem().getInstance_DIMENSIONLESS()));
            }
            try {
                newBioEvent.setParameters(parameters.toArray(new LocalParameter[0]));
            } catch (PropertyVetoException | ExpressionBindingException e) {
                e.printStackTrace();
                throw new XmlParseException("failed to read parameters in bioEvent " + name + ": " + e.getMessage(), e);
            }
        }
        ArrayList<BioEvent.EventAssignment> eventAssignmentList = new ArrayList<BioEvent.EventAssignment>();
        Iterator<Element> iter = bEventElement.getChildren(XMLTags.EventAssignmentTag, vcNamespace).iterator();
        while (iter.hasNext()) {
            Element eventAssignmentElement = iter.next();
            try {
                String varname = eventAssignmentElement.getAttributeValue(XMLTags.EventAssignmentVariableAttrTag);
                Expression assignExp = unMangleExpression(eventAssignmentElement.getText());
                SymbolTableEntry target = simContext.getEntry(varname);
                BioEvent.EventAssignment eventAssignment = newBioEvent.new EventAssignment(target, assignExp);
                eventAssignmentList.add(eventAssignment);
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
        }
        try {
            newBioEvent.setEventAssignmentsList(eventAssignmentList);
        } catch (PropertyVetoException e1) {
            e1.printStackTrace(System.out);
            throw new XmlParseException(e1);
        }
        try {
            newBioEvent.bind();
        } catch (ExpressionBindingException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
        bioEventsVector.add(newBioEvent);
    }
    return ((BioEvent[]) BeanUtils.getArray(bioEventsVector, BioEvent.class));
}
Also used : TriggerType(cbit.vcell.mapping.BioEvent.TriggerType) EventAssignment(cbit.vcell.math.Event.EventAssignment) Element(org.jdom.Element) ArrayList(java.util.ArrayList) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Expression(cbit.vcell.parser.Expression) BioEventParameterType(cbit.vcell.mapping.BioEvent.BioEventParameterType) Iterator(java.util.Iterator) BioEvent(cbit.vcell.mapping.BioEvent) Vector(java.util.Vector)

Example 14 with VCUnitDefinition

use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.

the class XmlReader method readParameters.

private void readParameters(List<Element> parameterElements, ParameterContext parameterContext, HashMap<String, ParameterRoleEnum> roleHash, ParameterRoleEnum userDefinedRole, HashSet<String> xmlRolesTagsToIgnore, Model model) throws XmlParseException {
    String contextName = parameterContext.getNameScope().getName();
    try {
        // 
        // prepopulate varHash with reserved symbols
        // 
        VariableHash varHash = new VariableHash();
        addResevedSymbols(varHash, model);
        // 
        for (Element xmlParam : parameterElements) {
            String parsedParamName = unMangle(xmlParam.getAttributeValue(XMLTags.NameAttrTag));
            String parsedRoleString = xmlParam.getAttributeValue(XMLTags.ParamRoleAttrTag);
            String parsedExpressionString = xmlParam.getText();
            // 
            if (xmlRolesTagsToIgnore.contains(parsedRoleString)) {
                varHash.removeVariable(parsedParamName);
                continue;
            }
            Expression paramExp = null;
            if (parsedExpressionString.trim().length() > 0) {
                paramExp = unMangleExpression(parsedExpressionString);
            }
            if (varHash.getVariable(parsedParamName) == null) {
                Domain domain = null;
                varHash.addVariable(new Function(parsedParamName, paramExp, domain));
            } else {
                if (model.getReservedSymbolByName(parsedParamName) != null) {
                    varHash.removeVariable(parsedParamName);
                    Domain domain = null;
                    varHash.addVariable(new Function(parsedParamName, paramExp, domain));
                }
            }
            // 
            // get the parameter for this xml role string
            // 
            ParameterRoleEnum paramRole = roleHash.get(parsedRoleString);
            if (paramRole == null) {
                throw new XmlParseException("parameter '" + parsedParamName + "' has unexpected role '" + parsedRoleString + "' in '" + contextName + "'");
            }
            // 
            if (paramRole != userDefinedRole) {
                LocalParameter paramWithSameRole = parameterContext.getLocalParameterFromRole(paramRole);
                if (paramWithSameRole == null) {
                    throw new XmlParseException("can't find parameter with role '" + parsedRoleString + "' in '" + contextName + "'");
                }
                // 
                if (!paramWithSameRole.getName().equals(parsedParamName)) {
                    // 
                    // first rename other parameters with same name
                    // 
                    LocalParameter paramWithSameNameButDifferentRole = parameterContext.getLocalParameterFromName(parsedParamName);
                    if (paramWithSameNameButDifferentRole != null) {
                        // 
                        // find available name
                        // 
                        int n = 0;
                        String newName = parsedParamName + "_" + n++;
                        while (parameterContext.getEntry(newName) != null) {
                            newName = parsedParamName + "_" + n++;
                        }
                        parameterContext.renameLocalParameter(parsedParamName, newName);
                    }
                    // 
                    // then rename parameter with correct role
                    // 
                    parameterContext.renameLocalParameter(paramWithSameRole.getName(), parsedParamName);
                }
            }
        }
        // 
        // create unresolved parameters for all unresolved symbols
        // 
        String unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        while (unresolvedSymbol != null) {
            try {
                Domain domain = null;
                // will turn into an UnresolvedParameter.
                varHash.addVariable(new Function(unresolvedSymbol, new Expression(0.0), domain));
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e.getMessage());
            }
            parameterContext.addUnresolvedParameter(unresolvedSymbol);
            unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        }
        // 
        // in topological order, add parameters to model (getting units also).
        // note that all pre-defined parameters already have the correct names
        // here we set expressions on pre-defined parameters and add user-defined parameters
        // 
        Variable[] sortedVariables = varHash.getTopologicallyReorderedVariables();
        ModelUnitSystem modelUnitSystem = model.getUnitSystem();
        for (int i = sortedVariables.length - 1; i >= 0; i--) {
            if (sortedVariables[i] instanceof Function) {
                Function paramFunction = (Function) sortedVariables[i];
                Element xmlParam = null;
                for (int j = 0; j < parameterElements.size(); j++) {
                    Element tempParam = (Element) parameterElements.get(j);
                    if (paramFunction.getName().equals(unMangle(tempParam.getAttributeValue(XMLTags.NameAttrTag)))) {
                        xmlParam = tempParam;
                        break;
                    }
                }
                if (xmlParam == null) {
                    // must have been an unresolved parameter
                    continue;
                }
                String symbol = xmlParam.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
                VCUnitDefinition unit = null;
                if (symbol != null) {
                    unit = modelUnitSystem.getInstance(symbol);
                }
                LocalParameter tempParam = parameterContext.getLocalParameterFromName(paramFunction.getName());
                if (tempParam == null) {
                    tempParam = parameterContext.addLocalParameter(paramFunction.getName(), new Expression(0.0), userDefinedRole, unit, userDefinedRole.getDescription());
                    parameterContext.setParameterValue(tempParam, paramFunction.getExpression(), true);
                } else {
                    if (tempParam.getExpression() != null) {
                        // if the expression is null, it should remain null.
                        parameterContext.setParameterValue(tempParam, paramFunction.getExpression(), true);
                    }
                    tempParam.setUnitDefinition(unit);
                }
            }
        }
    } catch (PropertyVetoException | ExpressionException | MathException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while setting parameters for '" + contextName + "': " + e.getMessage(), e);
    }
}
Also used : FilamentVariable(cbit.vcell.math.FilamentVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) RandomVariable(cbit.vcell.math.RandomVariable) VolumeRandomVariable(cbit.vcell.math.VolumeRandomVariable) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) VolVariable(cbit.vcell.math.VolVariable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) PointVariable(cbit.vcell.math.PointVariable) MembraneRandomVariable(cbit.vcell.math.MembraneRandomVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) Element(org.jdom.Element) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) PropertyVetoException(java.beans.PropertyVetoException) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) PointSubDomain(cbit.vcell.math.PointSubDomain) Domain(cbit.vcell.math.Variable.Domain) ParameterRoleEnum(cbit.vcell.mapping.ParameterContext.ParameterRoleEnum) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 15 with VCUnitDefinition

use of cbit.vcell.units.VCUnitDefinition in project vcell by virtualcell.

the class XmlReader method getElectricalStimulus.

/**
 * This method process Electrical Stimulus, also called Clamps.
 * Creation date: (6/6/2002 4:46:18 PM)
 * @return cbit.vcell.mapping.ElectricalStimulus
 * @param param org.jdom.Element
 */
private ElectricalStimulus getElectricalStimulus(Element param, SimulationContext currentSimulationContext) throws XmlParseException {
    ElectricalStimulus clampStimulus = null;
    // get name
    // String name = unMangle( param.getAttributeValue(XMLTags.NameAttrTag) );
    // get Electrode
    Electrode electrode = getElectrode(param.getChild(XMLTags.ElectrodeTag, vcNamespace), currentSimulationContext);
    if (param.getAttributeValue(XMLTags.TypeAttrTag).equalsIgnoreCase(XMLTags.VoltageClampTag)) {
        // is a voltage clamp
        clampStimulus = new VoltageClampStimulus(electrode, "voltClampElectrode", new Expression(0.0), currentSimulationContext);
    } else if (param.getAttributeValue(XMLTags.TypeAttrTag).equalsIgnoreCase(XMLTags.CurrentDensityClampTag) || param.getAttributeValue(XMLTags.TypeAttrTag).equalsIgnoreCase(XMLTags.CurrentDensityClampTag_oldName)) {
        // is a current density clamp
        clampStimulus = new CurrentDensityClampStimulus(electrode, "currDensityClampElectrode", new Expression(0.0), currentSimulationContext);
    } else if (param.getAttributeValue(XMLTags.TypeAttrTag).equalsIgnoreCase(XMLTags.TotalCurrentClampTag)) {
        // is a "total" current clamp
        clampStimulus = new TotalCurrentClampStimulus(electrode, "totalCurrClampElectrode", new Expression(0.0), currentSimulationContext);
    }
    try {
        // transaction begin flag ... yeah, this is a hack
        clampStimulus.reading(true);
        // Read all of the parameters
        List<Element> list = param.getChildren(XMLTags.ParameterTag, vcNamespace);
        // add constants that may be used in the electrical stimulus.
        VariableHash varHash = new VariableHash();
        Model model = currentSimulationContext.getModel();
        addResevedSymbols(varHash, model);
        // 
        for (Element xmlParam : list) {
            String paramName = unMangle(xmlParam.getAttributeValue(XMLTags.NameAttrTag));
            String role = xmlParam.getAttributeValue(XMLTags.ParamRoleAttrTag);
            String paramExpStr = xmlParam.getText();
            Expression paramExp = unMangleExpression(paramExpStr);
            try {
                if (varHash.getVariable(paramName) == null) {
                    Domain domain = null;
                    varHash.addVariable(new Function(paramName, paramExp, domain));
                } else {
                    if (model.getReservedSymbolByName(paramName) != null) {
                        varHash.removeVariable(paramName);
                        Domain domain = null;
                        varHash.addVariable(new Function(paramName, paramExp, domain));
                    }
                }
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException("error reordering parameters according to dependencies:", e);
            }
            LocalParameter tempParam = null;
            if (!role.equals(XMLTags.ParamRoleUserDefinedTag)) {
                if (role.equals(XMLTags.ParamRoleTotalCurrentTag)) {
                    if (clampStimulus instanceof TotalCurrentClampStimulus) {
                        tempParam = ((TotalCurrentClampStimulus) clampStimulus).getCurrentParameter();
                    } else {
                        varHash.removeVariable(paramName);
                        continue;
                    }
                } else if (role.equals(XMLTags.ParamRoleTotalCurrentDensityTag) || role.equals(XMLTags.ParamRoleTotalCurrentDensityOldNameTag)) {
                    if (clampStimulus instanceof CurrentDensityClampStimulus) {
                        tempParam = ((CurrentDensityClampStimulus) clampStimulus).getCurrentDensityParameter();
                    } else {
                        varHash.removeVariable(paramName);
                        continue;
                    }
                } else if (role.equals(XMLTags.ParamRolePotentialDifferenceTag)) {
                    if (clampStimulus instanceof VoltageClampStimulus) {
                        tempParam = ((VoltageClampStimulus) clampStimulus).getVoltageParameter();
                    } else {
                        varHash.removeVariable(paramName);
                        continue;
                    }
                }
            } else {
                continue;
            }
            if (tempParam == null) {
                throw new XmlParseException("parameter with role '" + role + "' not found in electricalstimulus");
            }
            // 
            if (!tempParam.getName().equals(paramName)) {
                LocalParameter multNameParam = clampStimulus.getLocalParameter(paramName);
                int n = 0;
                while (multNameParam != null) {
                    String tempName = paramName + "_" + n++;
                    clampStimulus.renameParameter(paramName, tempName);
                    multNameParam = clampStimulus.getLocalParameter(tempName);
                }
                clampStimulus.renameParameter(tempParam.getName(), paramName);
            }
        }
        // 
        // create unresolved parameters for all unresolved symbols
        // 
        String unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        while (unresolvedSymbol != null) {
            try {
                Domain domain = null;
                // will turn into an UnresolvedParameter.
                varHash.addVariable(new Function(unresolvedSymbol, new Expression(0.0), domain));
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e.getMessage());
            }
            clampStimulus.addUnresolvedParameter(unresolvedSymbol);
            unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        }
        Variable[] sortedVariables = varHash.getTopologicallyReorderedVariables();
        ModelUnitSystem modelUnitSystem = model.getUnitSystem();
        for (int i = sortedVariables.length - 1; i >= 0; i--) {
            if (sortedVariables[i] instanceof Function) {
                Function paramFunction = (Function) sortedVariables[i];
                Element xmlParam = null;
                for (int j = 0; j < list.size(); j++) {
                    Element tempParam = (Element) list.get(j);
                    if (paramFunction.getName().equals(unMangle(tempParam.getAttributeValue(XMLTags.NameAttrTag)))) {
                        xmlParam = tempParam;
                        break;
                    }
                }
                if (xmlParam == null) {
                    // must have been an unresolved parameter
                    continue;
                }
                String symbol = xmlParam.getAttributeValue(XMLTags.VCUnitDefinitionAttrTag);
                VCUnitDefinition unit = null;
                if (symbol != null) {
                    unit = modelUnitSystem.getInstance(symbol);
                }
                LocalParameter tempParam = clampStimulus.getLocalParameter(paramFunction.getName());
                if (tempParam == null) {
                    clampStimulus.addUserDefinedParameter(paramFunction.getName(), paramFunction.getExpression(), unit);
                } else {
                    if (tempParam.getExpression() != null) {
                        // if the expression is null, it should remain null.
                        clampStimulus.setParameterValue(tempParam, paramFunction.getExpression());
                    }
                    tempParam.setUnitDefinition(unit);
                }
            }
        }
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while setting parameters for simContext : " + currentSimulationContext.getName(), e);
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while settings parameters for simContext : " + currentSimulationContext.getName(), e);
    } finally {
        clampStimulus.reading(false);
    }
    return clampStimulus;
}
Also used : Electrode(cbit.vcell.mapping.Electrode) FilamentVariable(cbit.vcell.math.FilamentVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) StochVolVariable(cbit.vcell.math.StochVolVariable) RandomVariable(cbit.vcell.math.RandomVariable) VolumeRandomVariable(cbit.vcell.math.VolumeRandomVariable) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) VolVariable(cbit.vcell.math.VolVariable) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) PointVariable(cbit.vcell.math.PointVariable) MembraneRandomVariable(cbit.vcell.math.MembraneRandomVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) MemVariable(cbit.vcell.math.MemVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) VariableHash(cbit.vcell.math.VariableHash) Element(org.jdom.Element) CurrentDensityClampStimulus(cbit.vcell.mapping.CurrentDensityClampStimulus) TotalCurrentClampStimulus(cbit.vcell.mapping.TotalCurrentClampStimulus) ExpressionException(cbit.vcell.parser.ExpressionException) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) PropertyVetoException(java.beans.PropertyVetoException) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) VoltageClampStimulus(cbit.vcell.mapping.VoltageClampStimulus) MathException(cbit.vcell.math.MathException) MathModel(cbit.vcell.mathmodel.MathModel) Model(cbit.vcell.model.Model) PathwayModel(org.vcell.pathway.PathwayModel) RelationshipModel(org.vcell.relationship.RelationshipModel) BioModel(cbit.vcell.biomodel.BioModel) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) FilamentSubDomain(cbit.vcell.math.FilamentSubDomain) PointSubDomain(cbit.vcell.math.PointSubDomain) Domain(cbit.vcell.math.Variable.Domain) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Aggregations

VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)113 Expression (cbit.vcell.parser.Expression)73 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)36 ExpressionException (cbit.vcell.parser.ExpressionException)26 PropertyVetoException (java.beans.PropertyVetoException)24 LocalParameter (cbit.vcell.mapping.ParameterContext.LocalParameter)21 Element (org.jdom.Element)20 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)19 ArrayList (java.util.ArrayList)17 ModelParameter (cbit.vcell.model.Model.ModelParameter)16 Model (cbit.vcell.model.Model)14 Parameter (cbit.vcell.model.Parameter)14 SpeciesContext (cbit.vcell.model.SpeciesContext)13 SymbolTableEntry (cbit.vcell.parser.SymbolTableEntry)13 Membrane (cbit.vcell.model.Membrane)12 Structure (cbit.vcell.model.Structure)12 StructureMapping (cbit.vcell.mapping.StructureMapping)11 MathException (cbit.vcell.math.MathException)10 ReactionStep (cbit.vcell.model.ReactionStep)10 Feature (cbit.vcell.model.Feature)9