Search in sources :

Example 1 with BoundaryCondition

use of org.sbml.jsbml.ext.spatial.BoundaryCondition in project vcell by virtualcell.

the class SBMLImporter method addParameters.

/**
 * addParameters : Adds global parameters from SBML model to VCell model. If
 * expression for global parameter contains species, creates a conc_factor
 * parameter (conversion from SBML - VCell conc units) and adds this factor
 * to VC global params list, and replaces occurances of 'sp' with
 * 'sp*concFactor' in original param expression.
 *
 * @throws PropertyVetoException
 */
protected void addParameters() throws Exception {
    ListOf listofGlobalParams = sbmlModel.getListOfParameters();
    if (listofGlobalParams == null) {
        System.out.println("No Global Parameters");
        return;
    }
    Model vcModel = vcBioModel.getSimulationContext(0).getModel();
    ArrayList<ModelParameter> vcModelParamsList = new ArrayList<Model.ModelParameter>();
    // create a hash of reserved symbols so that if there is any reserved
    // symbol occurring as a global parameter in the SBML model,
    // the hash can be used to check for reserved symbols, so that it will
    // not be added as a global parameter in VCell,
    // since reserved symbols cannot be used as other variables (species,
    // structureSize, parameters, reactions, etc.).
    HashSet<String> reservedSymbolHash = new HashSet<String>();
    for (ReservedSymbol rs : vcModel.getReservedSymbols()) {
        reservedSymbolHash.add(rs.getName());
    }
    ModelUnitSystem modelUnitSystem = vcModel.getUnitSystem();
    for (int i = 0; i < sbmlModel.getNumParameters(); i++) {
        Parameter sbmlGlobalParam = (Parameter) listofGlobalParams.get(i);
        String paramName = sbmlGlobalParam.getId();
        SpatialParameterPlugin spplugin = null;
        if (bSpatial) {
            // check if parameter id is x/y/z : if so, check if its
            // 'spatialSymbolRef' child's spatial id and type are non-empty.
            // If so, the parameter represents a spatial element.
            // If not, throw an exception, since a parameter that does not
            // represent a spatial element cannot have an id of x/y/z
            spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            if (paramName.equals("x") || paramName.equals("y") || paramName.equals("z")) {
                boolean bSpatialParam = (spplugin != null && spplugin.getParamType() instanceof SpatialSymbolReference);
                // if (a) and (b) are true, continue with the next parameter
                if (!bSpatialParam) {
                    throw new RuntimeException("Parameter '" + paramName + "' is not a spatial parameter : Cannot have a variable in VCell named '" + paramName + "' unless it is a spatial variable.");
                } else {
                    // parameter to the list of vcell parameters.
                    continue;
                }
            }
        }
        // 
        // Get param value if set or get its expression from rule
        // 
        // Check if param is defined by an assignment rule or initial
        // assignment. If so, that value overrides the value existing in the
        // param element.
        // assignment rule, first
        Expression valueExpr = getValueFromAssignmentRule(paramName);
        if (valueExpr == null) {
            if (sbmlGlobalParam.isSetValue()) {
                double value = sbmlGlobalParam.getValue();
                valueExpr = new Expression(value);
            } else {
                // if value for global param is not set and param has a rate
                // rule, need to set an init value for param (else, there
                // will be a problem in reaction which uses this parameter).
                // use a 'default' initial value of '0'
                valueExpr = new Expression(0.0);
            // logger.sendMessage(VCLogger.Priority.MediumPriority,
            // VCLogger.Priority.LowPriority,
            // "Parameter did not have an initial value, but has a rate rule specified. Using a default value of 0.0.");
            }
        }
        if (valueExpr != null) {
            // valueExpr will be changed
            valueExpr = adjustExpression(valueExpr, vcModel);
        }
        // extension
        if (bSpatial) {
            VCAssert.assertTrue(spplugin != null, "invalid initialization logic");
            ParameterType sbmlParamType = spplugin.getParamType();
            SpeciesContext paramSpContext = null;
            SpeciesContextSpec vcSpContextsSpec = null;
            // Check for diffusion coefficient(s)
            if (sbmlParamType instanceof DiffusionCoefficient) {
                DiffusionCoefficient diffCoeff = (DiffusionCoefficient) sbmlParamType;
                if (diffCoeff != null && diffCoeff.isSetVariable()) {
                    // get the var of diffCoeff; find appropriate spContext
                    // in vcell; set its diff param to param value.
                    paramSpContext = vcModel.getSpeciesContext(diffCoeff.getVariable());
                    if (paramSpContext != null) {
                        vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                        vcSpContextsSpec.getDiffusionParameter().setExpression(valueExpr);
                    }
                    // coeff parameter to the list of vcell parameters.
                    continue;
                }
            }
            // Check for advection coefficient(s)
            if (sbmlParamType instanceof AdvectionCoefficient) {
                AdvectionCoefficient advCoeff = (AdvectionCoefficient) sbmlParamType;
                if (advCoeff != null && advCoeff.isSetVariable()) {
                    // get the var of advCoeff; find appropriate spContext
                    // in vcell; set its adv param to param value.
                    paramSpContext = vcModel.getSpeciesContext(advCoeff.getVariable());
                    if (paramSpContext != null) {
                        vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                        CoordinateKind coordKind = advCoeff.getCoordinate();
                        SpeciesContextSpecParameter param = null;
                        switch(coordKind) {
                            case cartesianX:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityX);
                                    break;
                                }
                            case cartesianY:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityY);
                                    break;
                                }
                            case cartesianZ:
                                {
                                    param = vcSpContextsSpec.getParameterFromRole(SpeciesContextSpec.ROLE_VelocityZ);
                                    break;
                                }
                        }
                        param.setExpression(valueExpr);
                    }
                    // coeff parameter to the list of vcell parameters.
                    continue;
                }
            }
            // Check for Boundary condition(s)
            if (sbmlParamType instanceof BoundaryCondition) {
                BoundaryCondition bCondn = (BoundaryCondition) sbmlParamType;
                if (bCondn != null && bCondn.isSetVariable()) {
                    // get the var of boundaryCondn; find appropriate
                    // spContext in vcell;
                    // set the BC param of its speciesContextSpec to param
                    // value.
                    paramSpContext = vcModel.getSpeciesContext(bCondn.getVariable());
                    if (paramSpContext == null) {
                        throw new RuntimeException("unable to process boundary condition for variable " + bCondn.getVariable());
                    }
                    StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(paramSpContext.getStructure());
                    vcSpContextsSpec = vcBioModel.getSimulationContext(0).getReactionContext().getSpeciesContextSpec(paramSpContext);
                    for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
                        if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
                            switch(coordComp.getType()) {
                                case cartesianX:
                                    {
                                        vcSpContextsSpec.getBoundaryXmParameter().setExpression(valueExpr);
                                    }
                                case cartesianY:
                                    {
                                        vcSpContextsSpec.getBoundaryYmParameter().setExpression(valueExpr);
                                    }
                                case cartesianZ:
                                    {
                                        vcSpContextsSpec.getBoundaryZmParameter().setExpression(valueExpr);
                                    }
                            }
                        }
                        if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
                            switch(coordComp.getType()) {
                                case cartesianX:
                                    {
                                        vcSpContextsSpec.getBoundaryXpParameter().setExpression(valueExpr);
                                    }
                                case cartesianY:
                                    {
                                        vcSpContextsSpec.getBoundaryYpParameter().setExpression(valueExpr);
                                    }
                                case cartesianZ:
                                    {
                                        vcSpContextsSpec.getBoundaryZpParameter().setExpression(valueExpr);
                                    }
                            }
                        }
                    }
                    continue;
                }
            }
            // Check for Boundary condition(s)
            if (sbmlParamType instanceof SpatialSymbolReference) {
                SpatialSymbolReference spatialSymbolRef = (SpatialSymbolReference) sbmlParamType;
                throw new RuntimeException("generic Spatial Symbol References not yet supported, unresolved spatial reference '" + spatialSymbolRef.getSpatialRef() + "'");
            }
        }
        // doesn't exist.
        if (vcModel.getModelParameter(paramName) == null) {
            VCUnitDefinition glParamUnitDefn = sbmlUnitIdentifierHash.get(sbmlGlobalParam.getUnits());
            // set it to TBD or check if it was dimensionless.
            if (glParamUnitDefn == null) {
                glParamUnitDefn = modelUnitSystem.getInstance_TBD();
            }
            // VCell : cannot add reserved symbol to model params.
            if (!reservedSymbolHash.contains(paramName)) {
                ModelParameter vcGlobalParam = vcModel.new ModelParameter(paramName, valueExpr, Model.ROLE_UserDefined, glParamUnitDefn);
                if (paramName.length() > 64) {
                    // record global parameter name in annotation if it is
                    // longer than 64 characeters
                    vcGlobalParam.setDescription("Parameter Name : " + paramName);
                }
                vcModelParamsList.add(vcGlobalParam);
            }
        }
    }
    // end for - sbmlModel.parameters
    vcModel.setModelParameters(vcModelParamsList.toArray(new ModelParameter[0]));
}
Also used : ReservedSymbol(cbit.vcell.model.Model.ReservedSymbol) ArrayList(java.util.ArrayList) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) StructureMapping(cbit.vcell.mapping.StructureMapping) CoordinateKind(org.sbml.jsbml.ext.spatial.CoordinateKind) ListOf(org.sbml.jsbml.ListOf) HashSet(java.util.HashSet) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) AdvectionCoefficient(org.sbml.jsbml.ext.spatial.AdvectionCoefficient) ParameterType(org.sbml.jsbml.ext.spatial.ParameterType) BioEventParameterType(cbit.vcell.mapping.BioEvent.BioEventParameterType) DiffusionCoefficient(org.sbml.jsbml.ext.spatial.DiffusionCoefficient) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) SpatialSymbolReference(org.sbml.jsbml.ext.spatial.SpatialSymbolReference) ModelParameter(cbit.vcell.model.Model.ModelParameter) VCUnitDefinition(cbit.vcell.units.VCUnitDefinition) Expression(cbit.vcell.parser.Expression) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Parameter(org.sbml.jsbml.Parameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter)

Example 2 with BoundaryCondition

use of org.sbml.jsbml.ext.spatial.BoundaryCondition in project vcell by virtualcell.

the class SBMLImporter method addGeometry.

protected void addGeometry() {
    // get a Geometry object via SpatialModelPlugin object.
    org.sbml.jsbml.ext.spatial.Geometry sbmlGeometry = getSbmlGeometry();
    if (sbmlGeometry == null) {
        return;
    }
    int dimension = 0;
    Origin vcOrigin = null;
    Extent vcExtent = null;
    {
        // local code block
        // get a CoordComponent object via the Geometry object.
        ListOf<CoordinateComponent> listOfCoordComps = sbmlGeometry.getListOfCoordinateComponents();
        if (listOfCoordComps == null) {
            throw new RuntimeException("Cannot have 0 coordinate compartments in geometry");
        }
        // coord component
        double ox = 0.0;
        double oy = 0.0;
        double oz = 0.0;
        double ex = 1.0;
        double ey = 1.0;
        double ez = 1.0;
        for (CoordinateComponent coordComponent : listOfCoordComps) {
            double minValue = coordComponent.getBoundaryMinimum().getValue();
            double maxValue = coordComponent.getBoundaryMaximum().getValue();
            switch(coordComponent.getType()) {
                case cartesianX:
                    {
                        ox = minValue;
                        ex = maxValue - minValue;
                        break;
                    }
                case cartesianY:
                    {
                        oy = minValue;
                        ey = maxValue - minValue;
                        break;
                    }
                case cartesianZ:
                    {
                        oz = minValue;
                        ez = maxValue - minValue;
                        break;
                    }
            }
            dimension++;
        }
        vcOrigin = new Origin(ox, oy, oz);
        vcExtent = new Extent(ex, ey, ez);
    }
    // from geometry definition, find out which type of geometry : image or
    // analytic or CSG
    AnalyticGeometry analyticGeometryDefinition = null;
    CSGeometry csGeometry = null;
    SampledFieldGeometry segmentedSampledFieldGeometry = null;
    SampledFieldGeometry distanceMapSampledFieldGeometry = null;
    ParametricGeometry parametricGeometry = null;
    for (int i = 0; i < sbmlGeometry.getListOfGeometryDefinitions().size(); i++) {
        GeometryDefinition gd_temp = sbmlGeometry.getListOfGeometryDefinitions().get(i);
        if (!gd_temp.isSetIsActive()) {
            continue;
        }
        if (gd_temp instanceof AnalyticGeometry) {
            analyticGeometryDefinition = (AnalyticGeometry) gd_temp;
        } else if (gd_temp instanceof SampledFieldGeometry) {
            SampledFieldGeometry sfg = (SampledFieldGeometry) gd_temp;
            String sfn = sfg.getSampledField();
            ListOf<SampledField> sampledFields = sbmlGeometry.getListOfSampledFields();
            if (sampledFields.size() > 1) {
                throw new RuntimeException("only one sampled field supported");
            }
            InterpolationKind ik = sampledFields.get(0).getInterpolationType();
            switch(ik) {
                case linear:
                    distanceMapSampledFieldGeometry = sfg;
                    break;
                case nearestneighbor:
                    segmentedSampledFieldGeometry = sfg;
                    break;
                default:
                    lg.warn("Unsupported " + sampledFields.get(0).getName() + " interpolation type " + ik);
            }
        } else if (gd_temp instanceof CSGeometry) {
            csGeometry = (CSGeometry) gd_temp;
        } else if (gd_temp instanceof ParametricGeometry) {
            parametricGeometry = (ParametricGeometry) gd_temp;
        } else {
            throw new RuntimeException("unsupported geometry definition type " + gd_temp.getClass().getSimpleName());
        }
    }
    if (analyticGeometryDefinition == null && segmentedSampledFieldGeometry == null && distanceMapSampledFieldGeometry == null && csGeometry == null) {
        throw new SBMLImportException("VCell supports only Analytic, Image based (segmentd or distance map) or Constructed Solid Geometry at this time.");
    }
    GeometryDefinition selectedGeometryDefinition = null;
    if (csGeometry != null) {
        selectedGeometryDefinition = csGeometry;
    } else if (analyticGeometryDefinition != null) {
        selectedGeometryDefinition = analyticGeometryDefinition;
    } else if (segmentedSampledFieldGeometry != null) {
        selectedGeometryDefinition = segmentedSampledFieldGeometry;
    } else if (distanceMapSampledFieldGeometry != null) {
        selectedGeometryDefinition = distanceMapSampledFieldGeometry;
    } else if (parametricGeometry != null) {
        selectedGeometryDefinition = parametricGeometry;
    } else {
        throw new SBMLImportException("no geometry definition found");
    }
    Geometry vcGeometry = null;
    if (selectedGeometryDefinition == analyticGeometryDefinition || selectedGeometryDefinition == csGeometry) {
        vcGeometry = new Geometry("spatialGeom", dimension);
    } else if (selectedGeometryDefinition == distanceMapSampledFieldGeometry || selectedGeometryDefinition == segmentedSampledFieldGeometry) {
        SampledFieldGeometry sfg = (SampledFieldGeometry) selectedGeometryDefinition;
        // get image from sampledFieldGeometry
        // get a sampledVol object via the listOfSampledVol (from
        // SampledGeometry) object.
        // gcw gcw gcw
        String sfn = sfg.getSampledField();
        SampledField sf = null;
        for (SampledField sampledField : sbmlGeometry.getListOfSampledFields()) {
            if (sampledField.getSpatialId().equals(sfn)) {
                sf = sampledField;
            }
        }
        int numX = sf.getNumSamples1();
        int numY = sf.getNumSamples2();
        int numZ = sf.getNumSamples3();
        int[] samples = new int[sf.getSamplesLength()];
        StringTokenizer tokens = new StringTokenizer(sf.getSamples(), " ");
        int count = 0;
        while (tokens.hasMoreTokens()) {
            int sample = Integer.parseInt(tokens.nextToken());
            samples[count++] = sample;
        }
        byte[] imageInBytes = new byte[samples.length];
        if (selectedGeometryDefinition == distanceMapSampledFieldGeometry) {
            // 
            for (int i = 0; i < imageInBytes.length; i++) {
                // if (interpolation(samples[i])<0){
                if (samples[i] < 0) {
                    imageInBytes[i] = -1;
                } else {
                    imageInBytes[i] = 1;
                }
            }
        } else {
            for (int i = 0; i < imageInBytes.length; i++) {
                imageInBytes[i] = (byte) samples[i];
            }
        }
        try {
            // System.out.println("ident " + sf.getId() + " " + sf.getName());
            VCImage vcImage = null;
            CompressionKind ck = sf.getCompression();
            DataKind dk = sf.getDataType();
            if (ck == CompressionKind.deflated) {
                vcImage = new VCImageCompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
            } else {
                switch(dk) {
                    case UINT8:
                    case UINT16:
                    case UINT32:
                        vcImage = new VCImageUncompressed(null, imageInBytes, vcExtent, numX, numY, numZ);
                    default:
                }
            }
            if (vcImage == null) {
                throw new SbmlException("Unsupported type combination " + ck + ", " + dk + " for sampled field " + sf.getName());
            }
            vcImage.setName(sf.getId());
            ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
            final int numSampledVols = sampledVolumes.size();
            if (numSampledVols == 0) {
                throw new RuntimeException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
            }
            // check to see if values are uniquely integer , add set up scaling if necessary
            double scaleFactor = checkPixelScaling(sampledVolumes, 1);
            if (scaleFactor != 1) {
                double checkScaleFactor = checkPixelScaling(sampledVolumes, scaleFactor);
                VCAssert.assertTrue(checkScaleFactor != scaleFactor, "Scale factor check failed");
            }
            VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
            // get pixel classes for geometry
            for (int i = 0; i < numSampledVols; i++) {
                SampledVolume sVol = sampledVolumes.get(i);
                // from subVolume, get pixelClass?
                final int scaled = (int) (scaleFactor * sVol.getSampledValue());
                vcpixelClasses[i] = new VCPixelClass(null, sVol.getDomainType(), scaled);
            }
            vcImage.setPixelClasses(vcpixelClasses);
            // now create image geometry
            vcGeometry = new Geometry("spatialGeom", vcImage);
        } catch (Exception e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Unable to create image from SampledFieldGeometry : " + e.getMessage());
        }
    }
    GeometrySpec vcGeometrySpec = vcGeometry.getGeometrySpec();
    vcGeometrySpec.setOrigin(vcOrigin);
    try {
        vcGeometrySpec.setExtent(vcExtent);
    } catch (PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to set extent on VC geometry : " + e.getMessage(), e);
    }
    // get listOfDomainTypes via the Geometry object.
    ListOf<DomainType> listOfDomainTypes = sbmlGeometry.getListOfDomainTypes();
    if (listOfDomainTypes == null || listOfDomainTypes.size() < 1) {
        throw new SBMLImportException("Cannot have 0 domainTypes in geometry");
    }
    // get a listOfDomains via the Geometry object.
    ListOf<Domain> listOfDomains = sbmlGeometry.getListOfDomains();
    if (listOfDomains == null || listOfDomains.size() < 1) {
        throw new SBMLImportException("Cannot have 0 domains in geometry");
    }
    // ListOfGeometryDefinitions listOfGeomDefns =
    // sbmlGeometry.getListOfGeometryDefinitions();
    // if ((listOfGeomDefns == null) ||
    // (sbmlGeometry.getNumGeometryDefinitions() > 1)) {
    // throw new
    // RuntimeException("Can have only 1 geometry definition in geometry");
    // }
    // use the boolean bAnalytic to create the right kind of subvolume.
    // First match the somVol=domainTypes for spDim=3. Deal witl spDim=2
    // afterwards.
    GeometrySurfaceDescription vcGsd = vcGeometry.getGeometrySurfaceDescription();
    Vector<DomainType> surfaceClassDomainTypesVector = new Vector<DomainType>();
    try {
        for (DomainType dt : listOfDomainTypes) {
            if (dt.getSpatialDimensions() == 3) {
                // subvolume
                if (selectedGeometryDefinition == analyticGeometryDefinition) {
                    // will set expression later - when reading in Analytic
                    // Volumes in GeometryDefinition
                    vcGeometrySpec.addSubVolume(new AnalyticSubVolume(dt.getId(), new Expression(1.0)));
                } else {
                // add SubVolumes later for CSG and Image-based
                }
            } else if (dt.getSpatialDimensions() == 2) {
                surfaceClassDomainTypesVector.add(dt);
            }
        }
        // analytic vol is needed to get the expression for subVols
        if (selectedGeometryDefinition == analyticGeometryDefinition) {
            // get an analyticVol object via the listOfAnalyticVol (from
            // AnalyticGeometry) object.
            ListOf<AnalyticVolume> aVolumes = analyticGeometryDefinition.getListOfAnalyticVolumes();
            if (aVolumes.size() < 1) {
                throw new SBMLImportException("Cannot have 0 Analytic volumes in analytic geometry");
            }
            for (AnalyticVolume analyticVol : aVolumes) {
                // get subVol from VC geometry using analyticVol spatialId;
                // set its expr using analyticVol's math.
                SubVolume vcSubvolume = vcGeometrySpec.getSubVolume(analyticVol.getDomainType());
                CastInfo<AnalyticSubVolume> ci = BeanUtils.attemptCast(AnalyticSubVolume.class, vcSubvolume);
                if (!ci.isGood()) {
                    throw new RuntimeException("analytic volume '" + analyticVol.getId() + "' does not map to any VC subvolume.");
                }
                AnalyticSubVolume asv = ci.get();
                try {
                    Expression subVolExpr = getExpressionFromFormula(analyticVol.getMath());
                    asv.setExpression(subVolExpr);
                } catch (ExpressionException e) {
                    e.printStackTrace(System.out);
                    throw new SBMLImportException("Unable to set expression on subVolume '" + asv.getName() + "'. " + e.getMessage(), e);
                }
            }
        }
        SampledFieldGeometry sfg = BeanUtils.downcast(SampledFieldGeometry.class, selectedGeometryDefinition);
        if (sfg != null) {
            ListOf<SampledVolume> sampledVolumes = sfg.getListOfSampledVolumes();
            int numSampledVols = sampledVolumes.size();
            if (numSampledVols == 0) {
                throw new SBMLImportException("Cannot have 0 sampled volumes in sampledField (image_based) geometry");
            }
            VCPixelClass[] vcpixelClasses = new VCPixelClass[numSampledVols];
            ImageSubVolume[] vcImageSubVols = new ImageSubVolume[numSampledVols];
            // get pixel classes for geometry
            int idx = 0;
            for (SampledVolume sVol : sampledVolumes) {
                // from subVolume, get pixelClass?
                final String name = sVol.getDomainType();
                final int pixelValue = SBMLUtils.ignoreZeroFraction(sVol.getSampledValue());
                VCPixelClass pc = new VCPixelClass(null, name, pixelValue);
                vcpixelClasses[idx] = pc;
                // Create the new Image SubVolume - use index of this for
                // loop as 'handle' for ImageSubVol?
                ImageSubVolume isv = new ImageSubVolume(null, pc, idx);
                isv.setName(name);
                vcImageSubVols[idx++] = isv;
            }
            vcGeometry.getGeometrySpec().setSubVolumes(vcImageSubVols);
        }
        if (selectedGeometryDefinition == csGeometry) {
            ListOf<org.sbml.jsbml.ext.spatial.CSGObject> listOfcsgObjs = csGeometry.getListOfCSGObjects();
            ArrayList<org.sbml.jsbml.ext.spatial.CSGObject> sbmlCSGs = new ArrayList<org.sbml.jsbml.ext.spatial.CSGObject>(listOfcsgObjs);
            // we want the CSGObj with highest ordinal to be the first
            // element in the CSG subvols array.
            Collections.sort(sbmlCSGs, new Comparator<org.sbml.jsbml.ext.spatial.CSGObject>() {

                @Override
                public int compare(org.sbml.jsbml.ext.spatial.CSGObject lhs, org.sbml.jsbml.ext.spatial.CSGObject rhs) {
                    // minus one to reverse sort
                    return -1 * Integer.compare(lhs.getOrdinal(), rhs.getOrdinal());
                }
            });
            int n = sbmlCSGs.size();
            CSGObject[] vcCSGSubVolumes = new CSGObject[n];
            for (int i = 0; i < n; i++) {
                org.sbml.jsbml.ext.spatial.CSGObject sbmlCSGObject = sbmlCSGs.get(i);
                CSGObject vcellCSGObject = new CSGObject(null, sbmlCSGObject.getDomainType(), i);
                vcellCSGObject.setRoot(getVCellCSGNode(sbmlCSGObject.getCSGNode()));
            }
            vcGeometry.getGeometrySpec().setSubVolumes(vcCSGSubVolumes);
        }
        // Call geom.geomSurfDesc.updateAll() to automatically generate
        // surface classes.
        // vcGsd.updateAll();
        vcGeometry.precomputeAll(new GeometryThumbnailImageFactoryAWT(), true, true);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to create VC subVolumes from SBML domainTypes : " + e.getMessage(), e);
    }
    // should now map each SBML domain to right VC geometric region.
    GeometricRegion[] vcGeomRegions = vcGsd.getGeometricRegions();
    ISize sampleSize = vcGsd.getVolumeSampleSize();
    RegionInfo[] regionInfos = vcGsd.getRegionImage().getRegionInfos();
    int numX = sampleSize.getX();
    int numY = sampleSize.getY();
    int numZ = sampleSize.getZ();
    double ox = vcOrigin.getX();
    double oy = vcOrigin.getY();
    double oz = vcOrigin.getZ();
    for (Domain domain : listOfDomains) {
        String domainType = domain.getDomainType();
        InteriorPoint interiorPt = domain.getListOfInteriorPoints().get(0);
        if (interiorPt == null) {
            DomainType currDomainType = null;
            for (DomainType dt : sbmlGeometry.getListOfDomainTypes()) {
                if (dt.getSpatialId().equals(domainType)) {
                    currDomainType = dt;
                }
            }
            if (currDomainType.getSpatialDimensions() == 2) {
                continue;
            }
        }
        Coordinate sbmlInteriorPtCoord = new Coordinate(interiorPt.getCoord1(), interiorPt.getCoord2(), interiorPt.getCoord3());
        for (int j = 0; j < vcGeomRegions.length; j++) {
            if (vcGeomRegions[j] instanceof VolumeGeometricRegion) {
                int regionID = ((VolumeGeometricRegion) vcGeomRegions[j]).getRegionID();
                for (int k = 0; k < regionInfos.length; k++) {
                    // (using gemoRegion regionID).
                    if (regionInfos[k].getRegionIndex() == regionID) {
                        int volIndx = 0;
                        Coordinate nearestPtCoord = null;
                        double minDistance = Double.MAX_VALUE;
                        // represented by SBML 'domain[i]'.
                        for (int z = 0; z < numZ; z++) {
                            for (int y = 0; y < numY; y++) {
                                for (int x = 0; x < numX; x++) {
                                    if (regionInfos[k].isIndexInRegion(volIndx)) {
                                        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;
                                        // for now, find the shortest dist
                                        // coord. Can refine algo later.
                                        Coordinate vcCoord = new Coordinate(coordX, coordY, coordZ);
                                        double distance = sbmlInteriorPtCoord.distanceTo(vcCoord);
                                        if (distance < minDistance) {
                                            minDistance = distance;
                                            nearestPtCoord = vcCoord;
                                        }
                                    }
                                    volIndx++;
                                }
                            // end - for x
                            }
                        // end - for y
                        }
                        // with domain name
                        if (nearestPtCoord != null) {
                            GeometryClass geomClassSBML = vcGeometry.getGeometryClass(domainType);
                            // we know vcGeometryReg[j] is a VolGeomRegion
                            GeometryClass geomClassVC = ((VolumeGeometricRegion) vcGeomRegions[j]).getSubVolume();
                            if (geomClassSBML.compareEqual(geomClassVC)) {
                                vcGeomRegions[j].setName(domain.getId());
                            }
                        }
                    }
                // end if (regInfoIndx = regId)
                }
            // end - for regInfo
            }
        }
    // end for - vcGeomRegions
    }
    // deal with surfaceClass:spDim2-domainTypes
    for (int i = 0; i < surfaceClassDomainTypesVector.size(); i++) {
        DomainType surfaceClassDomainType = surfaceClassDomainTypesVector.elementAt(i);
        // 'surfaceClassDomainType'
        for (Domain d : listOfDomains) {
            if (d.getDomainType().equals(surfaceClassDomainType.getId())) {
                // get the adjacent domains of this 'surface' domain
                // (surface domain + its 2 adj vol domains)
                Set<Domain> adjacentDomainsSet = getAssociatedAdjacentDomains(sbmlGeometry, d);
                // get the domain types of the adjacent domains in SBML and
                // store the corresponding subVol counterparts from VC for
                // adj vol domains
                Vector<SubVolume> adjacentSubVolumesVector = new Vector<SubVolume>();
                Vector<VolumeGeometricRegion> adjVolGeomRegionsVector = new Vector<VolumeGeometricRegion>();
                Iterator<Domain> iterator = adjacentDomainsSet.iterator();
                while (iterator.hasNext()) {
                    Domain dom = iterator.next();
                    DomainType dt = getBySpatialID(sbmlGeometry.getListOfDomainTypes(), dom.getDomainType());
                    if (dt.getSpatialDimensions() == 3) {
                        // for domain type with sp. dim = 3, get
                        // correspoinding subVol from VC geometry.
                        GeometryClass gc = vcGeometry.getGeometryClass(dt.getId());
                        adjacentSubVolumesVector.add((SubVolume) gc);
                        // store volGeomRegions corresponding to this (vol)
                        // geomClass in adjVolGeomRegionsVector : this
                        // should return ONLY 1 region for subVol.
                        GeometricRegion[] geomRegion = vcGsd.getGeometricRegions(gc);
                        adjVolGeomRegionsVector.add((VolumeGeometricRegion) geomRegion[0]);
                    }
                }
                // there should be only 2 subVols in this vector
                if (adjacentSubVolumesVector.size() != 2) {
                    throw new RuntimeException("Cannot have more or less than 2 subvolumes that are adjacent to surface (membrane) '" + d.getId() + "'");
                }
                // get the surface class with these 2 adj subVols. Set its
                // name to that of 'surfaceClassDomainType'
                SurfaceClass surfacClass = vcGsd.getSurfaceClass(adjacentSubVolumesVector.get(0), adjacentSubVolumesVector.get(1));
                surfacClass.setName(surfaceClassDomainType.getSpatialId());
                // get surfaceGeometricRegion that has adjVolGeomRegions as
                // its adjacent vol geom regions and set its name from
                // domain 'd'
                SurfaceGeometricRegion surfaceGeomRegion = getAssociatedSurfaceGeometricRegion(vcGsd, adjVolGeomRegionsVector);
                if (surfaceGeomRegion != null) {
                    surfaceGeomRegion.setName(d.getId());
                }
            }
        // end if - domain.domainType == surfaceClassDomainType
        }
    // end for - numDomains
    }
    // structureMappings in VC from compartmentMappings in SBML
    try {
        // set geometry first and then set structureMappings?
        vcBioModel.getSimulationContext(0).setGeometry(vcGeometry);
        // update simContextName ...
        vcBioModel.getSimulationContext(0).setName(vcBioModel.getSimulationContext(0).getName() + "_" + vcGeometry.getName());
        Model vcModel = vcBioModel.getSimulationContext(0).getModel();
        ModelUnitSystem vcModelUnitSystem = vcModel.getUnitSystem();
        Vector<StructureMapping> structMappingsVector = new Vector<StructureMapping>();
        SpatialCompartmentPlugin cplugin = null;
        for (int i = 0; i < sbmlModel.getNumCompartments(); i++) {
            Compartment c = sbmlModel.getCompartment(i);
            String cname = c.getName();
            cplugin = (SpatialCompartmentPlugin) c.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            CompartmentMapping compMapping = cplugin.getCompartmentMapping();
            if (compMapping != null) {
                // final String id = compMapping.getId();
                // final String name = compMapping.getName();
                CastInfo<Structure> ci = SBMLHelper.getTypedStructure(Structure.class, vcModel, cname);
                if (ci.isGood()) {
                    Structure struct = ci.get();
                    String domainType = compMapping.getDomainType();
                    GeometryClass geometryClass = vcGeometry.getGeometryClass(domainType);
                    double unitSize = compMapping.getUnitSize();
                    Feature feat = BeanUtils.downcast(Feature.class, struct);
                    if (feat != null) {
                        FeatureMapping featureMapping = new FeatureMapping(feat, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
                        featureMapping.setGeometryClass(geometryClass);
                        if (geometryClass instanceof SubVolume) {
                            featureMapping.getVolumePerUnitVolumeParameter().setExpression(new Expression(unitSize));
                        } else if (geometryClass instanceof SurfaceClass) {
                            featureMapping.getVolumePerUnitAreaParameter().setExpression(new Expression(unitSize));
                        }
                        structMappingsVector.add(featureMapping);
                    } else if (struct instanceof Membrane) {
                        MembraneMapping membraneMapping = new MembraneMapping((Membrane) struct, vcBioModel.getSimulationContext(0), vcModelUnitSystem);
                        membraneMapping.setGeometryClass(geometryClass);
                        if (geometryClass instanceof SubVolume) {
                            membraneMapping.getAreaPerUnitVolumeParameter().setExpression(new Expression(unitSize));
                        } else if (geometryClass instanceof SurfaceClass) {
                            membraneMapping.getAreaPerUnitAreaParameter().setExpression(new Expression(unitSize));
                        }
                        structMappingsVector.add(membraneMapping);
                    }
                }
            }
        }
        StructureMapping[] structMappings = structMappingsVector.toArray(new StructureMapping[0]);
        vcBioModel.getSimulationContext(0).getGeometryContext().setStructureMappings(structMappings);
        // if type from SBML parameter Boundary Condn is not the same as the
        // boundary type of the
        // structureMapping of structure of paramSpContext, set the boundary
        // condn type of the structureMapping
        // to the value of 'type' from SBML parameter Boundary Condn.
        ListOf<Parameter> listOfGlobalParams = sbmlModel.getListOfParameters();
        for (Parameter sbmlGlobalParam : sbmlModel.getListOfParameters()) {
            SpatialParameterPlugin spplugin = (SpatialParameterPlugin) sbmlGlobalParam.getPlugin(SBMLUtils.SBML_SPATIAL_NS_PREFIX);
            ParameterType paramType = spplugin.getParamType();
            if (!(paramType instanceof BoundaryCondition)) {
                continue;
            }
            BoundaryCondition bCondn = (BoundaryCondition) paramType;
            if (bCondn.isSetVariable()) {
                // get the var of boundaryCondn; find appropriate spContext
                // in vcell;
                SpeciesContext paramSpContext = vcBioModel.getSimulationContext(0).getModel().getSpeciesContext(bCondn.getVariable());
                if (paramSpContext != null) {
                    Structure s = paramSpContext.getStructure();
                    StructureMapping sm = vcBioModel.getSimulationContext(0).getGeometryContext().getStructureMapping(s);
                    if (sm != null) {
                        BoundaryConditionType bct = null;
                        switch(bCondn.getType()) {
                            case Dirichlet:
                                {
                                    bct = BoundaryConditionType.DIRICHLET;
                                    break;
                                }
                            case Neumann:
                                {
                                    bct = BoundaryConditionType.NEUMANN;
                                    break;
                                }
                            case Robin_inwardNormalGradientCoefficient:
                            case Robin_sum:
                            case Robin_valueCoefficient:
                            default:
                                throw new RuntimeException("boundary condition type " + bCondn.getType().name() + " not supported");
                        }
                        for (CoordinateComponent coordComp : getSbmlGeometry().getListOfCoordinateComponents()) {
                            if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMinimum().getSpatialId())) {
                                switch(coordComp.getType()) {
                                    case cartesianX:
                                        {
                                            sm.setBoundaryConditionTypeXm(bct);
                                        }
                                    case cartesianY:
                                        {
                                            sm.setBoundaryConditionTypeYm(bct);
                                        }
                                    case cartesianZ:
                                        {
                                            sm.setBoundaryConditionTypeZm(bct);
                                        }
                                }
                            }
                            if (bCondn.getSpatialRef().equals(coordComp.getBoundaryMaximum().getSpatialId())) {
                                switch(coordComp.getType()) {
                                    case cartesianX:
                                        {
                                            sm.setBoundaryConditionTypeXm(bct);
                                        }
                                    case cartesianY:
                                        {
                                            sm.setBoundaryConditionTypeYm(bct);
                                        }
                                    case cartesianZ:
                                        {
                                            sm.setBoundaryConditionTypeZm(bct);
                                        }
                                }
                            }
                        }
                    } else // sm != null
                    {
                        logger.sendMessage(VCLogger.Priority.MediumPriority, VCLogger.ErrorType.OverallWarning, "No structure " + s.getName() + " requested by species context " + paramSpContext.getName());
                    }
                }
            // end if (paramSpContext != null)
            }
        // end if (bCondn.isSetVar())
        }
        // end for (sbmlModel.numParams)
        vcBioModel.getSimulationContext(0).getGeometryContext().refreshStructureMappings();
        vcBioModel.getSimulationContext(0).refreshSpatialObjects();
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Unable to create VC structureMappings from SBML compartment mappings : " + e.getMessage(), e);
    }
}
Also used : Origin(org.vcell.util.Origin) VCPixelClass(cbit.image.VCPixelClass) MembraneMapping(cbit.vcell.mapping.MembraneMapping) DataKind(org.sbml.jsbml.ext.spatial.DataKind) ArrayList(java.util.ArrayList) BoundaryConditionType(cbit.vcell.math.BoundaryConditionType) SpeciesContext(cbit.vcell.model.SpeciesContext) Feature(cbit.vcell.model.Feature) GeometryDefinition(org.sbml.jsbml.ext.spatial.GeometryDefinition) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) Vector(java.util.Vector) CoordinateComponent(org.sbml.jsbml.ext.spatial.CoordinateComponent) SimulationContext(cbit.vcell.mapping.SimulationContext) SpeciesContext(cbit.vcell.model.SpeciesContext) IssueContext(org.vcell.util.IssueContext) ReactionContext(cbit.vcell.mapping.ReactionContext) CompressionKind(org.sbml.jsbml.ext.spatial.CompressionKind) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) PropertyVetoException(java.beans.PropertyVetoException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) Coordinate(org.vcell.util.Coordinate) BoundaryCondition(org.sbml.jsbml.ext.spatial.BoundaryCondition) SbmlException(org.vcell.sbml.SbmlException) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SurfaceClass(cbit.vcell.geometry.SurfaceClass) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) VCImage(cbit.image.VCImage) StructureMapping(cbit.vcell.mapping.StructureMapping) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) FeatureMapping(cbit.vcell.mapping.FeatureMapping) Structure(cbit.vcell.model.Structure) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem) ParameterType(org.sbml.jsbml.ext.spatial.ParameterType) BioEventParameterType(cbit.vcell.mapping.BioEvent.BioEventParameterType) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) Geometry(cbit.vcell.geometry.Geometry) SampledFieldGeometry(org.sbml.jsbml.ext.spatial.SampledFieldGeometry) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ParametricGeometry(org.sbml.jsbml.ext.spatial.ParametricGeometry) CSGeometry(org.sbml.jsbml.ext.spatial.CSGeometry) StringTokenizer(java.util.StringTokenizer) Expression(cbit.vcell.parser.Expression) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) InterpolationKind(org.sbml.jsbml.ext.spatial.InterpolationKind) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) Parameter(org.sbml.jsbml.Parameter) ModelParameter(cbit.vcell.model.Model.ModelParameter) SpeciesContextSpecParameter(cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter) LocalParameter(org.sbml.jsbml.LocalParameter) KineticsProxyParameter(cbit.vcell.model.Kinetics.KineticsProxyParameter) UnresolvedParameter(cbit.vcell.model.Kinetics.UnresolvedParameter) CompartmentMapping(org.sbml.jsbml.ext.spatial.CompartmentMapping) Compartment(org.sbml.jsbml.Compartment) SpatialParameterPlugin(org.sbml.jsbml.ext.spatial.SpatialParameterPlugin) AnalyticGeometry(org.sbml.jsbml.ext.spatial.AnalyticGeometry) ExpressionException(cbit.vcell.parser.ExpressionException) GeometrySpec(cbit.vcell.geometry.GeometrySpec) DomainType(org.sbml.jsbml.ext.spatial.DomainType) SampledVolume(org.sbml.jsbml.ext.spatial.SampledVolume) ListOf(org.sbml.jsbml.ListOf) SpatialCompartmentPlugin(org.sbml.jsbml.ext.spatial.SpatialCompartmentPlugin) VCImageCompressed(cbit.image.VCImageCompressed) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) AnalyticVolume(org.sbml.jsbml.ext.spatial.AnalyticVolume) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) ParametricGeometry(org.sbml.jsbml.ext.spatial.ParametricGeometry) SampledField(org.sbml.jsbml.ext.spatial.SampledField) Domain(org.sbml.jsbml.ext.spatial.Domain) GeometryClass(cbit.vcell.geometry.GeometryClass) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) RegionInfo(cbit.vcell.geometry.RegionImage.RegionInfo) Membrane(cbit.vcell.model.Membrane) CSGObject(cbit.vcell.geometry.CSGObject) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VCImageUncompressed(cbit.image.VCImageUncompressed) InteriorPoint(org.sbml.jsbml.ext.spatial.InteriorPoint) XMLStreamException(javax.xml.stream.XMLStreamException) SbmlException(org.vcell.sbml.SbmlException) IOException(java.io.IOException) PropertyVetoException(java.beans.PropertyVetoException) SBMLException(org.sbml.jsbml.SBMLException) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 3 with BoundaryCondition

use of org.sbml.jsbml.ext.spatial.BoundaryCondition 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)

Aggregations

BioModel (cbit.vcell.biomodel.BioModel)3 SpeciesContextSpecParameter (cbit.vcell.mapping.SpeciesContextSpec.SpeciesContextSpecParameter)3 StructureMapping (cbit.vcell.mapping.StructureMapping)3 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)3 Model (cbit.vcell.model.Model)3 ModelParameter (cbit.vcell.model.Model.ModelParameter)3 SpeciesContext (cbit.vcell.model.SpeciesContext)3 Expression (cbit.vcell.parser.Expression)3 BoundaryCondition (org.sbml.jsbml.ext.spatial.BoundaryCondition)3 CoordinateComponent (org.sbml.jsbml.ext.spatial.CoordinateComponent)3 InteriorPoint (org.sbml.jsbml.ext.spatial.InteriorPoint)3 SpatialParameterPlugin (org.sbml.jsbml.ext.spatial.SpatialParameterPlugin)3 BioEventParameterType (cbit.vcell.mapping.BioEvent.BioEventParameterType)2 KineticsProxyParameter (cbit.vcell.model.Kinetics.KineticsProxyParameter)2 UnresolvedParameter (cbit.vcell.model.Kinetics.UnresolvedParameter)2 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)2 ArrayList (java.util.ArrayList)2 ListOf (org.sbml.jsbml.ListOf)2 LocalParameter (org.sbml.jsbml.LocalParameter)2 Parameter (org.sbml.jsbml.Parameter)2