Search in sources :

Example 1 with UnitDefinition

use of org.sbml.jsbml.UnitDefinition in project vcell by virtualcell.

the class SBMLUnitTranslator method getSBMLUnitDefinition.

public static UnitDefinition getSBMLUnitDefinition(VCUnitDefinition vcUnitDefn, int level, int version, VCUnitSystem vcUnitSystem) throws SbmlException {
    final UnitDefinition sbmlUnitDefn = new UnitDefinition(3, 1);
    if (vcUnitDefn.isCompatible(vcUnitSystem.getInstance_DIMENSIONLESS())) {
        double multiplier = 1.0;
        String symbol = vcUnitDefn.getSymbol();
        if (isDouble(symbol)) {
            multiplier = Double.parseDouble(symbol);
        }
        sbmlUnitDefn.addUnit(new Unit(multiplier, 0, Kind.DIMENSIONLESS, 1.0, 3, 1));
        return sbmlUnitDefn;
    }
    String vcSymbol = vcUnitDefn.getSymbol();
    double overallMultiplier = 1.0;
    if (vcSymbol.contains(" ")) {
        String[] unitParts = vcSymbol.split(" ");
        overallMultiplier = Double.parseDouble(unitParts[0]);
        vcSymbol = unitParts[1];
    }
    // String sbmlUnitSymbol = TokenMangler.mangleToSName(vcSymbol);
    String[] symbols = vcSymbol.split("\\.");
    if (symbols.length == 0) {
        symbols = new String[] { vcSymbol };
    }
    for (int i = 0; i < symbols.length; i++) {
        double multiplier = 1.0;
        if (i == 0) {
            multiplier *= overallMultiplier;
        }
        double exponent = 1.0;
        int scale = 0;
        String symbol = symbols[i];
        // }
        if (symbol.contains("-")) {
            String[] symbolAndExp = symbol.split("\\-");
            symbol = symbolAndExp[0];
            exponent = -1 * Integer.parseInt(symbolAndExp[1]);
        } else if (Character.isDigit(symbol.charAt(symbol.length() - 1))) {
            exponent = Integer.parseInt(symbol.substring(symbol.length() - 1));
            symbol = symbol.substring(0, symbol.length() - 1);
        }
        VCUnitDefinition vcUnit = vcUnitSystem.getInstance(symbol);
        boolean bFoundMatch = false;
        // check sbml builtin units (base SI and supported derived units) first.
        for (Kind kind : Kind.values()) {
            String kindSymbol = kind.getSymbol();
            if (kind == Kind.AVOGADRO || kind == Kind.CELSIUS || kind == Kind.INVALID || kind == Kind.BECQUEREL || kind == Kind.HERTZ) {
                continue;
            }
            if (kind == Kind.OHM) {
                kindSymbol = "Ohm";
            }
            if (kind == Kind.ITEM) {
                kindSymbol = "molecules";
            }
            if (kind == Kind.METER) {
                kind = Kind.METRE;
            }
            if (kind == Kind.LITER) {
                kind = Kind.LITRE;
            }
            VCUnitDefinition kindVcUnit = vcUnitSystem.getInstance(kindSymbol);
            if (kindVcUnit.isCompatible(vcUnit)) {
                if (kindVcUnit.isEquivalent(vcUnit)) {
                    sbmlUnitDefn.addUnit(new Unit(multiplier, scale, kind, exponent, 3, 1));
                } else {
                    double factor = vcUnit.convertTo(1.0, kindVcUnit);
                    double logFactor = Math.log10(factor);
                    if (logFactor == (int) logFactor) {
                        scale = (int) logFactor;
                    } else {
                        scale = 0;
                        multiplier = multiplier * factor;
                    }
                    Unit sbmlUnit = new Unit(multiplier, scale, kind, exponent, 3, 1);
                    sbmlUnitDefn.addUnit(sbmlUnit);
                    System.err.println("kind = " + kind.name() + " is equivalent to vcUnit = " + vcUnit.getSymbol() + ",  SBML unit is " + sbmlUnit);
                }
                bFoundMatch = true;
                break;
            }
        }
        if (!bFoundMatch) {
            // check for molar, kind of crazy that this one is missing.
            VCUnitDefinition kindVcUnit = vcUnitSystem.getInstance("molar");
            if (kindVcUnit.isCompatible(vcUnit)) {
                if (kindVcUnit.isEquivalent(vcUnit)) {
                    sbmlUnitDefn.addUnit(new Unit(multiplier, scale, Kind.MOLE, exponent, 3, 1));
                    sbmlUnitDefn.addUnit(new Unit(1, 0, Kind.LITRE, -exponent, 3, 1));
                } else {
                    double factor = vcUnit.convertTo(1.0, kindVcUnit);
                    double logFactor = Math.log10(factor);
                    if (logFactor == (int) logFactor) {
                        scale = (int) logFactor;
                    } else {
                        scale = 0;
                        multiplier = multiplier * factor;
                    }
                    sbmlUnitDefn.addUnit(new Unit(multiplier, scale, Kind.MOLE, exponent, 3, 1));
                    sbmlUnitDefn.addUnit(new Unit(1, 0, Kind.LITRE, -exponent, 3, 1));
                    System.err.println("matched to liter ... had to create a replacement for molar, vcUnit = " + vcUnit.getSymbol() + ",  SBML unit is " + sbmlUnitDefn);
                }
                bFoundMatch = true;
            }
        }
        if (!bFoundMatch) {
            throw new RuntimeException("didn't find a match for vcUnit " + vcUnit.getSymbol());
        // System.out.println("Still didn't find a match for vcUnit "+vcUnit.getSymbol());
        }
    // ucar.units_vcell.Unit ucarUnit = vcUnit.getUcarUnit();
    // if (ucarUnit instanceof ScaledUnit){
    // ScaledUnit scaledUnit = (ScaledUnit)ucarUnit;
    // double parsedScale = scaledUnit.getScale();
    // double logScale = Math.log10(parsedScale);
    // if (logScale == (int)logScale){
    // scale = (int)logScale;
    // }else{
    // scale = 0;
    // multiplier = multiplier*parsedScale;
    // }
    // ucar.units_vcell.Unit insideUnit = scaledUnit.getUnit();
    // boolean bFoundMatch = false;
    // for (Kind kind : Kind.values()){
    // String kindSymbol = kind.getSymbol();
    // if (kind==Kind.AVOGADRO){
    // continue;
    // }
    // if (kind==Kind.CELSIUS){
    // continue;
    // }
    // if (kind==Kind.INVALID){
    // continue;
    // }
    // if (kind==Kind.OHM){
    // kindSymbol = "Ohm";
    // }
    // String sym = insideUnit.toString();
    // if (vcUnitSystem.getInstance(kindSymbol).isEquivalent(vcUnitSystem.getInstance(sym))){
    // sbmlUnitDefn.addUnit(new Unit(multiplier, scale, kind, exponent, 3, 1));
    // bFoundMatch = true;
    // break;
    // }
    // }
    // if (!bFoundMatch){
    // System.err.println("couldn't find an SBML unit for vcUnit "+vcUnit.getSymbol());
    // System.err.println("couldn't find an SBML unit for vcUnit "+vcUnit.getSymbol());
    // }
    // }
    // System.err.println("vcUnit is "+symbols[i]+",  ucarUnit is "+ucarUnit.getSymbol());
    }
    sbmlUnitDefn.setId(TokenMangler.mangleToSName(vcSymbol));
    return sbmlUnitDefn;
// 
// // If VC unit is DIMENSIONLESS ...
// if (vcUnitDefn.isTBD()) {
// throw new RuntimeException("TBD unit has no SBML equivalent");
// } else if (vcUnitDefn.isCompatible(vcUnitSystem.getInstance_DIMENSIONLESS())) {
// double multiplier = 1.0;
// multiplier = vcUnitDefn.convertTo(multiplier, vcUnitSystem.getInstance_DIMENSIONLESS());
// sbmlUnitDefn = new UnitDefinition(level, version);
// sbmlUnitDefn.setId(TokenMangler.mangleToSName(TokenMangler.mangleToSName(vcSymbol)));
// Unit dimensionlessUnit = new UnitD(level, version);
// dimensionlessUnit.setMultiplier(multiplier);
// sbmlUnitDefn.addUnit(dimensionlessUnit);
// } else {
// // Translate the VCUnitDef into libSBML UnitDef : convert the units of VCUnitDef into libSBML units and add them to sbmlUnitDefn
// 
// sbmlUnitDefn = new UnitDefinition(level, version);
// sbmlUnitDefn.setId(TokenMangler.mangleToSName(TokenMangler.mangleToSName(sbmlUnitSymbol)));
// ucar.units_vcell.Unit vcUcarUnit = vcUnitDefn.getUcarUnit();
// //ArrayList<Unit> sbmlUnitsList = convertVCUnitsToSbmlUnits(1.0, vcUcarUnit, new ArrayList<Unit>(), level, version);
// List<Unit> sbmlUnitsList = convert(vcUcarUnit, level, version);
// 
// for (int i = 0; i < sbmlUnitsList.size(); i++){
// Unit sbmlUnit = sbmlUnitsList.get(i);
// sbmlUnitDefn.addUnit(sbmlUnit);
// }
// }
// 
// return sbmlUnitDefn;
}
Also used : VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Kind(org.sbml.jsbml.Unit.Kind) Unit(org.sbml.jsbml.Unit) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 2 with UnitDefinition

use of org.sbml.jsbml.UnitDefinition in project vcell by virtualcell.

the class SBMLExporter method getOrCreateSBMLUnit.

private UnitDefinition getOrCreateSBMLUnit(VCUnitDefinition vcUnit) throws SbmlException {
    String mangledSymbol = TokenMangler.mangleToSName(vcUnit.getSymbol());
    UnitDefinition unitDefn = sbmlModel.getUnitDefinition(mangledSymbol);
    if (unitDefn == null) {
        unitDefn = SBMLUnitTranslator.getSBMLUnitDefinition(vcUnit, sbmlLevel, sbmlVersion, vcBioModel.getModel().getUnitSystem());
        unitDefn.setId(mangledSymbol);
        sbmlModel.addUnitDefinition(unitDefn);
    }
    return unitDefn;
}
Also used : VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 3 with UnitDefinition

use of org.sbml.jsbml.UnitDefinition in project vcell by virtualcell.

the class SBMLExporter method addCompartments.

/**
 * addCompartments comment.
 * @throws XMLStreamException
 * @throws SbmlException
 */
protected void addCompartments() throws XMLStreamException, SbmlException {
    Model vcModel = vcBioModel.getModel();
    cbit.vcell.model.Structure[] vcStructures = vcModel.getStructures();
    for (int i = 0; i < vcStructures.length; i++) {
        Compartment sbmlCompartment = sbmlModel.createCompartment();
        sbmlCompartment.setId(TokenMangler.mangleToSName(vcStructures[i].getName()));
        sbmlCompartment.setName(vcStructures[i].getName());
        VCUnitDefinition sbmlSizeUnit = null;
        StructureTopology structTopology = getSelectedSimContext().getModel().getStructureTopology();
        Structure parentStructure = structTopology.getParentStructure(vcStructures[i]);
        if (vcStructures[i] instanceof Feature) {
            sbmlCompartment.setSpatialDimensions(3);
            String outside = null;
            if (parentStructure != null) {
                outside = TokenMangler.mangleToSName(parentStructure.getName());
            }
            if (outside != null) {
                if (outside.length() > 0) {
                    sbmlCompartment.setOutside(outside);
                }
            }
            sbmlSizeUnit = sbmlExportSpec.getVolumeUnits();
            UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
            sbmlCompartment.setUnits(unitDefn);
        } else if (vcStructures[i] instanceof Membrane) {
            Membrane vcMembrane = (Membrane) vcStructures[i];
            sbmlCompartment.setSpatialDimensions(2);
            Feature outsideFeature = structTopology.getOutsideFeature(vcMembrane);
            if (outsideFeature != null) {
                sbmlCompartment.setOutside(TokenMangler.mangleToSName(outsideFeature.getName()));
                sbmlSizeUnit = sbmlExportSpec.getAreaUnits();
                UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlSizeUnit);
                sbmlCompartment.setUnits(unitDefn);
            } else if (lg.isWarnEnabled()) {
                lg.warn(this.sbmlModel.getName() + " membrame " + vcMembrane.getName() + " has not outside feature");
            }
        }
        sbmlCompartment.setConstant(true);
        StructureMapping vcStructMapping = getSelectedSimContext().getGeometryContext().getStructureMapping(vcStructures[i]);
        try {
            if (vcStructMapping.getSizeParameter().getExpression() != null) {
                sbmlCompartment.setSize(vcStructMapping.getSizeParameter().getExpression().evaluateConstant());
            } else {
            // really no need to set sizes of compartments in spatial ..... ????
            // throw new RuntimeException("Compartment size not set for compartment \"" + vcStructures[i].getName() + "\" ; Please set size and try exporting again.");
            }
        } catch (cbit.vcell.parser.ExpressionException e) {
            // If it is in the catch block, it means that the compartment size was probably not a double, but an assignment.
            // Check if the expression for the compartment size is not null and add it as an assignment rule.
            Expression sizeExpr = vcStructMapping.getSizeParameter().getExpression();
            if (sizeExpr != null) {
                ASTNode ruleFormulaNode = getFormulaFromExpression(sizeExpr);
                AssignmentRule assignRule = sbmlModel.createAssignmentRule();
                assignRule.setVariable(vcStructures[i].getName());
                assignRule.setMath(ruleFormulaNode);
                // If compartmentSize is specified by an assignment rule, the 'constant' field should be set to 'false' (default - true).
                sbmlCompartment.setConstant(false);
                sbmlModel.addRule(assignRule);
            }
        }
        // Add the outside compartment of given compartment as annotation to the compartment.
        // This is required later while trying to read in compartments ...
        Element sbmlImportRelatedElement = null;
        // if (parentStructure != null) {
        // sbmlImportRelatedElement = new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
        // Element compartmentElement = new Element(XMLTags.OutsideCompartmentTag, sbml_vcml_ns);
        // compartmentElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(parentStructure.getName()));
        // sbmlImportRelatedElement.addContent(compartmentElement);
        // }
        // Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcStructures[i], sbmlCompartment, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcStructures[i], sbmlCompartment);
    }
}
Also used : StructureTopology(cbit.vcell.model.Model.StructureTopology) Compartment(org.sbml.jsbml.Compartment) AssignmentRule(org.sbml.jsbml.AssignmentRule) Element(org.jdom.Element) ExpressionException(cbit.vcell.parser.ExpressionException) Feature(cbit.vcell.model.Feature) StructureMapping(cbit.vcell.mapping.StructureMapping) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ASTNode(org.sbml.jsbml.ASTNode) Membrane(cbit.vcell.model.Membrane) Structure(cbit.vcell.model.Structure) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition)

Example 4 with UnitDefinition

use of org.sbml.jsbml.UnitDefinition in project vcell by virtualcell.

the class SBMLExporter method addReactions.

/**
 * addReactions comment.
 * @throws SbmlException
 * @throws XMLStreamException
 */
protected void addReactions() throws SbmlException, XMLStreamException {
    // Check if any reaction has electrical mapping
    boolean bCalculatePotential = false;
    StructureMapping[] structureMappings = getSelectedSimContext().getGeometryContext().getStructureMappings();
    for (int i = 0; i < structureMappings.length; i++) {
        if (structureMappings[i] instanceof MembraneMapping) {
            if (((MembraneMapping) structureMappings[i]).getCalculateVoltage()) {
                bCalculatePotential = true;
            }
        }
    }
    // If it does, VCell doesn't export it to SBML (no representation).
    if (bCalculatePotential) {
        throw new RuntimeException("This VCell model has Electrical mapping; cannot be exported to SBML at this time");
    }
    l2gMap.clear();
    ReactionSpec[] vcReactionSpecs = getSelectedSimContext().getReactionContext().getReactionSpecs();
    for (int i = 0; i < vcReactionSpecs.length; i++) {
        if (vcReactionSpecs[i].isExcluded()) {
            continue;
        }
        ReactionStep vcReactionStep = vcReactionSpecs[i].getReactionStep();
        // Create sbml reaction
        String rxnName = vcReactionStep.getName();
        org.sbml.jsbml.Reaction sbmlReaction = sbmlModel.createReaction();
        sbmlReaction.setId(org.vcell.util.TokenMangler.mangleToSName(rxnName));
        sbmlReaction.setName(rxnName);
        String rxnSbmlName = vcReactionStep.getSbmlName();
        if (rxnSbmlName != null && !rxnSbmlName.isEmpty()) {
            sbmlReaction.setName(rxnSbmlName);
        }
        // If the reactionStep is a flux reaction, add the details to the annotation (structure, carrier valence, flux carrier, fluxOption, etc.)
        // If reactionStep is a simple reaction, add annotation to indicate the structure of reaction.
        // Useful when roundtripping ...
        Element sbmlImportRelatedElement = null;
        // try {
        // sbmlImportRelatedElement = getAnnotationElement(vcReactionStep);
        // } catch (XmlParseException e1) {
        // e1.printStackTrace(System.out);
        // //			throw new RuntimeException("Error ");
        // }
        // Get annotation (RDF and non-RDF) for reactionStep from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcReactionStep, sbmlReaction, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcReactionStep, sbmlReaction);
        // Get reaction kineticLaw
        Kinetics vcRxnKinetics = vcReactionStep.getKinetics();
        org.sbml.jsbml.KineticLaw sbmlKLaw = sbmlReaction.createKineticLaw();
        try {
            // Convert expression from kinetics rate parameter into MathML and use libSBMl utilities to convert it to formula
            // (instead of directly using rate parameter's expression infix) to maintain integrity of formula :
            // for example logical and inequalities are not handled gracefully by libSBMl if expression.infix is used.
            final Expression localRateExpr;
            final Expression lumpedRateExpr;
            if (vcRxnKinetics instanceof DistributedKinetics) {
                localRateExpr = ((DistributedKinetics) vcRxnKinetics).getReactionRateParameter().getExpression();
                lumpedRateExpr = null;
            } else if (vcRxnKinetics instanceof LumpedKinetics) {
                localRateExpr = null;
                lumpedRateExpr = ((LumpedKinetics) vcRxnKinetics).getLumpedReactionRateParameter().getExpression();
            } else {
                throw new RuntimeException("unexpected Rate Law '" + vcRxnKinetics.getClass().getSimpleName() + "', not distributed or lumped type");
            }
            // if (vcRxnKinetics instanceof DistributedKinetics)
            // Expression correctedRateExpr = kineticsAdapter.getExpression();
            // Add parameters, if any, to the kineticLaw
            Kinetics.KineticsParameter[] vcKineticsParams = vcRxnKinetics.getKineticsParameters();
            // In the first pass thro' the kinetic params, store the non-numeric param names and expressions in arrays
            String[] kinParamNames = new String[vcKineticsParams.length];
            Expression[] kinParamExprs = new Expression[vcKineticsParams.length];
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (true) {
                    // Since local reaction parameters cannot be defined by a rule, such parameters (with rules) are exported as global parameters.
                    if ((vcKineticsParams[j].getRole() == Kinetics.ROLE_CurrentDensity && (!vcKineticsParams[j].getExpression().isZero())) || (vcKineticsParams[j].getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKineticsParams[j].getExpression().isZero()))) {
                        throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
                    }
                    if (!vcKineticsParams[j].getExpression().isNumeric()) {
                        // NON_NUMERIC KINETIC PARAM
                        // Create new name for kinetic parameter and store it in kinParamNames, store corresponding exprs in kinParamExprs
                        // Will be used later to add this param as global.
                        String newParamName = TokenMangler.mangleToSName(vcKineticsParams[j].getName() + "_" + vcReactionStep.getName());
                        kinParamNames[j] = newParamName;
                        kinParamExprs[j] = new Expression(vcKineticsParams[j].getExpression());
                    }
                }
            }
            // If so, these need to be added as global param (else the SBML doc will not be valid)
            for (int j = 0; j < vcKineticsParams.length; j++) {
                final KineticsParameter vcKParam = vcKineticsParams[j];
                if ((vcKParam.getRole() != Kinetics.ROLE_ReactionRate) && (vcKParam.getRole() != Kinetics.ROLE_LumpedReactionRate)) {
                    // if expression of kinetic param evaluates to a double, the parameter value is set
                    if ((vcKParam.getRole() == Kinetics.ROLE_CurrentDensity && (!vcKParam.getExpression().isZero())) || (vcKParam.getRole() == Kinetics.ROLE_LumpedCurrent && (!vcKParam.getExpression().isZero()))) {
                        throw new RuntimeException("Electric current not handled by SBML export; failed to export reaction \"" + vcReactionStep.getName() + "\" at this time");
                    }
                    if (vcKParam.getExpression().isNumeric()) {
                        // NUMERIC KINETIC PARAM
                        // check if it is used in other parameters that have expressions,
                        boolean bAddedParam = false;
                        String origParamName = vcKParam.getName();
                        String newParamName = TokenMangler.mangleToSName(origParamName + "_" + vcReactionStep.getName());
                        VCUnitDefinition vcUnit = vcKParam.getUnitDefinition();
                        for (int k = 0; k < vcKineticsParams.length; k++) {
                            if (kinParamExprs[k] != null) {
                                // The param could be in the expression for any other param
                                if (kinParamExprs[k].hasSymbol(origParamName)) {
                                    // mangle its name to avoid conflict with other globals
                                    if (globalParamNamesHash.get(newParamName) == null) {
                                        globalParamNamesHash.put(newParamName, newParamName);
                                        org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
                                        sbmlKinParam.setId(newParamName);
                                        sbmlKinParam.setValue(vcKParam.getConstantValue());
                                        final boolean constValue = vcKParam.isConstant();
                                        sbmlKinParam.setConstant(true);
                                        // Set SBML units for sbmlParam using VC units from vcParam
                                        if (!vcUnit.isTBD()) {
                                            UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
                                            sbmlKinParam.setUnits(unitDefn);
                                        }
                                        Pair<String, String> origParam = new Pair<String, String>(rxnName, origParamName);
                                        l2gMap.put(origParam, newParamName);
                                        bAddedParam = true;
                                    } else {
                                    // need to get another name for param and need to change all its refereces in the other kinParam euqations.
                                    }
                                    // update the expression to contain new name, since the globalparam has new name
                                    kinParamExprs[k].substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                                }
                            }
                        }
                        // If the param hasn't been added yet, it is definitely a local param. add it to kineticLaw now.
                        if (!bAddedParam) {
                            org.sbml.jsbml.LocalParameter sbmlKinParam = sbmlKLaw.createLocalParameter();
                            sbmlKinParam.setId(origParamName);
                            sbmlKinParam.setValue(vcKParam.getConstantValue());
                            System.out.println("tis constant " + sbmlKinParam.isExplicitlySetConstant());
                            // Set SBML units for sbmlParam using VC units from vcParam
                            if (!vcUnit.isTBD()) {
                                UnitDefinition unitDefn = getOrCreateSBMLUnit(vcUnit);
                                sbmlKinParam.setUnits(unitDefn);
                            }
                        } else {
                            // hence change its occurance in rate expression if it contains that param name
                            if (localRateExpr != null && localRateExpr.hasSymbol(origParamName)) {
                                localRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                            }
                            if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(origParamName)) {
                                lumpedRateExpr.substituteInPlace(new Expression(origParamName), new Expression(newParamName));
                            }
                        }
                    }
                }
            }
            // (using the kinParamNames and kinParamExprs above) to ensure uniqueness in the global parameter names.
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
                    String oldName = vcKineticsParams[j].getName();
                    String newName = kinParamNames[j];
                    // change the name of this parameter in the rate expression
                    if (localRateExpr != null && localRateExpr.hasSymbol(oldName)) {
                        localRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
                    }
                    if (lumpedRateExpr != null && lumpedRateExpr.hasSymbol(oldName)) {
                        lumpedRateExpr.substituteInPlace(new Expression(oldName), new Expression(newName));
                    }
                    // Change the occurence of this param in other param expressions
                    for (int k = 0; k < vcKineticsParams.length; k++) {
                        if (((vcKineticsParams[k].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[k].getExpression().isNumeric())) {
                            if (k != j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
                                // for all params except the current param represented by index j (whose name was changed)
                                kinParamExprs[k].substituteInPlace(new Expression(oldName), new Expression(newName));
                            }
                            if (k == j && vcKineticsParams[k].getExpression().hasSymbol(oldName)) {
                                throw new RuntimeException("A parameter cannot refer to itself in its expression");
                            }
                        }
                    }
                // end for - k
                }
            }
            // In the fifth pass thro' the kinetic params, the non-numeric params are added to the global params of the model
            for (int j = 0; j < vcKineticsParams.length; j++) {
                if (((vcKineticsParams[j].getRole() != Kinetics.ROLE_ReactionRate) && (vcKineticsParams[j].getRole() != Kinetics.ROLE_LumpedReactionRate)) && !(vcKineticsParams[j].getExpression().isNumeric())) {
                    // Now, add this param to the globalParamNamesHash and add a global parameter to the sbmlModel
                    String paramName = kinParamNames[j];
                    if (globalParamNamesHash.get(paramName) == null) {
                        globalParamNamesHash.put(paramName, paramName);
                    } else {
                    // need to get another name for param and need to change all its refereces in the other kinParam euqations.
                    }
                    Pair<String, String> origParam = new Pair<String, String>(rxnName, paramName);
                    // keeps its name but becomes a global (?)
                    l2gMap.put(origParam, paramName);
                    ASTNode paramFormulaNode = getFormulaFromExpression(kinParamExprs[j]);
                    AssignmentRule sbmlParamAssignmentRule = sbmlModel.createAssignmentRule();
                    sbmlParamAssignmentRule.setVariable(paramName);
                    sbmlParamAssignmentRule.setMath(paramFormulaNode);
                    org.sbml.jsbml.Parameter sbmlKinParam = sbmlModel.createParameter();
                    sbmlKinParam.setId(paramName);
                    if (!vcKineticsParams[j].getUnitDefinition().isTBD()) {
                        sbmlKinParam.setUnits(getOrCreateSBMLUnit(vcKineticsParams[j].getUnitDefinition()));
                    }
                    // Since the parameter is being specified by a Rule, its 'constant' field shoud be set to 'false' (default - true).
                    sbmlKinParam.setConstant(false);
                }
            }
            // end for (j) - fifth pass
            // After making all necessary adjustments to the rate expression, now set the sbmlKLaw.
            final ASTNode exprFormulaNode;
            if (lumpedRateExpr != null) {
                exprFormulaNode = getFormulaFromExpression(lumpedRateExpr);
            } else {
                if (bSpatial) {
                    exprFormulaNode = getFormulaFromExpression(localRateExpr);
                } else {
                    exprFormulaNode = getFormulaFromExpression(Expression.mult(localRateExpr, new Expression(vcReactionStep.getStructure().getName())));
                }
            }
            sbmlKLaw.setMath(exprFormulaNode);
        } catch (cbit.vcell.parser.ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error getting value of parameter : " + e.getMessage());
        }
        // Add kineticLaw to sbmlReaction - not needed now, since we use sbmlRxn.createKLaw() ??
        // sbmlReaction.setKineticLaw(sbmlKLaw);
        // Add reactants, products, modifiers
        // Simple reactions have catalysts, fluxes have 'flux'
        cbit.vcell.model.ReactionParticipant[] rxnParticipants = vcReactionStep.getReactionParticipants();
        for (ReactionParticipant rxnParticpant : rxnParticipants) {
            SimpleSpeciesReference ssr = null;
            SpeciesReference sr = null;
            // to get unique ID when the same species is both a reactant and a product
            String rolePostfix = "";
            if (rxnParticpant instanceof cbit.vcell.model.Reactant) {
                rolePostfix = "r";
                ssr = sr = sbmlReaction.createReactant();
            } else if (rxnParticpant instanceof cbit.vcell.model.Product) {
                rolePostfix = "p";
                ssr = sr = sbmlReaction.createProduct();
            }
            if (rxnParticpant instanceof cbit.vcell.model.Catalyst) {
                rolePostfix = "c";
                ssr = sbmlReaction.createModifier();
            }
            if (ssr != null) {
                ssr.setSpecies(rxnParticpant.getSpeciesContext().getName());
            }
            if (sr != null) {
                sr.setStoichiometry(Double.parseDouble(Integer.toString(rxnParticpant.getStoichiometry())));
                String modelUniqueName = vcReactionStep.getName() + '_' + rxnParticpant.getName() + rolePostfix;
                sr.setId(TokenMangler.mangleToSName(modelUniqueName));
                // SBML-REVIEW
                sr.setConstant(true);
            // int rcode = sr.appendNotes("<
            // we know that in VCell we can't override stoichiometry anywhere, below is no longer questionable
            // try {
            // SBMLHelper.addNote(sr, "VCELL guess: how do we know if reaction is constant?");
            // } catch (Exception e) {
            // e.printStackTrace();
            // }
            }
        }
        sbmlReaction.setFast(vcReactionSpecs[i].isFast());
        // this attribute is mandatory for L3, optional for L2. So explicitly setting value.
        sbmlReaction.setReversible(true);
        if (bSpatial) {
            // set compartment for reaction if spatial
            sbmlReaction.setCompartment(vcReactionStep.getStructure().getName());
            // CORE  HAS ALT MATH true
            // set the "isLocal" attribute = true (in 'spatial' namespace) for each species
            SpatialReactionPlugin srplugin = (SpatialReactionPlugin) sbmlReaction.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            srplugin.setIsLocal(vcRxnKinetics instanceof DistributedKinetics);
        }
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) LumpedKinetics(cbit.vcell.model.LumpedKinetics) Element(org.jdom.Element) StructureMapping(cbit.vcell.mapping.StructureMapping) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) SpeciesReference(org.sbml.jsbml.SpeciesReference) SimpleSpeciesReference(org.sbml.jsbml.SimpleSpeciesReference) ASTNode(org.sbml.jsbml.ASTNode) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) Pair(org.vcell.util.Pair) DistributedKinetics(cbit.vcell.model.DistributedKinetics) SpatialReactionPlugin(org.sbml.jsbml.ext.spatial.SpatialReactionPlugin) ReactionSpec(cbit.vcell.mapping.ReactionSpec) AssignmentRule(org.sbml.jsbml.AssignmentRule) ExpressionException(cbit.vcell.parser.ExpressionException) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) ReactionStep(cbit.vcell.model.ReactionStep) Kinetics(cbit.vcell.model.Kinetics) DistributedKinetics(cbit.vcell.model.DistributedKinetics) LumpedKinetics(cbit.vcell.model.LumpedKinetics) ReactionParticipant(cbit.vcell.model.ReactionParticipant)

Example 5 with UnitDefinition

use of org.sbml.jsbml.UnitDefinition in project vcell by virtualcell.

the class SBMLUnitTranslatorTest method testSBMLtoVCell.

@Test
public void testSBMLtoVCell() throws XMLStreamException, IOException, SbmlException {
    File[] sbmlFiles = getBiomodelsCuratedSBMLFiles();
    // };
    for (File sbmlFile : sbmlFiles) {
        if (sbmlFile.getName().equals("BIOMD0000000539.xml")) {
            System.err.println("skipping this model, seems like a bug in jsbml  RenderParser.processEndDocument() ... line 403 ... wrong constant for extension name");
            continue;
        }
        SBMLDocument doc = SBMLReader.read(sbmlFile);
        BioModel bioModel = new BioModel(null);
        VCUnitSystem unitSystem = bioModel.getModel().getUnitSystem();
        Model sbmlModel = doc.getModel();
        ListOf<UnitDefinition> listOfUnitDefinitions = sbmlModel.getListOfUnitDefinitions();
        for (UnitDefinition sbmlUnitDef : listOfUnitDefinitions) {
            VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
            UnitDefinition new_sbmlUnitDef = SBMLUnitTranslator.getSBMLUnitDefinition(vcUnit, 3, 1, unitSystem);
            VCUnitDefinition new_vcUnit = SBMLUnitTranslator.getVCUnitDefinition(new_sbmlUnitDef, unitSystem);
            if (!vcUnit.getSymbol().equals(new_vcUnit.getSymbol())) {
                System.err.println("orig vcUnit '" + vcUnit.getSymbol() + "' doesn't match new vcUnit '" + new_vcUnit.getSymbol() + "'");
            }
            // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
            System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            if (sbmlUnitDef.getNumUnits() > 1) {
                System.out.println("vcUnit = " + vcUnit.getSymbol());
                for (Unit unit : sbmlUnitDef.getListOfUnits()) {
                    try {
                        // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
                        System.out.println("    vcUnit = " + unit);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("found bigger unit, " + sbmlUnitDef);
            }
        }
        if (sbmlFile == sbmlFiles[0]) {
            System.out.println("sbml length unit = " + sbmlModel.getLengthUnitsInstance() + ", idref=" + sbmlModel.getLengthUnits());
            System.out.println("sbml area unit = " + sbmlModel.getAreaUnitsInstance() + ", idref=" + sbmlModel.getAreaUnits());
            System.out.println("sbml volume unit = " + sbmlModel.getVolumeUnitsInstance() + ", idref=" + sbmlModel.getVolumeUnits());
            System.out.println("sbml time unit = " + sbmlModel.getTimeUnitsInstance() + ", idref=" + sbmlModel.getTimeUnits());
            System.out.println("sbml extent unit = " + sbmlModel.getExtentUnitsInstance() + ", idref=" + sbmlModel.getExtentUnits());
            System.out.println("sbml substance unit = " + sbmlModel.getSubstanceUnitsInstance() + ", idref=" + sbmlModel.getSubstanceUnits());
            for (UnitDefinition sbmlUnitDef : sbmlModel.getListOfPredefinedUnitDefinitions()) {
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isAvogadro()) {
                    continue;
                }
                if (sbmlUnitDef.getNumUnits() == 1 && sbmlUnitDef.getUnit(0).isKatal()) {
                    continue;
                }
                VCUnitDefinition vcUnit = SBMLUnitTranslator.getVCUnitDefinition(sbmlUnitDef, unitSystem);
                // System.out.println("sbmlUnit = "+sbmlUnitDef.toString()+", vcUnit = "+vcUnit.getSymbol());
                System.out.println("sbmlUnit(" + sbmlUnitDef.getClass().getName() + ", builtin=" + sbmlUnitDef.isVariantOfSubstance() + ") = " + sbmlUnitDef.toString() + ", id=" + sbmlUnitDef.getId() + ",  name=" + sbmlUnitDef.getName() + ",   vcUnit = " + vcUnit.getSymbol());
            // for (Unit unit : sbmlUnitDef.getListOfUnits()){
            // try {
            // VCUnitDefinition vcUnit = unitSystem.getInstance(unit.getKind().getName());
            // System.out.println("    vcUnit = "+vcUnit.getSymbol());
            // }catch (Exception e){
            // e.printStackTrace();
            // }
            // }
            }
        }
    }
}
Also used : VCUnitSystem(cbit.vcell.units.VCUnitSystem) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) SBMLDocument(org.sbml.jsbml.SBMLDocument) BioModel(cbit.vcell.biomodel.BioModel) Model(org.sbml.jsbml.Model) BioModel(cbit.vcell.biomodel.BioModel) Unit(org.sbml.jsbml.Unit) File(java.io.File) UnitDefinition(org.sbml.jsbml.UnitDefinition) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) IOException(java.io.IOException) XMLStreamException(javax.xml.stream.XMLStreamException) Test(org.junit.Test)

Aggregations

VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)9 UnitDefinition (org.sbml.jsbml.UnitDefinition)9 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)6 StructureMapping (cbit.vcell.mapping.StructureMapping)5 Expression (cbit.vcell.parser.Expression)5 ExpressionException (cbit.vcell.parser.ExpressionException)5 ASTNode (org.sbml.jsbml.ASTNode)5 BioModel (cbit.vcell.biomodel.BioModel)4 AssignmentRule (org.sbml.jsbml.AssignmentRule)4 Compartment (org.sbml.jsbml.Compartment)4 Model (cbit.vcell.model.Model)3 XMLStreamException (javax.xml.stream.XMLStreamException)3 ImageException (cbit.image.ImageException)2 MappingException (cbit.vcell.mapping.MappingException)2 StructureMappingParameter (cbit.vcell.mapping.StructureMapping.StructureMappingParameter)2 MathException (cbit.vcell.math.MathException)2 MatrixException (cbit.vcell.matrix.MatrixException)2 ModelException (cbit.vcell.model.ModelException)2 SpeciesContext (cbit.vcell.model.SpeciesContext)2 VCUnitSystem (cbit.vcell.units.VCUnitSystem)2