Search in sources :

Example 91 with Model

use of cbit.vcell.model.Model in project vcell by virtualcell.

the class ModelOptimizationSpec method refreshDependencies.

/**
 * Insert the method's description here.
 * Creation date: (12/19/2005 3:20:34 PM)
 */
public void refreshDependencies(boolean isRemoveUncoupledParameters) {
    if (getSimulationContext() != null) {
        // remove listeners - simContext, mathDesc, model, spContextSpec, reactionSteps & kinetics
        getSimulationContext().removePropertyChangeListener(this);
        Model model = getSimulationContext().getModel();
        updateListenersList(model, false);
        // add listeners - simContext, mathDesc, model, spContextSpec, reactionSteps & kinetics
        getSimulationContext().addPropertyChangeListener(this);
        updateListenersList(model, true);
    }
    if (isRemoveUncoupledParameters) {
    // System.err.println("not calling removeUncoupledParameters() during ModelOptimizationSpec.refreshDependencies() ... need to invoke removeUncoupledParameters functionality a different way");
    // removeUncoupledParameters();
    }
}
Also used : Model(cbit.vcell.model.Model)

Example 92 with Model

use of cbit.vcell.model.Model in project vcell by virtualcell.

the class PathwayMapping method parseReaction.

private ReactionParticipant[] parseReaction(ReactionStep reactionStep, BioModel bioModel, RelationshipObject relationshipObject) throws ExpressionException, PropertyVetoException {
    if (reactionStep == null || bioModel == null || bioModel.getRelationshipModel() == null) {
        return null;
    }
    // create the reaction equation string
    String leftHand = getParticipantsString(((Conversion) relationshipObject.getBioPaxObject()).getLeft());
    String rightHand = getParticipantsString(((Conversion) relationshipObject.getBioPaxObject()).getRight());
    StringTokenizer st = new StringTokenizer(leftHand, "+");
    HashMap<String, SpeciesContext> speciesContextMap = new HashMap<String, SpeciesContext>();
    ArrayList<ReactionParticipant> rplist = new ArrayList<ReactionParticipant>();
    // create and add reaction participants to list for left-hand side of equation
    Model model = bioModel.getModel();
    Structure structure = reactionStep.getStructure();
    while (st.hasMoreElements()) {
        String nextToken = st.nextToken().trim();
        if (nextToken.length() == 0) {
            continue;
        }
        int stoichiIndex = 0;
        while (true) {
            if (Character.isDigit(nextToken.charAt(stoichiIndex))) {
                stoichiIndex++;
            } else {
                break;
            }
        }
        int stoichi = 1;
        String tmp = nextToken.substring(0, stoichiIndex);
        if (tmp.length() > 0) {
            stoichi = Integer.parseInt(tmp);
        }
        String var = nextToken.substring(stoichiIndex).trim();
        // get speciesContext object based on its name
        // if the speciesContext is not existed, create a new one
        SpeciesContext sc = model.getSpeciesContext(var);
        if (sc == null) {
            sc = speciesContextMap.get(var);
            if (sc == null) {
                // get species object based on its name
                // if the species is not existed, create a new one
                Species species = model.getSpecies(var);
                if (species == null) {
                    species = new Species(var, null);
                }
                sc = new SpeciesContext(species, structure);
                sc.setName(var);
                speciesContextMap.put(var, sc);
            }
        }
        // add the existed speciesContext objects or new speciesContext objects to reaction participant list
        if (reactionStep instanceof SimpleReaction || reactionStep instanceof FluxReaction) {
            rplist.add(new Reactant(null, (SimpleReaction) reactionStep, sc, stoichi));
        }
    }
    // create and add reaction participants to list for right-hand side of equation
    st = new StringTokenizer(rightHand, "+");
    while (st.hasMoreElements()) {
        String nextToken = st.nextToken().trim();
        if (nextToken.length() == 0) {
            continue;
        }
        int stoichiIndex = 0;
        while (true) {
            if (Character.isDigit(nextToken.charAt(stoichiIndex))) {
                stoichiIndex++;
            } else {
                break;
            }
        }
        int stoichi = 1;
        String tmp = nextToken.substring(0, stoichiIndex);
        if (tmp.length() > 0) {
            stoichi = Integer.parseInt(tmp);
        }
        String var = nextToken.substring(stoichiIndex);
        SpeciesContext sc = model.getSpeciesContext(var);
        if (sc == null) {
            sc = speciesContextMap.get(var);
            if (sc == null) {
                Species species = model.getSpecies(var);
                if (species == null) {
                    species = new Species(var, null);
                }
                sc = new SpeciesContext(species, structure);
                sc.setName(var);
                speciesContextMap.put(var, sc);
            }
        }
        if (reactionStep instanceof SimpleReaction || reactionStep instanceof FluxReaction) {
            rplist.add(new Product(null, (SimpleReaction) reactionStep, sc, stoichi));
        }
    }
    return rplist.toArray(new ReactionParticipant[0]);
}
Also used : SimpleReaction(cbit.vcell.model.SimpleReaction) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Product(cbit.vcell.model.Product) FluxReaction(cbit.vcell.model.FluxReaction) SpeciesContext(cbit.vcell.model.SpeciesContext) Reactant(cbit.vcell.model.Reactant) StringTokenizer(java.util.StringTokenizer) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) Structure(cbit.vcell.model.Structure) ReactionParticipant(cbit.vcell.model.ReactionParticipant) Species(cbit.vcell.model.Species)

Example 93 with Model

use of cbit.vcell.model.Model in project vcell by virtualcell.

the class SBMLExporter method addSpecies.

/**
 * addSpecies comment.
 * @throws XMLStreamException
 * @throws SbmlException
 */
protected void addSpecies() throws XMLStreamException, SbmlException {
    Model vcModel = vcBioModel.getModel();
    SpeciesContext[] vcSpeciesContexts = vcModel.getSpeciesContexts();
    for (int i = 0; i < vcSpeciesContexts.length; i++) {
        org.sbml.jsbml.Species sbmlSpecies = sbmlModel.createSpecies();
        sbmlSpecies.setId(vcSpeciesContexts[i].getName());
        // Assuming that at this point, the compartment(s) for the model are already filled in.
        Compartment compartment = sbmlModel.getCompartment(TokenMangler.mangleToSName(vcSpeciesContexts[i].getStructure().getName()));
        if (compartment != null) {
            sbmlSpecies.setCompartment(compartment.getId());
        }
        // 'hasSubstanceOnly' field will be 'false', since VC deals only with initial concentrations and not initial amounts.
        sbmlSpecies.setHasOnlySubstanceUnits(false);
        // Get (and set) the initial concentration value
        if (getSelectedSimContext() == null) {
            throw new RuntimeException("No simcontext (application) specified; Cannot proceed.");
        }
        // Get the speciesContextSpec in the simContext corresponding to the 'speciesContext'; and extract its initial concentration value.
        SpeciesContextSpec vcSpeciesContextsSpec = getSelectedSimContext().getReactionContext().getSpeciesContextSpec(vcSpeciesContexts[i]);
        // we need to convert concentration from uM -> molecules/um3; this can be achieved by dividing by KMOLE.
        try {
            sbmlSpecies.setInitialConcentration(vcSpeciesContextsSpec.getInitialConditionParameter().getExpression().evaluateConstant());
        } catch (cbit.vcell.parser.ExpressionException e) {
            // If exporting to L2V3, if species concentration is not an expr with x, y, z or other species, add as InitialAssignment, else complain.
            if (vcSpeciesContextsSpec.getInitialConditionParameter().getExpression() != null) {
                Expression initConcExpr = vcSpeciesContextsSpec.getInitialConditionParameter().getExpression();
                if ((sbmlLevel == 2 && sbmlVersion >= 3) || (sbmlLevel > 2)) {
                    // L2V3 and above - add expression as init assignment
                    ASTNode initAssgnMathNode = getFormulaFromExpression(initConcExpr);
                    InitialAssignment initAssignment = sbmlModel.createInitialAssignment();
                    initAssignment.setSymbol(vcSpeciesContexts[i].getName());
                    initAssignment.setMath(initAssgnMathNode);
                } else {
                    // L2V1 (or L1V2 also??)
                    // L2V1 (and L1V2?) and species is 'fixed' (constant), and not fn of x,y,z, other sp, add expr as assgn rule
                    ASTNode assgnRuleMathNode = getFormulaFromExpression(initConcExpr);
                    AssignmentRule assgnRule = sbmlModel.createAssignmentRule();
                    assgnRule.setVariable(vcSpeciesContexts[i].getName());
                    assgnRule.setMath(assgnRuleMathNode);
                }
            }
        }
        // Get (and set) the boundary condition value
        boolean bBoundaryCondition = getBoundaryCondition(vcSpeciesContexts[i]);
        sbmlSpecies.setBoundaryCondition(bBoundaryCondition);
        // mandatory for L3, optional for L2
        sbmlSpecies.setConstant(false);
        // set species substance units as 'molecules' - same as defined in the model; irrespective of it is in surface or volume.
        UnitDefinition unitDefn = getOrCreateSBMLUnit(sbmlExportSpec.getSubstanceUnits());
        sbmlSpecies.setSubstanceUnits(unitDefn);
        // need to do the following if exporting to SBML spatial
        if (bSpatial) {
            // Required for setting BoundaryConditions : structureMapping for vcSpeciesContext[i] & sbmlGeometry.coordinateComponents
            StructureMapping sm = getSelectedSimContext().getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure());
            SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.getGeometry();
            CoordinateComponent ccX = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getX().getName());
            CoordinateComponent ccY = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getY().getName());
            CoordinateComponent ccZ = sbmlGeometry.getListOfCoordinateComponents().get(vcModel.getZ().getName());
            // add diffusion, advection, boundary condition parameters for species, if they exist
            Parameter[] scsParams = vcSpeciesContextsSpec.getParameters();
            if (scsParams != null) {
                for (int j = 0; j < scsParams.length; j++) {
                    if (scsParams[j] != null) {
                        SpeciesContextSpecParameter scsParam = (SpeciesContextSpecParameter) scsParams[j];
                        // no need to add parameters in SBML for init conc or init count
                        int role = scsParam.getRole();
                        switch(role) {
                            case SpeciesContextSpec.ROLE_BoundaryValueXm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueXp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueYm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueYp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueZm:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_BoundaryValueZp:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_DiffusionRate:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_InitialConcentration:
                                {
                                    // done elsewhere??
                                    continue;
                                // break;
                                }
                            case SpeciesContextSpec.ROLE_InitialCount:
                                {
                                    // done elsewhere??
                                    continue;
                                // break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityX:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityY:
                                {
                                    break;
                                }
                            case SpeciesContextSpec.ROLE_VelocityZ:
                                {
                                    break;
                                }
                            default:
                                {
                                    throw new RuntimeException("SpeciesContext Specification parameter with role " + SpeciesContextSpec.RoleNames[role] + " not yet supported for SBML export");
                                }
                        }
                        // if diffusion is 0 && vel terms are not specified, boundary condition not present
                        if (vcSpeciesContextsSpec.isAdvecting() || vcSpeciesContextsSpec.isDiffusing()) {
                            Expression diffExpr = vcSpeciesContextsSpec.getDiffusionParameter().getExpression();
                            boolean bDiffExprNull = (diffExpr == null);
                            boolean bDiffExprIsZero = false;
                            if (!bDiffExprNull && diffExpr.isNumeric()) {
                                try {
                                    bDiffExprIsZero = (diffExpr.evaluateConstant() == 0.0);
                                } catch (Exception e) {
                                    e.printStackTrace(System.out);
                                    throw new RuntimeException("Unable to evalute numeric value of diffusion parameter for speciesContext '" + vcSpeciesContexts[i] + "'.");
                                }
                            }
                            boolean bDiffusionZero = (bDiffExprNull || bDiffExprIsZero);
                            Expression velX_Expr = vcSpeciesContextsSpec.getVelocityXParameter().getExpression();
                            SpatialQuantity[] velX_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.X);
                            boolean bVelX_ExprIsNull = (velX_Expr == null && velX_Quantities.length == 0);
                            Expression velY_Expr = vcSpeciesContextsSpec.getVelocityYParameter().getExpression();
                            SpatialQuantity[] velY_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Y);
                            boolean bVelY_ExprIsNull = (velY_Expr == null && velY_Quantities.length == 0);
                            Expression velZ_Expr = vcSpeciesContextsSpec.getVelocityZParameter().getExpression();
                            SpatialQuantity[] velZ_Quantities = vcSpeciesContextsSpec.getVelocityQuantities(QuantityComponent.Z);
                            boolean bVelZ_ExprIsNull = (velZ_Expr == null && velZ_Quantities.length == 0);
                            boolean bAdvectionNull = (bVelX_ExprIsNull && bVelY_ExprIsNull && bVelZ_ExprIsNull);
                            if (bDiffusionZero && bAdvectionNull) {
                                continue;
                            }
                        }
                        // for example, if scsParam is BC_Zm and if coordinateComponent 'ccZ' is null, no SBML parameter should be created for BC_Zm
                        if ((((role == SpeciesContextSpec.ROLE_BoundaryValueXm) || (role == SpeciesContextSpec.ROLE_BoundaryValueXp)) && (ccX == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueYm) || (role == SpeciesContextSpec.ROLE_BoundaryValueYp)) && (ccY == null)) || (((role == SpeciesContextSpec.ROLE_BoundaryValueZm) || (role == SpeciesContextSpec.ROLE_BoundaryValueZp)) && (ccZ == null))) {
                            continue;
                        }
                        org.sbml.jsbml.Parameter sbmlParam = createSBMLParamFromSpeciesParam(vcSpeciesContexts[i], (SpeciesContextSpecParameter) scsParams[j]);
                        if (sbmlParam != null) {
                            BoundaryConditionType vcBCType_Xm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXm();
                            BoundaryConditionType vcBCType_Xp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeXp();
                            BoundaryConditionType vcBCType_Ym = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYm();
                            BoundaryConditionType vcBCType_Yp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeYp();
                            BoundaryConditionType vcBCType_Zm = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZm();
                            BoundaryConditionType vcBCType_Zp = vcSelectedSimContext.getGeometryContext().getStructureMapping(vcSpeciesContexts[i].getStructure()).getBoundaryConditionTypeZp();
                            SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
                            if (role == SpeciesContextSpec.ROLE_DiffusionRate) {
                                // set diffusionCoefficient element in SpatialParameterPlugin for param
                                DiffusionCoefficient sbmlDiffCoeff = new DiffusionCoefficient();
                                sbmlDiffCoeff.setVariable(vcSpeciesContexts[i].getName());
                                sbmlDiffCoeff.setDiffusionKind(DiffusionKind.isotropic);
                                sbmlDiffCoeff.setSpeciesRef(vcSpeciesContexts[i].getName());
                                spplugin.setParamType(sbmlDiffCoeff);
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXm) && (ccX != null)) {
                                // set BoundaryCondn Xm element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCXm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCXm);
                                sbmlBCXm.setType(getBoundaryConditionKind(vcBCType_Xm));
                                sbmlBCXm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCXm.setCoordinateBoundary(ccX.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueXp) && (ccX != null)) {
                                // set BoundaryCondn Xp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCXp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCXp);
                                sbmlBCXp.setType(getBoundaryConditionKind(vcBCType_Xp));
                                sbmlBCXp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCXp.setType(sm.getBoundaryConditionTypeXp().boundaryTypeStringValue());
                                sbmlBCXp.setCoordinateBoundary(ccX.getBoundaryMaximum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYm) && (ccY != null)) {
                                // set BoundaryCondn Ym element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCYm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCYm);
                                sbmlBCYm.setType(getBoundaryConditionKind(vcBCType_Yp));
                                sbmlBCYm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCYm.setType(sm.getBoundaryConditionTypeYm().boundaryTypeStringValue());
                                sbmlBCYm.setCoordinateBoundary(ccY.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueYp) && (ccY != null)) {
                                // set BoundaryCondn Yp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCYp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCYp);
                                sbmlBCYp.setType(getBoundaryConditionKind(vcBCType_Yp));
                                sbmlBCYp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCYp.setType(sm.getBoundaryConditionTypeYp().boundaryTypeStringValue());
                                sbmlBCYp.setCoordinateBoundary(ccY.getBoundaryMaximum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZm) && (ccZ != null)) {
                                // set BoundaryCondn Zm element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCZm = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCZm);
                                sbmlBCZm.setType(getBoundaryConditionKind(vcBCType_Zm));
                                sbmlBCZm.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCZm.setType(sm.getBoundaryConditionTypeZm().boundaryTypeStringValue());
                                sbmlBCZm.setCoordinateBoundary(ccZ.getBoundaryMinimum().getId());
                            }
                            if ((role == SpeciesContextSpec.ROLE_BoundaryValueZp) && (ccZ != null)) {
                                // set BoundaryCondn Zp element in SpatialParameterPlugin for param
                                BoundaryCondition sbmlBCZp = new BoundaryCondition();
                                spplugin.setParamType(sbmlBCZp);
                                sbmlBCZp.setType(getBoundaryConditionKind(vcBCType_Zp));
                                sbmlBCZp.setVariable(vcSpeciesContexts[i].getName());
                                sbmlBCZp.setType(sm.getBoundaryConditionTypeZp().boundaryTypeStringValue());
                                sbmlBCZp.setCoordinateBoundary(ccZ.getBoundaryMaximum().getId());
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityX) {
                                // set advectionCoeff X element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffX = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffX);
                                sbmlAdvCoeffX.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffX.setCoordinate(CoordinateKind.cartesianX);
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityY) {
                                // set advectionCoeff Y element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffY = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffY);
                                sbmlAdvCoeffY.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffY.setCoordinate(CoordinateKind.cartesianY);
                            }
                            if (role == SpeciesContextSpec.ROLE_VelocityZ) {
                                // set advectionCoeff Z element in SpatialParameterPlugin for param
                                AdvectionCoefficient sbmlAdvCoeffZ = new AdvectionCoefficient();
                                spplugin.setParamType(sbmlAdvCoeffZ);
                                sbmlAdvCoeffZ.setVariable(vcSpeciesContexts[i].getName());
                                sbmlAdvCoeffZ.setCoordinate(CoordinateKind.cartesianZ);
                            }
                        }
                    // if sbmlParam != null
                    }
                // if scsParams[j] != null
                }
            // end for scsParams
            }
        // end scsParams != null
        }
        // end if (bSpatial)
        // Add the common name of species to annotation, and add an annotation element to the species.
        // This is required later while trying to read in fluxes ...
        // new Element(XMLTags.VCellRelatedInfoTag, sbml_vcml_ns);
        Element sbmlImportRelatedElement = null;
        // Element speciesElement = new Element(XMLTags.SpeciesTag, sbml_vcml_ns);
        // speciesElement.setAttribute(XMLTags.NameAttrTag, TokenMangler.mangleToSName(vcSpeciesContexts[i].getSpecies().getCommonName()));
        // sbmlImportRelatedElement.addContent(speciesElement);
        // Get RDF annotation for species from SBMLAnnotationUtils
        sbmlAnnotationUtil.writeAnnotation(vcSpeciesContexts[i].getSpecies(), sbmlSpecies, sbmlImportRelatedElement);
        // Now set notes,
        sbmlAnnotationUtil.writeNotes(vcSpeciesContexts[i].getSpecies(), sbmlSpecies);
    }
}
Also used : Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) BoundaryConditionType(cbit.vcell.math.BoundaryConditionType) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) ASTNode(org.sbml.jsbml.ASTNode) SpatialQuantity(cbit.vcell.mapping.spatial.SpatialObject.SpatialQuantity) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) AdvectionCoefficient(org.sbml.jsbml.ext.spatial.AdvectionCoefficient) AssignmentRule(org.sbml.jsbml.AssignmentRule) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) ExpressionException(cbit.vcell.parser.ExpressionException) DiffusionCoefficient(org.sbml.jsbml.ext.spatial.DiffusionCoefficient) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) InitialAssignment(org.sbml.jsbml.InitialAssignment) Expression(cbit.vcell.parser.Expression) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) Parameter(cbit.vcell.model.Parameter) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(cbit.vcell.mapping.ParameterContext.LocalParameter)

Example 94 with Model

use of cbit.vcell.model.Model in project vcell by virtualcell.

the class SBMLExporter method addParameters.

/**
 * addKineticParameterUnits:
 * @throws SbmlException
 */
// private void addKineticAndGlobalParameterUnits() throws SbmlException {
// 
// //
// // Get all kinetic parameters from simple reactions and flux reactions from the Biomodel
// // And all Model (global) parameters from Model.
// // For each parameter,
// //		get its unit (VCunitDefinition)
// //		check if it is part of unitsList - if so, continue
// //		check if it is a base unit - if so, continue
// //		else, get the converted unit (VC -> SBML)
// //		add unit to sbmlModel unit definition
// //
// 
// Vector<Parameter> paramsVector = new Vector<Parameter>();
// // Add globals
// Model vcModel = vcBioModel.getModel();
// ModelParameter[] globalParams = vcModel.getModelParameters();
// for (int i = 0; i < globalParams.length; i++) {
// paramsVector.addElement(globalParams[i]);
// }
// // Add reaction kinetic parameters
// ReactionStep[] vcReactions = vcModel.getReactionSteps();
// for (int i = 0; i < vcReactions.length; i++) {
// Kinetics rxnKinetics = vcReactions[i].getKinetics();
// Parameter[] kineticParams = rxnKinetics.getKineticsParameters();
// for (int j = 0; j < kineticParams.length; j++) {
// paramsVector.addElement(kineticParams[j]);
// }
// }
// 
// for (int i = 0; i < paramsVector.size(); i++){
// Parameter param = (Parameter)paramsVector.elementAt(i);
// VCUnitDefinition paramUnitDefn = param.getUnitDefinition();
// if (paramUnitDefn == null || paramUnitDefn.isTBD()) {
// continue;
// }
// String unitSymbol = org.vcell.util.TokenMangler.mangleToSName(paramUnitDefn.getSymbol());
// if (unitSymbol == null) {
// continue;
// }
// getOrCreateSBMLUnit(paramUnitDefn);
// }
// }
/**
 * At present, the Virtual cell doesn't support global parameters
 * @throws SbmlException
 */
protected void addParameters() throws ExpressionException, SbmlException {
    Model vcModel = getSelectedSimContext().getModel();
    // add VCell global parameters to the SBML listofParameters
    ModelParameter[] vcGlobalParams = vcModel.getModelParameters();
    if (vcGlobalParams != null) {
        for (ModelParameter vcParam : vcGlobalParams) {
            org.sbml.jsbml.Parameter sbmlParam = sbmlModel.createParameter();
            sbmlParam.setId(vcParam.getName());
            sbmlParam.setConstant(vcParam.isConstant());
            Expression paramExpr = new Expression(vcParam.getExpression());
            boolean bParamIsNumeric = true;
            if (paramExpr.isNumeric()) {
                // For a VCell global param, if it is numeric, it has a constant value and is not defined by a rule, hence set Constant = true.
                sbmlParam.setValue(paramExpr.evaluateConstant());
                // the expression for modelParam might be numeric, but modelParam could have a rate rule, if so, set constant attribute to 'false'
                if (getSelectedSimContext().getRateRule(vcParam) != null) {
                    bParamIsNumeric = false;
                }
            } else {
                // non-numeric VCell global parameter will be defined by a (assignment) rule, hence mark Constant = false.
                bParamIsNumeric = false;
                // add assignment rule for param
                ASTNode paramFormulaNode = getFormulaFromExpression(paramExpr);
                AssignmentRule sbmlParamAssignmentRule = sbmlModel.createAssignmentRule();
                sbmlParamAssignmentRule.setVariable(vcParam.getName());
                sbmlParamAssignmentRule.setMath(paramFormulaNode);
            }
            sbmlParam.setConstant(bParamIsNumeric);
            VCUnitDefinition vcParamUnit = vcParam.getUnitDefinition();
            if (!vcParamUnit.isTBD()) {
                sbmlParam.setUnits(getOrCreateSBMLUnit(vcParamUnit));
            }
        }
    }
}
Also used : ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) AssignmentRule(org.sbml.jsbml.AssignmentRule) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) ASTNode(org.sbml.jsbml.ASTNode)

Example 95 with Model

use of cbit.vcell.model.Model in project vcell by virtualcell.

the class SBMLExporter method addGeometry.

private void addGeometry() throws SbmlException {
    SpatialModelPlugin mplugin = (SpatialModelPlugin) sbmlModel.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    // Creates a geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = mplugin.createGeometry();
    sbmlGeometry.setCoordinateSystem(GeometryKind.cartesian);
    sbmlGeometry.setSpatialId("vcell");
    Geometry vcGeometry = getSelectedSimContext().getGeometry();
    Model vcModel = getSelectedSimContext().getModel();
    // 
    // list of CoordinateComponents : 1 if geometry is 1-d, 2 if geometry is 2-d, 3 if geometry is 3-d
    // 
    int dimension = vcGeometry.getDimension();
    Extent vcExtent = vcGeometry.getExtent();
    Origin vcOrigin = vcGeometry.getOrigin();
    // add x coordinate component
    CoordinateComponent xComp = sbmlGeometry.createCoordinateComponent();
    xComp.setSpatialId(vcModel.getX().getName());
    xComp.setType(CoordinateKind.cartesianX);
    final UnitDefinition sbmlUnitDef_length = getOrCreateSBMLUnit(vcModel.getUnitSystem().getLengthUnit());
    xComp.setUnits(sbmlUnitDef_length);
    Boundary minX = new Boundary();
    xComp.setBoundaryMinimum(minX);
    minX.setSpatialId("Xmin");
    minX.setValue(vcOrigin.getX());
    Boundary maxX = new Boundary();
    xComp.setBoundaryMaximum(maxX);
    maxX.setSpatialId("Xmax");
    maxX.setValue(vcOrigin.getX() + (vcExtent.getX()));
    org.sbml.jsbml.Parameter pX = sbmlModel.createParameter();
    pX.setId(vcModel.getX().getName());
    pX.setValue(0.0);
    pX.setConstant(false);
    pX.setUnits(sbmlUnitDef_length);
    SpatialParameterPlugin spPluginPx = (SpatialParameterPlugin) pX.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
    SpatialSymbolReference spSymRefPx = new SpatialSymbolReference();
    spPluginPx.setParamType(spSymRefPx);
    spSymRefPx.setSpatialRef(xComp.getSpatialId());
    // add y coordinate component
    if (dimension == 2 || dimension == 3) {
        CoordinateComponent yComp = sbmlGeometry.createCoordinateComponent();
        yComp.setSpatialId(vcModel.getY().getName());
        yComp.setType(CoordinateKind.cartesianY);
        yComp.setUnits(sbmlUnitDef_length);
        Boundary minY = new Boundary();
        yComp.setBoundaryMinimum(minY);
        minY.setSpatialId("Ymin");
        minY.setValue(vcOrigin.getY());
        Boundary maxY = new Boundary();
        yComp.setBoundaryMaximum(maxY);
        maxY.setSpatialId("Ymax");
        maxY.setValue(vcOrigin.getY() + (vcExtent.getY()));
        org.sbml.jsbml.Parameter pY = sbmlModel.createParameter();
        pY.setId(vcModel.getY().getName());
        pY.setValue(0.0);
        pY.setConstant(false);
        pY.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPy = (SpatialParameterPlugin) pY.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPy = new SpatialSymbolReference();
        spPluginPy.setParamType(spSymRefPy);
        spSymRefPy.setSpatialRef(yComp.getSpatialId());
    }
    // add z coordinate component
    if (dimension == 3) {
        CoordinateComponent zComp = sbmlGeometry.createCoordinateComponent();
        zComp.setSpatialId(vcModel.getZ().getName());
        zComp.setType(CoordinateKind.cartesianZ);
        zComp.setUnits(sbmlUnitDef_length);
        Boundary minZ = new Boundary();
        zComp.setBoundaryMinimum(minZ);
        minZ.setSpatialId("Zmin");
        minZ.setValue(vcOrigin.getZ());
        Boundary maxZ = new Boundary();
        zComp.setBoundaryMaximum(maxZ);
        maxZ.setSpatialId("Zmax");
        maxZ.setValue(vcOrigin.getZ() + (vcExtent.getZ()));
        org.sbml.jsbml.Parameter pZ = sbmlModel.createParameter();
        pZ.setId(vcModel.getZ().getName());
        pZ.setValue(0.0);
        pZ.setConstant(false);
        pZ.setUnits(sbmlUnitDef_length);
        SpatialParameterPlugin spPluginPz = (SpatialParameterPlugin) pZ.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        SpatialSymbolReference spSymRefPz = new SpatialSymbolReference();
        spPluginPz.setParamType(spSymRefPz);
        spSymRefPz.setSpatialRef(zComp.getSpatialId());
    }
    // 
    // list of compartmentMappings : VC structureMappings
    // 
    GeometryContext vcGeoContext = getSelectedSimContext().getGeometryContext();
    StructureMapping[] vcStrucMappings = vcGeoContext.getStructureMappings();
    for (int i = 0; i < vcStrucMappings.length; i++) {
        StructureMapping vcStructMapping = vcStrucMappings[i];
        String structName = vcStructMapping.getStructure().getName();
        Compartment comp = sbmlModel.getCompartment(TokenMangler.mangleToSName(structName));
        SpatialCompartmentPlugin cplugin = (SpatialCompartmentPlugin) comp.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
        GeometryClass gc = vcStructMapping.getGeometryClass();
        if (!goodPointer(gc, GeometryClass.class, structName)) {
            continue;
        }
        CompartmentMapping compMapping = new CompartmentMapping();
        cplugin.setCompartmentMapping(compMapping);
        String geomClassName = gc.getName();
        String id = TokenMangler.mangleToSName(geomClassName + structName);
        compMapping.setSpatialId(id);
        compMapping.setDomainType(TokenMangler.mangleToSName(DOMAIN_TYPE_PREFIX + geomClassName));
        try {
            StructureMappingParameter usp = vcStructMapping.getUnitSizeParameter();
            Expression e = usp.getExpression();
            if (goodPointer(e, Expression.class, id)) {
                compMapping.setUnitSize(e.evaluateConstant());
            }
        } catch (ExpressionException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to create compartment mapping for structureMapping '" + compMapping.getId() + "' : " + e.getMessage());
        }
    }
    // 
    // list of domain types : subvolumes and surface classes from VC
    // 
    boolean bAnyAnalyticSubvolumes = false;
    boolean bAnyImageSubvolumes = false;
    boolean bAnyCSGSubvolumes = false;
    GeometryClass[] vcGeomClasses = vcGeometry.getGeometryClasses();
    int numSubVols = 0;
    for (int i = 0; i < vcGeomClasses.length; i++) {
        DomainType domainType = sbmlGeometry.createDomainType();
        domainType.setSpatialId(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
        if (vcGeomClasses[i] instanceof SubVolume) {
            if (((SubVolume) vcGeomClasses[i]) instanceof AnalyticSubVolume) {
                bAnyAnalyticSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof ImageSubVolume) {
                bAnyImageSubvolumes = true;
            } else if (((SubVolume) vcGeomClasses[i]) instanceof CSGObject) {
                bAnyCSGSubvolumes = true;
            }
            domainType.setSpatialDimensions(3);
            numSubVols++;
        } else if (vcGeomClasses[i] instanceof SurfaceClass) {
            domainType.setSpatialDimensions(2);
        }
    }
    // 
    // list of domains, adjacent domains : from VC geometricRegions
    // 
    GeometrySurfaceDescription vcGSD = vcGeometry.getGeometrySurfaceDescription();
    if (vcGSD.getRegionImage() == null) {
        try {
            vcGSD.updateAll();
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to generate region images for geometry");
        }
    }
    GeometricRegion[] vcGeometricRegions = vcGSD.getGeometricRegions();
    ISize sampleSize = vcGSD.getVolumeSampleSize();
    int numX = sampleSize.getX();
    int numY = sampleSize.getY();
    int numZ = sampleSize.getZ();
    double ox = vcOrigin.getX();
    double oy = vcOrigin.getY();
    double oz = vcOrigin.getZ();
    RegionInfo[] regionInfos = vcGSD.getRegionImage().getRegionInfos();
    for (int i = 0; i < vcGeometricRegions.length; i++) {
        // domains
        Domain domain = sbmlGeometry.createDomain();
        domain.setSpatialId(vcGeometricRegions[i].getName());
        if (vcGeometricRegions[i] instanceof VolumeGeometricRegion) {
            domain.setDomainType(DOMAIN_TYPE_PREFIX + ((VolumeGeometricRegion) vcGeometricRegions[i]).getSubVolume().getName());
            // 
            // get a list of interior points ... should probably use the distance map to find a point
            // furthest inside (or several points associated with the morphological skeleton).
            // 
            InteriorPoint interiorPt = domain.createInteriorPoint();
            int regionID = ((VolumeGeometricRegion) vcGeometricRegions[i]).getRegionID();
            boolean bFound = false;
            int regInfoIndx = 0;
            for (int j = 0; j < regionInfos.length; j++) {
                regInfoIndx = j;
                if (regionInfos[j].getRegionIndex() == regionID) {
                    int volIndx = 0;
                    for (int z = 0; z < numZ && !bFound; z++) {
                        for (int y = 0; y < numY && !bFound; y++) {
                            for (int x = 0; x < numX && !bFound; x++) {
                                if (regionInfos[j].isIndexInRegion(volIndx)) {
                                    bFound = true;
                                    double unit_z = (numZ > 1) ? ((double) z) / (numZ - 1) : 0.5;
                                    double coordZ = oz + vcExtent.getZ() * unit_z;
                                    double unit_y = (numY > 1) ? ((double) y) / (numY - 1) : 0.5;
                                    double coordY = oy + vcExtent.getY() * unit_y;
                                    double unit_x = (numX > 1) ? ((double) x) / (numX - 1) : 0.5;
                                    double coordX = ox + vcExtent.getX() * unit_x;
                                    interiorPt.setCoord1(coordX);
                                    interiorPt.setCoord2(coordY);
                                    interiorPt.setCoord3(coordZ);
                                }
                                volIndx++;
                            }
                        // end - for x
                        }
                    // end - for y
                    }
                // end - for z
                }
            // end if
            }
            // end for regionInfos
            if (!bFound) {
                throw new RuntimeException("Unable to find interior point for region '" + regionInfos[regInfoIndx].toString());
            }
        } else if (vcGeometricRegions[i] instanceof SurfaceGeometricRegion) {
            SurfaceGeometricRegion vcSurfaceGeomReg = (SurfaceGeometricRegion) vcGeometricRegions[i];
            GeometricRegion geomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion geomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            SurfaceClass surfaceClass = vcGSD.getSurfaceClass(((VolumeGeometricRegion) geomRegion0).getSubVolume(), ((VolumeGeometricRegion) geomRegion1).getSubVolume());
            domain.setDomainType(DOMAIN_TYPE_PREFIX + surfaceClass.getName());
            // adjacent domains : 2 adjacent domain objects for each surfaceClass in VC.
            // adjacent domain 1
            GeometricRegion adjGeomRegion0 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[0];
            GeometricRegion adjGeomRegion1 = vcSurfaceGeomReg.getAdjacentGeometricRegions()[1];
            AdjacentDomains adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion0.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion0.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
            // adj domain 2
            adjDomain = new AdjacentDomains();
            adjDomain.setSpatialId(TokenMangler.mangleToSName(vcSurfaceGeomReg.getName() + "_" + adjGeomRegion1.getName()));
            adjDomain.setDomain1(vcSurfaceGeomReg.getName());
            adjDomain.setDomain2(adjGeomRegion1.getName());
            sbmlGeometry.addAdjacentDomain(adjDomain);
        }
    }
    // 
    if (bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && !bAnyCSGSubvolumes) {
        AnalyticGeometry sbmlAnalyticGeomDefinition = sbmlGeometry.createAnalyticGeometry();
        sbmlAnalyticGeomDefinition.setSpatialId(TokenMangler.mangleToSName("Analytic_" + vcGeometry.getName()));
        sbmlAnalyticGeomDefinition.setIsActive(true);
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof AnalyticSubVolume) {
                AnalyticVolume analyticVol = sbmlAnalyticGeomDefinition.createAnalyticVolume();
                analyticVol.setSpatialId(vcGeomClasses[i].getName());
                analyticVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[i].getName());
                analyticVol.setFunctionType(FunctionKind.layered);
                analyticVol.setOrdinal(numSubVols - (i + 1));
                Expression expr = ((AnalyticSubVolume) vcGeomClasses[i]).getExpression();
                try {
                    String mathMLStr = ExpressionMathMLPrinter.getMathML(expr, true, MathType.BOOLEAN);
                    ASTNode mathMLNode = ASTNode.readMathMLFromString(mathMLStr);
                    analyticVol.setMath(mathMLNode);
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Error converting VC subvolume expression to mathML" + e.getMessage());
                }
            }
        }
    }
    // 
    if (!bAnyAnalyticSubvolumes && !bAnyImageSubvolumes && bAnyCSGSubvolumes) {
        CSGeometry sbmlCSGeomDefinition = new CSGeometry();
        sbmlGeometry.addGeometryDefinition(sbmlCSGeomDefinition);
        sbmlCSGeomDefinition.setSpatialId(TokenMangler.mangleToSName("CSG_" + vcGeometry.getName()));
        for (int i = 0; i < vcGeomClasses.length; i++) {
            if (vcGeomClasses[i] instanceof CSGObject) {
                CSGObject vcellCSGObject = (CSGObject) vcGeomClasses[i];
                org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = new org.sbml.jsbml.ext.spatial.CSGObject();
                sbmlCSGeomDefinition.addCSGObject(sbmlCSGObject);
                sbmlCSGObject.setSpatialId(vcellCSGObject.getName());
                sbmlCSGObject.setDomainType(DOMAIN_TYPE_PREFIX + vcellCSGObject.getName());
                // the ordinal should the the least for the default/background subVolume
                sbmlCSGObject.setOrdinal(numSubVols - (i + 1));
                org.sbml.jsbml.ext.spatial.CSGNode sbmlcsgNode = getSBMLCSGNode(vcellCSGObject.getRoot());
                sbmlCSGObject.setCSGNode(sbmlcsgNode);
            }
        }
    }
    // 
    // add "Segmented" and "DistanceMap" SampledField Geometries
    // 
    final boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
    // 55if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
    if (bVCGeometryIsImage) {
        // 
        // add "Segmented" SampledFieldGeometry
        // 
        SampledFieldGeometry segmentedImageSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
        segmentedImageSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("SegmentedImage_" + vcGeometry.getName()));
        segmentedImageSampledFieldGeometry.setIsActive(true);
        // 55boolean bVCGeometryIsImage = bAnyImageSubvolumes && !bAnyAnalyticSubvolumes && !bAnyCSGSubvolumes;
        Geometry vcImageGeometry = null;
        {
            if (bVCGeometryIsImage) {
                // make a resampled image;
                if (dimension == 3) {
                    try {
                        ISize imageSize = vcGeometry.getGeometrySpec().getDefaultSampledImageSize();
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
                        vcImageGeometry = RayCaster.resampleGeometry(new GeometryThumbnailImageFactoryAWT(), vcGeometry, imageSize);
                    } catch (Throwable e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                } else {
                    try {
                        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, false);
                        GeometrySpec origGeometrySpec = vcGeometry.getGeometrySpec();
                        VCImage newVCImage = origGeometrySpec.getSampledImage().getCurrentValue();
                        // 
                        // construct the new geometry with the sampled VCImage.
                        // 
                        vcImageGeometry = new Geometry(vcGeometry.getName() + "_asImage", newVCImage);
                        vcImageGeometry.getGeometrySpec().setExtent(vcGeometry.getExtent());
                        vcImageGeometry.getGeometrySpec().setOrigin(vcGeometry.getOrigin());
                        vcImageGeometry.setDescription(vcGeometry.getDescription());
                        vcImageGeometry.getGeometrySurfaceDescription().setFilterCutoffFrequency(vcGeometry.getGeometrySurfaceDescription().getFilterCutoffFrequency());
                        vcImageGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
                    } catch (Exception e) {
                        e.printStackTrace(System.out);
                        throw new RuntimeException("Unable to convert the original analytic or constructed solid geometry to image-based geometry : " + e.getMessage());
                    }
                }
                GeometryClass[] vcImageGeomClasses = vcImageGeometry.getGeometryClasses();
                for (int j = 0; j < vcImageGeomClasses.length; j++) {
                    if (vcImageGeomClasses[j] instanceof ImageSubVolume) {
                        SampledVolume sampledVol = segmentedImageSampledFieldGeometry.createSampledVolume();
                        sampledVol.setSpatialId(vcGeomClasses[j].getName());
                        sampledVol.setDomainType(DOMAIN_TYPE_PREFIX + vcGeomClasses[j].getName());
                        sampledVol.setSampledValue(((ImageSubVolume) vcImageGeomClasses[j]).getPixelValue());
                    }
                }
                // add sampledField to sampledFieldGeometry
                SampledField segmentedImageSampledField = sbmlGeometry.createSampledField();
                VCImage vcImage = vcImageGeometry.getGeometrySpec().getImage();
                segmentedImageSampledField.setSpatialId("SegmentedImageSampledField");
                segmentedImageSampledField.setNumSamples1(vcImage.getNumX());
                segmentedImageSampledField.setNumSamples2(vcImage.getNumY());
                segmentedImageSampledField.setNumSamples3(vcImage.getNumZ());
                segmentedImageSampledField.setInterpolationType(InterpolationKind.nearestneighbor);
                segmentedImageSampledField.setCompression(CompressionKind.uncompressed);
                segmentedImageSampledField.setDataType(DataKind.UINT8);
                segmentedImageSampledFieldGeometry.setSampledField(segmentedImageSampledField.getId());
                try {
                    byte[] vcImagePixelsBytes = vcImage.getPixels();
                    // imageData.setCompression("");
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < vcImagePixelsBytes.length; i++) {
                        int uint8_sample = ((int) vcImagePixelsBytes[i]) & 0xff;
                        sb.append(uint8_sample + " ");
                    }
                    segmentedImageSampledField.setSamplesLength(vcImage.getNumXYZ());
                    segmentedImageSampledField.setSamples(sb.toString().trim());
                } catch (ImageException e) {
                    e.printStackTrace(System.out);
                    throw new RuntimeException("Unable to export image from VCell to SBML : " + e.getMessage());
                }
            }
        }
    /*		
		//
		// add "DistanceMap" SampledFieldGeometry if there are exactly two subvolumes (else need more fields) and geometry is 3d.
		//
		if (numSubVols==2 && dimension == 3){
			SignedDistanceMap[] distanceMaps = null;
			try {
				distanceMaps = DistanceMapGenerator.computeDistanceMaps(vcImageGeometry, vcImageGeometry.getGeometrySpec().getImage(), false, false);
			} catch (ImageException e) {
				e.printStackTrace(System.out);
				System.err.println("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				// throw new RuntimeException("Unable to export distance map sampled field from VCell to SBML : " + e.getMessage());
				
				// don't want to throw an exception and stop export because distance map geometry couldn't be exported. 
				// just 'return' from method (since this is the last thing that is being done in this method).
				return;
			}
			//
			// the two distanceMaps should be redundant (one is negation of the other) ... so choose first one for field.
			//
			double[] signedDistances = distanceMaps[0].getSignedDistances();
			SampledFieldGeometry distanceMapSampledFieldGeometry = sbmlGeometry.createSampledFieldGeometry();
			distanceMapSampledFieldGeometry.setSpatialId(TokenMangler.mangleToSName("DistanceMap_"+vcGeometry.getName()));
			SampledField distanceMapSampledField = distanceMapSampledFieldGeometry.createSampledField();
			distanceMapSampledField.setSpatialId("DistanceMapSampledField");
			distanceMapSampledField.setNumSamples1(distanceMaps[0].getSamplesX().length);
			distanceMapSampledField.setNumSamples2(distanceMaps[0].getSamplesY().length);
			distanceMapSampledField.setNumSamples3(distanceMaps[0].getSamplesZ().length);
			distanceMapSampledField.setDataType("real");
System.err.println("do we need distanceMapSampleField.setDataType()?");
			distanceMapSampledField.setInterpolationType("linear");
			ImageData distanceMapImageData = distanceMapSampledField.createImageData();
			distanceMapImageData.setDataType("int16");
System.err.println("should be:\n  distanceMapImageData.setDataType(\"float32\")");
//					distanceMapImageData.setCompression("");

			double maxAbsValue = 0;
			for (int i = 0; i < signedDistances.length; i++) {
				maxAbsValue = Math.max(maxAbsValue,Math.abs(signedDistances[i]));
			}
			if (maxAbsValue==0.0){
				throw new RuntimeException("computed distance map all zeros");
			}
			double scale = (Short.MAX_VALUE-1)/maxAbsValue;
			int[] scaledIntegerDistanceMap = new int[signedDistances.length];
			for (int i = 0; i < signedDistances.length; i++) {
				scaledIntegerDistanceMap[i] = (int)(scale * signedDistances[i]);
			}
			distanceMapImageData.setSamples(scaledIntegerDistanceMap, signedDistances.length);
System.err.println("should be:\n  distanceMapImageData.setSamples((float[])signedDistances,signedDistances.length)");
			SampledVolume sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[0].getInsideSubvolumeName());
			sampledVol.setSampledValue(255);
			sampledVol = distanceMapSampledFieldGeometry.createSampledVolume();
			sampledVol.setSpatialId(distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setDomainType(DOMAIN_TYPE_PREFIX+distanceMaps[1].getInsideSubvolumeName());
			sampledVol.setSampledValue(1);
		}
*/
    }
// 
// add "SurfaceMesh" ParametricGeometry
// 
// if (bAnyAnalyticSubvolumes || bAnyImageSubvolumes || bAnyCSGSubvolumes){
// ParametricGeometry sbmlParametricGeomDefinition = sbmlGeometry.createParametricGeometry();
// sbmlParametricGeomDefinition.setSpatialId(TokenMangler.mangleToSName("SurfaceMesh_"+vcGeometry.getName()));
// xxxx
// }
}
Also used : Origin(org.vcell.util.Origin) CompartmentMapping(org.sbml.jsbml.ext.spatial.CompartmentMapping) Compartment(org.sbml.jsbml.Compartment) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ExpressionException(cbit.vcell.parser.ExpressionException) Boundary(org.sbml.jsbml.ext.spatial.Boundary) GeometrySpec(cbit.vcell.geometry.GeometrySpec) DomainType(org.sbml.jsbml.ext.spatial.DomainType) SampledVolume(org.sbml.jsbml.ext.spatial.SampledVolume) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryContext(cbit.vcell.mapping.GeometryContext) SpatialCompartmentPlugin(org.sbml.jsbml.ext.spatial.SpatialCompartmentPlugin) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) GeometryContext(cbit.vcell.mapping.GeometryContext) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) SpatialSymbolReference(org.sbml.jsbml.ext.spatial.SpatialSymbolReference) AnalyticVolume(org.sbml.jsbml.ext.spatial.AnalyticVolume) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SampledField(org.sbml.jsbml.ext.spatial.SampledField) Domain(org.sbml.jsbml.ext.spatial.Domain) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) GeometryClass(cbit.vcell.geometry.GeometryClass) ImageException(cbit.image.ImageException) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) ISize(org.vcell.util.ISize) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) RegionInfo(cbit.vcell.geometry.RegionImage.RegionInfo) VCImage(cbit.image.VCImage) StructureMapping(cbit.vcell.mapping.StructureMapping) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) ASTNode(org.sbml.jsbml.ASTNode) CSGObject(cbit.vcell.geometry.CSGObject) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) UnitDefinition(org.sbml.jsbml.UnitDefinition) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) SpatialModelPlugin(org.sbml.jsbml.ext.spatial.SpatialModelPlugin) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) ImageException(cbit.image.ImageException) SBMLException(org.sbml.jsbml.SBMLException) ExpressionException(cbit.vcell.parser.ExpressionException) AdjacentDomains(org.sbml.jsbml.ext.spatial.AdjacentDomains) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel)

Aggregations

Model (cbit.vcell.model.Model)107 BioModel (cbit.vcell.biomodel.BioModel)53 SpeciesContext (cbit.vcell.model.SpeciesContext)44 Expression (cbit.vcell.parser.Expression)42 Structure (cbit.vcell.model.Structure)35 PropertyVetoException (java.beans.PropertyVetoException)34 SimulationContext (cbit.vcell.mapping.SimulationContext)27 ReactionStep (cbit.vcell.model.ReactionStep)27 ModelParameter (cbit.vcell.model.Model.ModelParameter)23 ExpressionException (cbit.vcell.parser.ExpressionException)22 ArrayList (java.util.ArrayList)22 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)21 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)19 MathDescription (cbit.vcell.math.MathDescription)17 Feature (cbit.vcell.model.Feature)16 ModelException (cbit.vcell.model.ModelException)16 VCUnitDefinition (cbit.vcell.units.VCUnitDefinition)16 SubVolume (cbit.vcell.geometry.SubVolume)15 Parameter (cbit.vcell.model.Parameter)15 StructureMapping (cbit.vcell.mapping.StructureMapping)14