Search in sources :

Example 86 with VCUnitDefinition

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

the class AbstractMathMapping method getIdentifierSubstitutions.

/**
 * Substitutes appropriate variables for speciesContext bindings
 *
 * @return cbit.vcell.parser.Expression
 * @param origExp cbit.vcell.parser.Expression
 * @param structureMapping cbit.vcell.mapping.StructureMapping
 */
protected Expression getIdentifierSubstitutions(Expression origExp, VCUnitDefinition desiredExpUnitDef, GeometryClass geometryClass) throws ExpressionException, MappingException {
    String[] symbols = origExp.getSymbols();
    if (symbols == null) {
        return origExp;
    }
    VCUnitDefinition expUnitDef = null;
    try {
        VCUnitEvaluator unitEvaluator = new VCUnitEvaluator(simContext.getModel().getUnitSystem());
        expUnitDef = unitEvaluator.getUnitDefinition(origExp);
        if (desiredExpUnitDef == null) {
            String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
            System.out.println("...........exp='" + expStr + "', desiredUnits are null");
            localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[null], observed=[" + expUnitDef.getSymbol() + "]", Issue.SEVERITY_WARNING));
        } else if (expUnitDef == null) {
            String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
            System.out.println("...........exp='" + expStr + "', evaluated Units are null");
            localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + desiredExpUnitDef.getSymbol() + "], observed=[null]", Issue.SEVERITY_WARNING));
        } else if (desiredExpUnitDef.isTBD()) {
            String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
            // System.out.println("...........exp='"+expStr+"', desiredUnits are ["+desiredExpUnitDef.getSymbol()+"] and expression units are ["+expUnitDef.getSymbol()+"]");
            localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + desiredExpUnitDef.getSymbol() + "], observed=[" + expUnitDef.getSymbol() + "] for exp = " + expStr, Issue.SEVERITY_WARNING));
        } else if (!desiredExpUnitDef.isEquivalent(expUnitDef) && !expUnitDef.isTBD()) {
            String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
            // System.out.println("...........exp='"+expStr+"', desiredUnits are ["+desiredExpUnitDef.getSymbol()+"] and expression units are ["+expUnitDef.getSymbol()+"]");
            localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + desiredExpUnitDef.getSymbol() + "], observed=[" + expUnitDef.getSymbol() + "] for exp = " + expStr, Issue.SEVERITY_WARNING));
        }
    } catch (VCUnitException e) {
        String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
        System.out.println(".........exp='" + expStr + "' exception='" + e.getMessage() + "'");
        localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + ((desiredExpUnitDef != null) ? (desiredExpUnitDef.getSymbol()) : ("null")) + "], exception=" + e.getMessage(), Issue.SEVERITY_WARNING));
    } catch (ExpressionException e) {
        String expStr = origExp.renameBoundSymbols(getNameScope()).infix();
        System.out.println(".........exp='" + expStr + "' exception='" + e.getMessage() + "'");
        localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + ((desiredExpUnitDef != null) ? (desiredExpUnitDef.getSymbol()) : ("null")) + "], exception=" + e.getMessage(), Issue.SEVERITY_WARNING));
    } catch (Exception e) {
        e.printStackTrace(System.out);
        localIssueList.add(new Issue(origExp, issueContext, IssueCategory.Units, "expected=[" + ((desiredExpUnitDef != null) ? (desiredExpUnitDef.getSymbol()) : ("null")) + "], exception=" + e.getMessage(), Issue.SEVERITY_WARNING));
    }
    Expression newExp = new Expression(origExp);
    // 
    // flatten user-defined functions
    // 
    FunctionInvocation[] functionInvocations = newExp.getFunctionInvocations(new FunctionFilter() {

        @Override
        public boolean accept(String functionName, FunctionType functionType) {
            return functionType == FunctionType.USERDEFINED;
        }
    });
    for (FunctionInvocation functionInvocation : functionInvocations) {
        if (functionInvocation.getSymbolTableFunctionEntry() instanceof Model.ModelFunction) {
            ModelFunction modelFunction = (ModelFunction) functionInvocation.getSymbolTableFunctionEntry();
            newExp.substituteInPlace(functionInvocation.getFunctionExpression(), modelFunction.getFlattenedExpression(functionInvocation));
        }
    }
    // 
    // then substitute Math symbols for Biological symbols.
    // 
    newExp.bindExpression(null);
    for (int i = 0; i < symbols.length; i++) {
        SymbolTableEntry ste = origExp.getSymbolBinding(symbols[i]);
        if (ste == null) {
            throw new ExpressionBindingException("symbol '" + symbols[i] + "' not bound");
        // ste = simContext.getGeometryContext().getModel().getSpeciesContext(symbols[i]);
        }
        if (ste != null) {
            String newName = getMathSymbol(ste, geometryClass);
            if (!newName.equals(symbols[i])) {
                newExp.substituteInPlace(new Expression(symbols[i]), new Expression(newName));
            }
        }
    }
    return newExp;
}
Also used : FunctionInvocation(cbit.vcell.parser.FunctionInvocation) Issue(org.vcell.util.Issue) ModelFunction(cbit.vcell.model.Model.ModelFunction) FunctionType(cbit.vcell.parser.ASTFuncNode.FunctionType) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ExpressionException(cbit.vcell.parser.ExpressionException) VCUnitException(cbit.vcell.units.VCUnitException) PropertyVetoException(java.beans.PropertyVetoException) MatrixException(cbit.vcell.matrix.MatrixException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) VCUnitException(cbit.vcell.units.VCUnitException) VCUnitEvaluator(cbit.vcell.parser.VCUnitEvaluator) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) FunctionFilter(cbit.vcell.parser.Expression.FunctionFilter) Expression(cbit.vcell.parser.Expression)

Example 87 with VCUnitDefinition

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

the class AbstractStochMathMapping method getExpressionAmtToConc.

/**
 * getExpressionAmtToConc : converts the particles expression ('particlesExpr') to an expression for concentration.
 * 		If argument 'speciesContext' is on a membrane, concExpr = particlesExpr/size_of_Mem. If 'speciesContext' is in
 * 		feature, concExpr = (particlesExpr/size_of_Feature)*KMOLE.
 * @param particlesExpr
 * @param speciesContext
 * @return
 * @throws MappingException
 * @throws ExpressionException
 */
protected Expression getExpressionAmtToConc(Expression particlesExpr, Structure structure) throws MappingException, ExpressionException {
    ModelUnitSystem unitSystem = getSimulationContext().getModel().getUnitSystem();
    VCUnitDefinition substanceUnit = unitSystem.getSubstanceUnit(structure);
    Expression unitFactor = getUnitFactor(substanceUnit.divideBy(unitSystem.getStochasticSubstanceUnit()));
    Expression scStructureSize = new Expression(structure.getStructureSize(), getNameScope());
    Expression concentrationExpr = Expression.mult(particlesExpr, Expression.div(unitFactor, scStructureSize));
    return concentrationExpr;
}
Also used : VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 88 with VCUnitDefinition

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

the class BioEvent method setTimeList.

public void setTimeList(Expression[] listExps) throws ExpressionBindingException, PropertyVetoException {
    if (triggerType != TriggerType.ListOfTimes) {
        throw new RuntimeException("list of times only available for " + TriggerType.ListOfTimes.name() + " trigger type");
    }
    // 
    // remove any existing TimeListItem parameters
    // 
    ArrayList<LocalParameter> parameters = new ArrayList<LocalParameter>();
    for (LocalParameter p : getEventParameters()) {
        if (p.getRole() != BioEventParameterType.TimeListItem) {
            parameters.add(p);
        }
    }
    // 
    // generate new TimeListItem parameters from function arguments
    // 
    VCUnitDefinition timeUnit = getSimulationContext().getModel().getUnitSystem().getTimeUnit();
    String name = "t0";
    for (Expression exp : listExps) {
        String description = BioEventParameterType.TimeListItem.description;
        parameters.add(parameterContext.new LocalParameter(name, exp, BioEventParameterType.TimeListItem, timeUnit, description));
        name = TokenMangler.getNextEnumeratedToken(name);
    }
    setParameters(parameters.toArray(new LocalParameter[0]));
}
Also used : LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ArrayList(java.util.ArrayList)

Example 89 with VCUnitDefinition

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

the class GeometrySurfaceUtils method getUpdatedGeometricRegions.

/**
 * Insert the method's description here.
 * Creation date: (6/28/2004 3:09:13 PM)
 * @return cbit.vcell.geometry.surface.GeometricRegion[]
 * @param geoSurfaceDescription cbit.vcell.geometry.surface.GeometrySurfaceDescription
 * @param surfaceCollection cbit.vcell.geometry.surface.SurfaceCollection
 */
public static GeometricRegion[] getUpdatedGeometricRegions(GeometrySurfaceDescription geoSurfaceDescription, cbit.vcell.geometry.RegionImage regionImage, SurfaceCollection surfaceCollection) {
    // 
    // parse regionImage into ResolvedVolumeLocations
    // 
    VCellThreadChecker.checkCpuIntensiveInvocation();
    double sizeOfPixel = 0;
    VCUnitDefinition volumeUnit = null;
    VCUnitDefinition surfaceUnit = null;
    GeometrySpec geometrySpec = geoSurfaceDescription.getGeometry().getGeometrySpec();
    GeometryUnitSystem geometryUnitSystem = geoSurfaceDescription.getGeometry().getUnitSystem();
    switch(geometrySpec.getDimension()) {
        case 1:
            {
                sizeOfPixel = geometrySpec.getExtent().getX() / (regionImage.getNumX() - 1);
                // sizeOfPixel /= 9.0;  // to account for the padding from 1D to 3D
                volumeUnit = geometryUnitSystem.getLengthUnit();
                surfaceUnit = geometryUnitSystem.getInstance_DIMENSIONLESS();
                break;
            }
        case 2:
            {
                sizeOfPixel = geometrySpec.getExtent().getX() / (regionImage.getNumX() - 1) * geometrySpec.getExtent().getY() / (regionImage.getNumY() - 1);
                // sizeOfPixel /= 3.0;  // to account for the padding from 2D to 3D
                volumeUnit = geometryUnitSystem.getAreaUnit();
                surfaceUnit = geometryUnitSystem.getLengthUnit();
                break;
            }
        case 3:
            {
                sizeOfPixel = geometrySpec.getExtent().getX() / (regionImage.getNumX() - 1) * geometrySpec.getExtent().getY() / (regionImage.getNumY() - 1) * geometrySpec.getExtent().getZ() / (regionImage.getNumZ() - 1);
                volumeUnit = geometryUnitSystem.getVolumeUnit();
                surfaceUnit = geometryUnitSystem.getAreaUnit();
                break;
            }
    }
    int numX = regionImage.getNumX();
    int numY = regionImage.getNumY();
    int numZ = regionImage.getNumZ();
    int numXY = numX * numY;
    java.util.Vector<GeometricRegion> regionList = new java.util.Vector<GeometricRegion>();
    cbit.vcell.geometry.RegionImage.RegionInfo[] regionInfos = regionImage.getRegionInfos();
    for (int i = 0; i < regionInfos.length; i++) {
        cbit.vcell.geometry.RegionImage.RegionInfo regionInfo = regionInfos[i];
        lg.info(regionInfo);
        cbit.vcell.geometry.SubVolume subVolume = geometrySpec.getSubVolume(regionInfo.getPixelValue());
        String name = subVolume.getName() + regionInfo.getRegionIndex();
        int numPixels = regionInfo.getNumPixels();
        double size = numPixels * sizeOfPixel;
        // 
        switch(geometrySpec.getDimension()) {
            case 1:
                {
                    int numHalvesToRemove = 0;
                    // -x pixel
                    if (regionInfo.isIndexInRegion(0)) {
                        // (regionImage.getRegionIndex(0,0,0) == regionIndex)
                        numHalvesToRemove++;
                    }
                    // +x pixel
                    if (regionInfo.isIndexInRegion(numX - 1)) {
                        // (regionImage.getRegionIndex(regionImageNumX-1,0,0) == regionIndex){
                        numHalvesToRemove++;
                    }
                    // *9; // 1D is padded by 3 in y and 3 in z (hence factor of 9)
                    size -= sizeOfPixel * 0.5 * numHalvesToRemove;
                    break;
                }
            case 2:
                {
                    int numQuadrantsToRemove = 0;
                    int yOffset = 0;
                    for (int yIndex = 0; yIndex < numY; yIndex++) {
                        if (regionInfo.isIndexInRegion(yOffset)) {
                            // (regionImage.getRegionIndex(0,yIndex,0) == regionIndex){
                            if (yIndex == 0 || yIndex == numY - 1) {
                                // corner, remove 3 quadrants
                                numQuadrantsToRemove += 3;
                            } else {
                                // side, remove 2 quadrants
                                numQuadrantsToRemove += 2;
                            }
                        }
                        // +x side (including attached corners)
                        if (regionInfo.isIndexInRegion(numX - 1 + yOffset)) {
                            // (regionImage.getRegionIndex(numX-1,yIndex,0) == regionIndex){
                            if (yIndex == 0 || yIndex == numY - 1) {
                                // corner, remove 3 quadrants
                                numQuadrantsToRemove += 3;
                            } else {
                                // side, remove 2 quadrants
                                numQuadrantsToRemove += 2;
                            }
                        }
                        yOffset += numX;
                    }
                    int yOffsetLastLine = (numY - 1) * numX;
                    for (int xIndex = 1; xIndex < numX - 1; xIndex++) {
                        // -y side (excluding corners)
                        if (regionInfo.isIndexInRegion(xIndex)) {
                            // (regionImage.getRegionIndex(xIndex,0,0) == regionIndex){
                            // side, remove 2 quadrants
                            numQuadrantsToRemove += 2;
                        }
                        // +x side (excluding corners)
                        if (regionInfo.isIndexInRegion(xIndex + yOffsetLastLine)) {
                            // (regionImage.getRegionIndex(xIndex,numY-1,0) == regionIndex){
                            // side, remove 2 quadrants
                            numQuadrantsToRemove += 2;
                        }
                    }
                    // *3; // 2D is padded by 3 in z (hence the factor of 3).
                    size -= sizeOfPixel * 0.25 * numQuadrantsToRemove;
                    break;
                }
            case 3:
                {
                    int numOctantsToRemove = 0;
                    for (int zIndex = 0; zIndex < numZ; zIndex++) {
                        for (int yIndex = 0; yIndex < numY; yIndex++) {
                            // -x side (including attached edges and corners)
                            // already on face of boundary (removing half)
                            int totalOctants = 4;
                            // lg.info("-x side including edges and corners");
                            if (regionInfo.isIndexInRegion(yIndex * numX + zIndex * numXY)) {
                                // (regionImage.getRegionIndex(0,yIndex,zIndex) == regionIndex){
                                if (yIndex == 0 || yIndex == numY - 1) {
                                    totalOctants /= 2;
                                }
                                if (zIndex == 0 || zIndex == numZ - 1) {
                                    totalOctants /= 2;
                                }
                                numOctantsToRemove += (8 - totalOctants);
                            }
                            // lg.info("+x side including edges and corners");
                            // +x side (including attached edges and corners)
                            // already on face of boundary (removing half)
                            totalOctants = 4;
                            if (regionInfo.isIndexInRegion(numX - 1 + yIndex * numX + zIndex * numXY)) {
                                // (regionImage.getRegionIndex(numX-1,yIndex,zIndex) == regionIndex){
                                if (yIndex == 0 || yIndex == numY - 1) {
                                    totalOctants /= 2;
                                }
                                if (zIndex == 0 || zIndex == numZ - 1) {
                                    totalOctants /= 2;
                                }
                                numOctantsToRemove += (8 - totalOctants);
                            }
                        }
                        for (int xIndex = 1; xIndex < numX - 1; xIndex++) {
                            // -y side (including attached edges along x axis, excluding corners)
                            // lg.info("-y side including edges");
                            // already on face of boundary (removing half)
                            int totalOctants = 4;
                            if (regionInfo.isIndexInRegion(xIndex + zIndex * numXY)) {
                                // (regionImage.getRegionIndex(xIndex,0,zIndex) == regionIndex){
                                if (zIndex == 0 || zIndex == numZ - 1) {
                                    totalOctants /= 2;
                                }
                                numOctantsToRemove += (8 - totalOctants);
                            }
                            // lg.info("+y side including edges");
                            // +y side (including attached edges along x axis, excluding corners)
                            // already on face of boundary (removing half)
                            totalOctants = 4;
                            if (regionInfo.isIndexInRegion(xIndex + (numY - 1) * numX + zIndex * numXY)) {
                                // (regionImage.getRegionIndex(xIndex,numY-1,zIndex) == regionIndex){
                                if (zIndex == 0 || zIndex == numZ - 1) {
                                    totalOctants /= 2;
                                }
                                numOctantsToRemove += (8 - totalOctants);
                            }
                        }
                    }
                    for (int yIndex = 1; yIndex < numY - 1; yIndex++) {
                        for (int xIndex = 1; xIndex < numX - 1; xIndex++) {
                            // already on face of boundary (removing half)
                            int totalOctants = 4;
                            // lg.info("-z side including nothing");
                            if (regionInfo.isIndexInRegion(xIndex + yIndex * numX)) {
                                // (regionImage.getRegionIndex(xIndex,yIndex,0) == regionIndex){
                                numOctantsToRemove += (8 - totalOctants);
                            }
                            // lg.info("+z side including nothing");
                            if (regionInfo.isIndexInRegion(xIndex + yIndex * numX + (numZ - 1) * numXY)) {
                                // (regionImage.getRegionIndex(xIndex,yIndex,numZ-1) == regionIndex){
                                numOctantsToRemove += (8 - totalOctants);
                            }
                        }
                    }
                    size -= sizeOfPixel * 0.125 * numOctantsToRemove;
                    if (lg.isInfoEnabled()) {
                        lg.info("size=" + size);
                    }
                    break;
                }
        }
        VolumeGeometricRegion volumeRegion = new VolumeGeometricRegion(name, size, volumeUnit, subVolume, regionInfo.getRegionIndex());
        regionList.add(volumeRegion);
        if (lg.isInfoEnabled()) {
            lg.info("added volumeRegion(" + volumeRegion.getName() + ")");
        }
    }
    // 
    for (int i = 0; i < surfaceCollection.getSurfaceCount(); i++) {
        cbit.vcell.geometry.surface.Surface surface = surfaceCollection.getSurfaces(i);
        int exteriorRegionIndex = surface.getExteriorRegionIndex();
        int interiorRegionIndex = surface.getInteriorRegionIndex();
        cbit.vcell.geometry.SubVolume surfaceExteriorSubvolume = geometrySpec.getSubVolume(regionInfos[exteriorRegionIndex].getPixelValue());
        cbit.vcell.geometry.SubVolume surfaceInteriorSubvolume = geometrySpec.getSubVolume(regionInfos[interiorRegionIndex].getPixelValue());
        String name = "membrane_" + surfaceInteriorSubvolume.getName() + interiorRegionIndex + "_" + surfaceExteriorSubvolume.getName() + exteriorRegionIndex;
        double correctedArea = surface.getArea();
        if (geometrySpec.getDimension() == 2) {
            correctedArea /= geometrySpec.getExtent().getZ();
        } else if (geometrySpec.getDimension() == 1) {
            correctedArea /= (geometrySpec.getExtent().getY() * geometrySpec.getExtent().getZ());
        }
        SurfaceGeometricRegion surfaceRegion = new SurfaceGeometricRegion(name, correctedArea, surfaceUnit);
        regionList.add(surfaceRegion);
        // 
        // connect this surfaceLocation to its exterior and interior volumeLocations
        // 
        VolumeGeometricRegion exteriorVolumeRegion = null;
        for (int j = 0; j < regionList.size(); j++) {
            GeometricRegion region = regionList.elementAt(j);
            if (region instanceof VolumeGeometricRegion && region.getName().equals(surfaceExteriorSubvolume.getName() + exteriorRegionIndex)) {
                exteriorVolumeRegion = (VolumeGeometricRegion) region;
            }
        }
        surfaceRegion.addAdjacentGeometricRegion(exteriorVolumeRegion);
        exteriorVolumeRegion.addAdjacentGeometricRegion(surfaceRegion);
        VolumeGeometricRegion interiorVolumeRegion = null;
        for (int j = 0; j < regionList.size(); j++) {
            GeometricRegion region = regionList.elementAt(j);
            if (region instanceof VolumeGeometricRegion && region.getName().equals(surfaceInteriorSubvolume.getName() + interiorRegionIndex)) {
                interiorVolumeRegion = (VolumeGeometricRegion) region;
            }
        }
        surfaceRegion.addAdjacentGeometricRegion(interiorVolumeRegion);
        interiorVolumeRegion.addAdjacentGeometricRegion(surfaceRegion);
        if (lg.isInfoEnabled()) {
            lg.info("added surfaceRegion(" + surfaceRegion.getName() + ")");
        }
    }
    return org.vcell.util.BeanUtils.getArray(regionList, GeometricRegion.class);
}
Also used : GeometrySpec(cbit.vcell.geometry.GeometrySpec) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) GeometryUnitSystem(cbit.vcell.geometry.GeometryUnitSystem) RegionImage(cbit.vcell.geometry.RegionImage)

Example 90 with VCUnitDefinition

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

the class XmlReader method getKinetics.

/**
 * This method returns a Kinetics object from a XML Element based on the value of the kinetics type attribute.
 * Creation date: (3/19/2001 4:42:04 PM)
 * @return cbit.vcell.model.Kinetics
 * @param param org.jdom.Element
 */
private Kinetics getKinetics(Element param, ReactionStep reaction, Model model) throws XmlParseException {
    VariableHash varHash = new VariableHash();
    addResevedSymbols(varHash, model);
    String type = param.getAttributeValue(XMLTags.KineticsTypeAttrTag);
    Kinetics newKinetics = null;
    try {
        if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralKinetics)) {
            // create a general kinetics
            newKinetics = new GeneralKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentKinetics)) {
            // Create GeneralCurrentKinetics
            newKinetics = new GeneralCurrentKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMassAction) && reaction instanceof SimpleReaction) {
            // create a Mass Action kinetics
            newKinetics = new MassActionKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeNernst) && reaction instanceof FluxReaction) {
            // create NernstKinetics
            newKinetics = new NernstKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGHK) && reaction instanceof FluxReaction) {
            // create GHKKinetics
            newKinetics = new GHKKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Irr) && reaction instanceof SimpleReaction) {
            // create HMM_IrrKinetics
            newKinetics = new HMM_IRRKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeHMM_Rev) && reaction instanceof SimpleReaction) {
            // create HMM_RevKinetics
            newKinetics = new HMM_REVKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralTotal_oldname)) {
            // create GeneralTotalKinetics
            newKinetics = new GeneralLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralLumped)) {
            // create GeneralLumpedKinetics
            newKinetics = new GeneralLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralCurrentLumped)) {
            // create GeneralCurrentLumpedKinetics
            newKinetics = new GeneralCurrentLumpedKinetics(reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeGeneralPermeability) && reaction instanceof FluxReaction) {
            // create GeneralPermeabilityKinetics
            newKinetics = new GeneralPermeabilityKinetics((FluxReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMacroscopic_Irr) && reaction instanceof SimpleReaction) {
            // create Macroscopic_IRRKinetics
            newKinetics = new Macroscopic_IRRKinetics((SimpleReaction) reaction);
        } else if (type.equalsIgnoreCase(XMLTags.KineticsTypeMicroscopic_Irr) && reaction instanceof SimpleReaction) {
            // create Microscopic_IRRKinetics
            newKinetics = new Microscopic_IRRKinetics((SimpleReaction) reaction);
        } else {
            throw new XmlParseException("Unknown kinetics type: " + type);
        }
    } catch (ExpressionException e) {
        e.printStackTrace();
        throw new XmlParseException("Error creating the kinetics for reaction: " + reaction.getName(), e);
    }
    try {
        // transaction begin flag ... yeah, this is a hack
        newKinetics.reading(true);
        // Read all of the parameters
        List<Element> list = param.getChildren(XMLTags.ParameterTag, vcNamespace);
        // add constants that may be used in kinetics.
        // VariableHash varHash = getVariablesHash();
        ArrayList<String> reserved = new ArrayList<String>();
        ReservedSymbol[] reservedSymbols = reaction.getModel().getReservedSymbols();
        for (ReservedSymbol rs : reservedSymbols) {
            reserved.add(rs.getName());
        }
        try {
            if (reaction.getStructure() instanceof Membrane) {
                Membrane membrane = (Membrane) reaction.getStructure();
                varHash.addVariable(new Constant(membrane.getMembraneVoltage().getName(), new Expression(0.0)));
                reserved.add(membrane.getMembraneVoltage().getName());
            }
            // 
            // add Reactants, Products, and Catalysts (ReactionParticipants)
            // 
            ReactionParticipant[] rp = reaction.getReactionParticipants();
            for (int i = 0; i < rp.length; i++) {
                varHash.addVariable(new Constant(rp[i].getName(), new Expression(0.0)));
            }
        } catch (MathException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("error reordering parameters according to dependencies: ", e);
        }
        // 
        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) {
                    varHash.addVariable(new Function(paramName, paramExp, null));
                } else {
                    if (reserved.contains(paramName)) {
                        varHash.removeVariable(paramName);
                        varHash.addVariable(new Function(paramName, paramExp, null));
                    }
                }
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException("error reordering parameters according to dependencies: ", e);
            }
            Kinetics.KineticsParameter tempParam = null;
            if (!role.equals(XMLTags.ParamRoleUserDefinedTag)) {
                tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.getParamRoleFromDefaultDesc(role));
            } else {
                continue;
            }
            // hack for bringing in General Total kinetics without breaking.
            if (tempParam == null && newKinetics instanceof GeneralLumpedKinetics) {
                if (role.equals(Kinetics.GTK_AssumedCompartmentSize_oldname) || role.equals(Kinetics.GTK_ReactionRate_oldname) || role.equals(Kinetics.GTK_CurrentDensity_oldname)) {
                    continue;
                } else if (role.equals(VCMODL.TotalRate_oldname)) {
                    tempParam = newKinetics.getKineticsParameterFromRole(Kinetics.ROLE_LumpedReactionRate);
                }
            }
            // hack from bringing in chargeValence parameters without breaking
            if (tempParam == null && Kinetics.getParamRoleFromDefaultDesc(role) == Kinetics.ROLE_ChargeValence) {
                tempParam = newKinetics.getChargeValenceParameter();
            }
            if (tempParam == null) {
                throw new XmlParseException("parameter with role '" + role + "' not found in kinetics type '" + type + "'");
            }
            // 
            if (!tempParam.getName().equals(paramName)) {
                Kinetics.KineticsParameter multNameParam = newKinetics.getKineticsParameter(paramName);
                int n = 0;
                while (multNameParam != null) {
                    String tempName = paramName + "_" + n++;
                    newKinetics.renameParameter(paramName, tempName);
                    multNameParam = newKinetics.getKineticsParameter(tempName);
                }
                newKinetics.renameParameter(tempParam.getName(), paramName);
            }
        }
        // 
        // create unresolved parameters for all unresolved symbols
        // 
        String unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        while (unresolvedSymbol != null) {
            try {
                // will turn into an UnresolvedParameter.
                varHash.addVariable(new Function(unresolvedSymbol, new Expression(0.0), null));
            } catch (MathException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
            newKinetics.addUnresolvedParameter(unresolvedSymbol);
            unresolvedSymbol = varHash.getFirstUnresolvedSymbol();
        }
        Variable[] sortedVariables = varHash.getTopologicallyReorderedVariables();
        ModelUnitSystem modelUnitSystem = reaction.getModel().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);
                }
                Kinetics.KineticsParameter tempParam = newKinetics.getKineticsParameter(paramFunction.getName());
                if (tempParam == null) {
                    newKinetics.addUserDefinedKineticsParameter(paramFunction.getName(), paramFunction.getExpression(), unit);
                } else {
                    newKinetics.setParameterValue(tempParam, paramFunction.getExpression());
                    tempParam.setUnitDefinition(unit);
                }
            }
        }
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while setting parameters for Reaction : " + reaction.getName(), e);
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception while settings parameters for Reaction : " + reaction.getName(), e);
    } finally {
        newKinetics.reading(false);
    }
    return newKinetics;
}
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) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) VariableHash(cbit.vcell.math.VariableHash) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) MacroscopicRateConstant(cbit.vcell.math.MacroscopicRateConstant) Constant(cbit.vcell.math.Constant) Element(org.jdom.Element) ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) NernstKinetics(cbit.vcell.model.NernstKinetics) ArrayList(java.util.ArrayList) FluxReaction(cbit.vcell.model.FluxReaction) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) ExpressionException(cbit.vcell.parser.ExpressionException) PropertyVetoException(java.beans.PropertyVetoException) GeneralCurrentKinetics(cbit.vcell.model.GeneralCurrentKinetics) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Function(cbit.vcell.math.Function) GeneralCurrentLumpedKinetics(cbit.vcell.model.GeneralCurrentLumpedKinetics) Membrane(cbit.vcell.model.Membrane) Macroscopic_IRRKinetics(cbit.vcell.model.Macroscopic_IRRKinetics) GeneralPermeabilityKinetics(cbit.vcell.model.GeneralPermeabilityKinetics) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SimpleReaction(cbit.vcell.model.SimpleReaction) GHKKinetics(cbit.vcell.model.GHKKinetics) HMM_REVKinetics(cbit.vcell.model.HMM_REVKinetics) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Macroscopic_IRRKinetics(cbit.vcell.model.Macroscopic_IRRKinetics) Kinetics(cbit.vcell.model.Kinetics) NernstKinetics(cbit.vcell.model.NernstKinetics) GeneralKinetics(cbit.vcell.model.GeneralKinetics) GeneralLumpedKinetics(cbit.vcell.model.GeneralLumpedKinetics) GeneralPermeabilityKinetics(cbit.vcell.model.GeneralPermeabilityKinetics) GHKKinetics(cbit.vcell.model.GHKKinetics) MassActionKinetics(cbit.vcell.model.MassActionKinetics) Microscopic_IRRKinetics(cbit.vcell.model.Microscopic_IRRKinetics) GeneralCurrentKinetics(cbit.vcell.model.GeneralCurrentKinetics) HMM_REVKinetics(cbit.vcell.model.HMM_REVKinetics) HMM_IRRKinetics(cbit.vcell.model.HMM_IRRKinetics) GeneralCurrentLumpedKinetics(cbit.vcell.model.GeneralCurrentLumpedKinetics) Microscopic_IRRKinetics(cbit.vcell.model.Microscopic_IRRKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

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