Search in sources :

Example 26 with Species

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

the class XmlReader method getSpeciesContext.

/**
 * This method returns a Speciecontext object from a XML Element.
 * Creation date: (4/16/2001 6:32:23 PM)
 * @return cbit.vcell.model.SpeciesContext
 * @param param org.jdom.Element
 */
private SpeciesContext getSpeciesContext(Element param, Model model) throws XmlParseException {
    // retrieve its information
    String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
    String hasOverrideString = param.getAttributeValue(XMLTags.HasOverrideAttrTag);
    String speciesName = unMangle(param.getAttributeValue(XMLTags.SpeciesRefAttrTag));
    Species specieref = (Species) model.getSpecies(speciesName);
    if (specieref == null) {
        throw new XmlParseException("The Species " + speciesName + "could not be resolved!");
    }
    String structureName = unMangle(param.getAttributeValue(XMLTags.StructureAttrTag));
    Structure structureref = (Structure) model.getStructure(structureName);
    if (structureref == null) {
        // the structure coul not be retrieved, so throw an exception!
        throw new XmlParseException("The Structure " + structureName + "could not be resolved!");
    }
    // Try to read KeyValue data
    String keystring = param.getAttributeValue(XMLTags.KeyValueAttrTag);
    KeyValue key = null;
    if (keystring != null && keystring.length() > 0 && this.readKeysFlag) {
        key = new KeyValue(keystring);
    }
    SpeciesPattern sp = null;
    Element element = param.getChild(XMLTags.RbmSpeciesPatternTag, vcNamespace);
    if (element != null) {
        sp = getSpeciesPattern(element, model);
        sp.resolveBonds();
        if (sp == null) {
            throw new XmlParseException("XMLReader: getSpeciesContext: SpeciesPattern is missing.");
        }
    }
    // ---try to create the speciesContext---
    SpeciesContext speciecontext = null;
    speciecontext = new SpeciesContext(key, name, specieref, structureref, sp);
    return speciecontext;
}
Also used : KeyValue(org.vcell.util.document.KeyValue) Element(org.jdom.Element) SpeciesContext(cbit.vcell.model.SpeciesContext) Structure(cbit.vcell.model.Structure) DBFormalSpecies(cbit.vcell.model.DBFormalSpecies) Species(cbit.vcell.model.Species) DBSpecies(cbit.vcell.model.DBSpecies) ParticleSpeciesPattern(cbit.vcell.math.ParticleSpeciesPattern) VolumeParticleSpeciesPattern(cbit.vcell.math.VolumeParticleSpeciesPattern) SpeciesPattern(org.vcell.model.rbm.SpeciesPattern)

Example 27 with Species

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

the class Xmlproducer method getXML.

/**
 * Outputs a XML version of a Model object
 * Creation date: (2/15/2001 11:39:27 AM)
 * @return Element
 * @param param cbit.vcell.model.Model
 */
private Element getXML(Model param) throws XmlParseException /*, cbit.vcell.parser.ExpressionException */
{
    Element modelnode = new Element(XMLTags.ModelTag);
    String versionName = (param.getName() != null) ? mangle(param.getName()) : "unnamed_model";
    // get Attributes
    modelnode.setAttribute(XMLTags.NameAttrTag, versionName);
    // modelnode.setAttribute(XMLTags.AnnotationAttrTag, this.mangle(param.getDescription()));
    if (param.getDescription() != null && param.getDescription().length() > 0) {
        Element annotationElem = new Element(XMLTags.AnnotationTag);
        annotationElem.setText(mangle(param.getDescription()));
        modelnode.addContent(annotationElem);
    }
    // get global parameters
    ModelParameter[] modelGlobals = param.getModelParameters();
    if (modelGlobals != null && modelGlobals.length > 0) {
        modelnode.addContent(getXML(modelGlobals));
    }
    // Get Species
    Species[] array = param.getSpecies();
    for (int i = 0; i < array.length; i++) {
        modelnode.addContent(getXML(array[i]));
    }
    // Get Structures(Features and Membranes). Add them in an ordered fashion, but it does not matter who comes first.
    try {
        ArrayList<Element> list = new ArrayList<Element>();
        Structure[] structarray = param.getStructures();
        for (int i = 0; i < structarray.length; i++) {
            Element structure = getXML(structarray[i], param);
            if (structarray[i] instanceof Feature)
                modelnode.addContent(structure);
            else
                list.add(structure);
        }
        for (int i = 0; i < list.size(); i++) {
            modelnode.addContent((Element) list.get(i));
        }
    } catch (XmlParseException e) {
        e.printStackTrace();
        throw new XmlParseException("An error occurred while procesing a Structure for the model " + versionName, e);
    }
    // Process SpeciesContexts
    SpeciesContext[] specarray = param.getSpeciesContexts();
    for (int i = 0; i < specarray.length; i++) {
        modelnode.addContent(getXML(specarray[i]));
    }
    // Get reaction Steps(Simple Reactions and Fluxtep)
    ReactionStep[] reactarray = param.getReactionSteps();
    for (int i = 0; i < reactarray.length; i++) {
        modelnode.addContent(getXML(reactarray[i]));
    }
    // add the rbmModelContainer elements
    RbmModelContainer rbmModelContainer = param.getRbmModelContainer();
    if (rbmModelContainer != null && !rbmModelContainer.isEmpty()) {
        Element rbmModelContainerElement = getXML(rbmModelContainer);
        {
            // for testing purposes only
            Document doc = new Document();
            Element clone = (Element) rbmModelContainerElement.clone();
            doc.setRootElement(clone);
            String xmlString = XmlUtil.xmlToString(doc, false);
            System.out.println(xmlString);
        }
        modelnode.addContent(rbmModelContainerElement);
    }
    // // Add rate rules
    // if (param.getRateRuleVariables()!=null && param.getRateRuleVariables().length>0){
    // modelnode.addContent( getXML(param.getRateRuleVariables()) );
    // }
    // Get Diagrams
    Diagram[] diagarray = param.getDiagrams();
    for (int i = 0; i < diagarray.length; i++) {
        modelnode.addContent(getXML(diagarray[i]));
    }
    // Add Metadata information
    if (param.getVersion() != null) {
        modelnode.addContent(getXML(param.getVersion(), param));
    }
    // add model UnitSystem
    ModelUnitSystem unitSystem = param.getUnitSystem();
    if (unitSystem != null) {
        modelnode.addContent(getXML(unitSystem));
    }
    return modelnode;
}
Also used : Element(org.jdom.Element) ArrayList(java.util.ArrayList) SpeciesContext(cbit.vcell.model.SpeciesContext) Document(org.jdom.Document) Feature(cbit.vcell.model.Feature) Diagram(cbit.vcell.model.Diagram) ModelParameter(cbit.vcell.model.Model.ModelParameter) RbmModelContainer(cbit.vcell.model.Model.RbmModelContainer) ReactionStep(cbit.vcell.model.ReactionStep) Structure(cbit.vcell.model.Structure) DBFormalSpecies(cbit.vcell.model.DBFormalSpecies) Species(cbit.vcell.model.Species) DBSpecies(cbit.vcell.model.DBSpecies) ModelUnitSystem(cbit.vcell.model.ModelUnitSystem)

Example 28 with Species

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

the class FRAPStudy method createNewSimBioModel.

public static BioModel createNewSimBioModel(FRAPStudy sourceFrapStudy, Parameter[] params, TimeStep tStep, KeyValue simKey, User owner, int startingIndexForRecovery) throws Exception {
    if (owner == null) {
        throw new Exception("Owner is not defined");
    }
    ROI cellROI_2D = sourceFrapStudy.getFrapData().getRoi(FRAPData.VFRAP_ROI_ENUM.ROI_CELL.name());
    double df = params[FRAPModel.INDEX_PRIMARY_DIFF_RATE].getInitialGuess();
    double ff = params[FRAPModel.INDEX_PRIMARY_FRACTION].getInitialGuess();
    double bwmRate = params[FRAPModel.INDEX_BLEACH_MONITOR_RATE].getInitialGuess();
    double dc = 0;
    double fc = 0;
    double bs = 0;
    double onRate = 0;
    double offRate = 0;
    if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_TWO_DIFF) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
    } else if (params.length == FRAPModel.NUM_MODEL_PARAMETERS_BINDING) {
        dc = params[FRAPModel.INDEX_SECONDARY_DIFF_RATE].getInitialGuess();
        fc = params[FRAPModel.INDEX_SECONDARY_FRACTION].getInitialGuess();
        bs = params[FRAPModel.INDEX_BINDING_SITE_CONCENTRATION].getInitialGuess();
        onRate = params[FRAPModel.INDEX_ON_RATE].getInitialGuess();
        offRate = params[FRAPModel.INDEX_OFF_RATE].getInitialGuess();
    }
    // immobile fraction
    double fimm = 1 - ff - fc;
    if (fimm < FRAPOptimizationUtils.epsilon && fimm > (0 - FRAPOptimizationUtils.epsilon)) {
        fimm = 0;
    }
    if (fimm < (1 + FRAPOptimizationUtils.epsilon) && fimm > (1 - FRAPOptimizationUtils.epsilon)) {
        fimm = 1;
    }
    Extent extent = sourceFrapStudy.getFrapData().getImageDataset().getExtent();
    double[] timeStamps = sourceFrapStudy.getFrapData().getImageDataset().getImageTimeStamps();
    TimeBounds timeBounds = new TimeBounds(0.0, timeStamps[timeStamps.length - 1] - timeStamps[startingIndexForRecovery]);
    double timeStepVal = timeStamps[startingIndexForRecovery + 1] - timeStamps[startingIndexForRecovery];
    int numX = cellROI_2D.getRoiImages()[0].getNumX();
    int numY = cellROI_2D.getRoiImages()[0].getNumY();
    int numZ = cellROI_2D.getRoiImages().length;
    short[] shortPixels = cellROI_2D.getRoiImages()[0].getPixels();
    byte[] bytePixels = new byte[numX * numY * numZ];
    final byte EXTRACELLULAR_PIXVAL = 0;
    final byte CYTOSOL_PIXVAL = 1;
    for (int i = 0; i < bytePixels.length; i++) {
        if (shortPixels[i] != 0) {
            bytePixels[i] = CYTOSOL_PIXVAL;
        }
    }
    VCImage maskImage;
    try {
        maskImage = new VCImageUncompressed(null, bytePixels, extent, numX, numY, numZ);
    } catch (ImageException e) {
        e.printStackTrace();
        throw new RuntimeException("failed to create mask image for geometry");
    }
    Geometry geometry = new Geometry("geometry", maskImage);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    int subVolume0PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(0).setName((subVolume0PixVal == EXTRACELLULAR_PIXVAL ? EXTRACELLULAR_NAME : CYTOSOL_NAME));
    int subVolume1PixVal = ((ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1)).getPixelValue();
    geometry.getGeometrySpec().getSubVolume(1).setName((subVolume1PixVal == CYTOSOL_PIXVAL ? CYTOSOL_NAME : EXTRACELLULAR_NAME));
    geometry.getGeometrySurfaceDescription().updateAll();
    BioModel bioModel = new BioModel(null);
    bioModel.setName("unnamed");
    Model model = new Model("model");
    bioModel.setModel(model);
    model.addFeature(EXTRACELLULAR_NAME);
    Feature extracellular = (Feature) model.getStructure(EXTRACELLULAR_NAME);
    model.addFeature(CYTOSOL_NAME);
    Feature cytosol = (Feature) model.getStructure(CYTOSOL_NAME);
    // Membrane mem = model.addMembrane(EXTRACELLULAR_CYTOSOL_MEM_NAME);
    // model.getStructureTopology().setInsideFeature(mem, cytosol);
    // model.getStructureTopology().setOutsideFeature(mem, extracellular);
    String roiDataName = FRAPStudy.ROI_EXTDATA_NAME;
    final int SPECIES_COUNT = 4;
    final int FREE_SPECIES_INDEX = 0;
    final int BS_SPECIES_INDEX = 1;
    final int COMPLEX_SPECIES_INDEX = 2;
    final int IMMOBILE_SPECIES_INDEX = 3;
    Expression[] diffusionConstants = null;
    Species[] species = null;
    SpeciesContext[] speciesContexts = null;
    Expression[] initialConditions = null;
    diffusionConstants = new Expression[SPECIES_COUNT];
    species = new Species[SPECIES_COUNT];
    speciesContexts = new SpeciesContext[SPECIES_COUNT];
    initialConditions = new Expression[SPECIES_COUNT];
    // total initial condition
    FieldFunctionArguments postBleach_first = new FieldFunctionArguments(roiDataName, "postbleach_first", new Expression(0), VariableType.VOLUME);
    FieldFunctionArguments prebleach_avg = new FieldFunctionArguments(roiDataName, "prebleach_avg", new Expression(0), VariableType.VOLUME);
    Expression expPostBleach_first = new Expression(postBleach_first.infix());
    Expression expPreBleach_avg = new Expression(prebleach_avg.infix());
    Expression totalIniCondition = Expression.div(expPostBleach_first, expPreBleach_avg);
    // Free Species
    diffusionConstants[FREE_SPECIES_INDEX] = new Expression(df);
    species[FREE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_MOBILE, "Mobile bleachable species");
    speciesContexts[FREE_SPECIES_INDEX] = new SpeciesContext(null, species[FREE_SPECIES_INDEX].getCommonName(), species[FREE_SPECIES_INDEX], cytosol);
    initialConditions[FREE_SPECIES_INDEX] = Expression.mult(new Expression(ff), totalIniCondition);
    // Immobile Species (No diffusion)
    // Set very small diffusion rate on immobile to force evaluation as state variable (instead of FieldData function)
    // If left as a function errors occur because functions involving FieldData require a database connection
    final String IMMOBILE_DIFFUSION_KLUDGE = "1e-14";
    diffusionConstants[IMMOBILE_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[IMMOBILE_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_IMMOBILE, "Immobile bleachable species");
    speciesContexts[IMMOBILE_SPECIES_INDEX] = new SpeciesContext(null, species[IMMOBILE_SPECIES_INDEX].getCommonName(), species[IMMOBILE_SPECIES_INDEX], cytosol);
    initialConditions[IMMOBILE_SPECIES_INDEX] = Expression.mult(new Expression(fimm), totalIniCondition);
    // BS Species
    diffusionConstants[BS_SPECIES_INDEX] = new Expression(IMMOBILE_DIFFUSION_KLUDGE);
    species[BS_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE, "Binding Site species");
    speciesContexts[BS_SPECIES_INDEX] = new SpeciesContext(null, species[BS_SPECIES_INDEX].getCommonName(), species[BS_SPECIES_INDEX], cytosol);
    initialConditions[BS_SPECIES_INDEX] = Expression.mult(new Expression(bs), totalIniCondition);
    // Complex species
    diffusionConstants[COMPLEX_SPECIES_INDEX] = new Expression(dc);
    species[COMPLEX_SPECIES_INDEX] = new Species(FRAPStudy.SPECIES_NAME_PREFIX_SLOW_MOBILE, "Slower mobile bleachable species");
    speciesContexts[COMPLEX_SPECIES_INDEX] = new SpeciesContext(null, species[COMPLEX_SPECIES_INDEX].getCommonName(), species[COMPLEX_SPECIES_INDEX], cytosol);
    initialConditions[COMPLEX_SPECIES_INDEX] = Expression.mult(new Expression(fc), totalIniCondition);
    // add reactions to species if there is bleachWhileMonitoring rate.
    for (int i = 0; i < initialConditions.length; i++) {
        model.addSpecies(species[i]);
        model.addSpeciesContext(speciesContexts[i]);
        // reaction with BMW rate, which should not be applied to binding site
        if (!(species[i].getCommonName().equals(FRAPStudy.SPECIES_NAME_PREFIX_BINDING_SITE))) {
            SimpleReaction simpleReaction = new SimpleReaction(model, cytosol, speciesContexts[i].getName() + "_bleach", true);
            model.addReactionStep(simpleReaction);
            simpleReaction.addReactant(speciesContexts[i], 1);
            MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction);
            simpleReaction.setKinetics(massActionKinetics);
            KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
            simpleReaction.getKinetics().setParameterValue(kforward, new Expression(new Double(bwmRate)));
        }
    }
    // add the binding reaction: F + BS <-> C
    SimpleReaction simpleReaction2 = new SimpleReaction(model, cytosol, "reac_binding", true);
    model.addReactionStep(simpleReaction2);
    simpleReaction2.addReactant(speciesContexts[FREE_SPECIES_INDEX], 1);
    simpleReaction2.addReactant(speciesContexts[BS_SPECIES_INDEX], 1);
    simpleReaction2.addProduct(speciesContexts[COMPLEX_SPECIES_INDEX], 1);
    MassActionKinetics massActionKinetics = new MassActionKinetics(simpleReaction2);
    simpleReaction2.setKinetics(massActionKinetics);
    KineticsParameter kforward = massActionKinetics.getForwardRateParameter();
    KineticsParameter kreverse = massActionKinetics.getReverseRateParameter();
    simpleReaction2.getKinetics().setParameterValue(kforward, new Expression(new Double(onRate)));
    simpleReaction2.getKinetics().setParameterValue(kreverse, new Expression(new Double(offRate)));
    // create simulation context
    SimulationContext simContext = new SimulationContext(bioModel.getModel(), geometry);
    bioModel.addSimulationContext(simContext);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(extracellular);
    // Membrane plasmaMembrane = model.getStructureTopology().getMembrane(cytosol, extracellular);
    // MembraneMapping plasmaMembraneMapping = (MembraneMapping)simContext.getGeometryContext().getStructureMapping(plasmaMembrane);
    SubVolume cytSubVolume = geometry.getGeometrySpec().getSubVolume(CYTOSOL_NAME);
    SubVolume exSubVolume = geometry.getGeometrySpec().getSubVolume(EXTRACELLULAR_NAME);
    SurfaceClass pmSurfaceClass = geometry.getGeometrySurfaceDescription().getSurfaceClass(exSubVolume, cytSubVolume);
    cytosolFeatureMapping.setGeometryClass(cytSubVolume);
    extracellularFeatureMapping.setGeometryClass(exSubVolume);
    // plasmaMembraneMapping.setGeometryClass(pmSurfaceClass);
    cytosolFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    extracellularFeatureMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    for (int i = 0; i < speciesContexts.length; i++) {
        SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(speciesContexts[i]);
        scs.getInitialConditionParameter().setExpression(initialConditions[i]);
        scs.getDiffusionParameter().setExpression(diffusionConstants[i]);
    }
    MathMapping mathMapping = simContext.createNewMathMapping();
    MathDescription mathDesc = mathMapping.getMathDescription();
    // Add total fluorescence as function of mobile(optional: and slower mobile) and immobile fractions
    mathDesc.addVariable(new Function(FRAPStudy.SPECIES_NAME_PREFIX_COMBINED, new Expression(species[FREE_SPECIES_INDEX].getCommonName() + "+" + species[COMPLEX_SPECIES_INDEX].getCommonName() + "+" + species[IMMOBILE_SPECIES_INDEX].getCommonName()), null));
    simContext.setMathDescription(mathDesc);
    SimulationVersion simVersion = new SimulationVersion(simKey, "sim1", owner, new GroupAccessNone(), new KeyValue("0"), new BigDecimal(0), new Date(), VersionFlag.Current, "", null);
    Simulation newSimulation = new Simulation(simVersion, mathDesc);
    simContext.addSimulation(newSimulation);
    newSimulation.getSolverTaskDescription().setTimeBounds(timeBounds);
    newSimulation.getMeshSpecification().setSamplingSize(cellROI_2D.getISize());
    // newSimulation.getSolverTaskDescription().setTimeStep(timeStep); // Sundials doesn't need time step
    newSimulation.getSolverTaskDescription().setSolverDescription(SolverDescription.SundialsPDE);
    // use exp time step as output time spec
    newSimulation.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec(timeStepVal));
    return bioModel;
}
Also used : ImageException(cbit.image.ImageException) KeyValue(org.vcell.util.document.KeyValue) Extent(org.vcell.util.Extent) SurfaceClass(cbit.vcell.geometry.SurfaceClass) MathDescription(cbit.vcell.math.MathDescription) VCImage(cbit.image.VCImage) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) TimeBounds(cbit.vcell.solver.TimeBounds) Function(cbit.vcell.math.Function) GroupAccessNone(org.vcell.util.document.GroupAccessNone) SimulationVersion(org.vcell.util.document.SimulationVersion) KineticsParameter(cbit.vcell.model.Kinetics.KineticsParameter) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Species(cbit.vcell.model.Species) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) SimpleReaction(cbit.vcell.model.SimpleReaction) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) FieldFunctionArguments(cbit.vcell.field.FieldFunctionArguments) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ROI(cbit.vcell.VirtualMicroscopy.ROI) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException) BigDecimal(java.math.BigDecimal) Date(java.util.Date) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) MathMapping(cbit.vcell.mapping.MathMapping) MassActionKinetics(cbit.vcell.model.MassActionKinetics)

Example 29 with Species

use of cbit.vcell.model.Species 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 30 with Species

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

the class SBMLImporter method addSpecies.

protected void addSpecies(VCMetaData metaData) {
    if (sbmlModel == null) {
        throw new SBMLImportException("SBML model is NULL");
    }
    ListOf listOfSpecies = sbmlModel.getListOfSpecies();
    if (listOfSpecies == null) {
        System.out.println("No Spcecies");
        return;
    }
    HashMap<String, Species> vcSpeciesHash = new HashMap<String, Species>();
    HashMap<Species, org.sbml.jsbml.Species> vc_sbmlSpeciesHash = new HashMap<Species, org.sbml.jsbml.Species>();
    SpeciesContext[] vcSpeciesContexts = new SpeciesContext[(int) sbmlModel.getNumSpecies()];
    // Get species from SBMLmodel; Add/get speciesContext
    try {
        // First pass - add the speciesContexts
        for (int i = 0; i < sbmlModel.getNumSpecies(); i++) {
            org.sbml.jsbml.Species sbmlSpecies = (org.sbml.jsbml.Species) listOfSpecies.get(i);
            // Sometimes, the species name can be null or a blank string; in
            // that case, use species id as the name.
            String speciesName = sbmlSpecies.getId();
            Species vcSpecies = null;
            // create a species with speciesName as commonName. If it is
            // different in the annotation, can change it later
            Element sbmlImportRelatedElement = sbmlAnnotationUtil.readVCellSpecificAnnotation(sbmlSpecies);
            if (sbmlImportRelatedElement != null) {
                Element embeddedElement = getEmbeddedElementInAnnotation(sbmlImportRelatedElement, SPECIES_NAME);
                if (embeddedElement != null) {
                    // species.
                    if (embeddedElement.getName().equals(XMLTags.SpeciesTag)) {
                        String vcSpeciesName = embeddedElement.getAttributeValue(XMLTags.NameAttrTag);
                        vcSpecies = vcSpeciesHash.get(vcSpeciesName);
                        if (vcSpecies == null) {
                            vcSpecies = new Species(vcSpeciesName, vcSpeciesName);
                            vcSpeciesHash.put(vcSpeciesName, vcSpecies);
                        }
                    }
                // if embedded element is not speciesTag, do I have to
                // do something?
                } else {
                    // Annotation element is present, but doesn't contain
                    // the species element.
                    vcSpecies = new Species(speciesName, speciesName);
                    vcSpeciesHash.put(speciesName, vcSpecies);
                }
            } else {
                vcSpecies = new Species(speciesName, speciesName);
                vcSpeciesHash.put(speciesName, vcSpecies);
            }
            // store vc & sbml species in hash to read in annotation later
            vc_sbmlSpeciesHash.put(vcSpecies, sbmlSpecies);
            // Get matching compartment name (of sbmlSpecies[i]) from
            // feature list
            String compartmentId = sbmlSpecies.getCompartment();
            Structure spStructure = vcBioModel.getSimulationContext(0).getModel().getStructure(compartmentId);
            vcSpeciesContexts[i] = new SpeciesContext(vcSpecies, spStructure);
            vcSpeciesContexts[i].setName(speciesName);
            // Adjust units of species, convert to VC units.
            // Units in SBML, compute this using some of the attributes of
            // sbmlSpecies
            Compartment sbmlCompartment = sbmlModel.getCompartment(sbmlSpecies.getCompartment());
            int dimension = 3;
            if (sbmlCompartment.isSetSpatialDimensions()) {
                dimension = (int) sbmlCompartment.getSpatialDimensions();
            }
            if (dimension == 0 || dimension == 1) {
                logger.sendMessage(VCLogger.Priority.HighPriority, VCLogger.ErrorType.UnitError, dimension + " dimensional compartment " + compartmentId + " not supported");
            }
        }
        // end - for sbmlSpecies
        // set the species & speciesContexts on model
        Model vcModel = vcBioModel.getSimulationContext(0).getModel();
        vcModel.setSpecies(vcSpeciesHash.values().toArray(new Species[0]));
        vcModel.setSpeciesContexts(vcSpeciesContexts);
        // Set annotations and notes from SBML to VCMetadata
        Species[] vcSpeciesArray = vc_sbmlSpeciesHash.keySet().toArray(new Species[0]);
        for (Species vcSpecies : vcSpeciesArray) {
            org.sbml.jsbml.Species sbmlSpecies = vc_sbmlSpeciesHash.get(vcSpecies);
            sbmlAnnotationUtil.readAnnotation(vcSpecies, sbmlSpecies);
            sbmlAnnotationUtil.readNotes(vcSpecies, sbmlSpecies);
        }
    } catch (ModelPropertyVetoException e) {
        throw new SBMLImportException("Error adding species context; " + e.getMessage(), e);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new SBMLImportException("Error adding species context; " + e.getMessage(), e);
    }
}
Also used : HashMap(java.util.HashMap) Compartment(org.sbml.jsbml.Compartment) Element(org.jdom.Element) SpeciesContext(cbit.vcell.model.SpeciesContext) 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) ModelPropertyVetoException(cbit.vcell.model.ModelPropertyVetoException) ListOf(org.sbml.jsbml.ListOf) Model(cbit.vcell.model.Model) BioModel(cbit.vcell.biomodel.BioModel) Structure(cbit.vcell.model.Structure) Species(cbit.vcell.model.Species)

Aggregations

Species (cbit.vcell.model.Species)39 SpeciesContext (cbit.vcell.model.SpeciesContext)28 Structure (cbit.vcell.model.Structure)21 Model (cbit.vcell.model.Model)16 PropertyVetoException (java.beans.PropertyVetoException)13 KeyValue (org.vcell.util.document.KeyValue)12 Feature (cbit.vcell.model.Feature)11 ReactionStep (cbit.vcell.model.ReactionStep)11 Expression (cbit.vcell.parser.Expression)11 DBSpecies (cbit.vcell.model.DBSpecies)10 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)9 Membrane (cbit.vcell.model.Membrane)9 SimpleReaction (cbit.vcell.model.SimpleReaction)9 BioModel (cbit.vcell.biomodel.BioModel)8 KineticsParameter (cbit.vcell.model.Kinetics.KineticsParameter)8 ModelException (cbit.vcell.model.ModelException)8 ArrayList (java.util.ArrayList)8 FeatureMapping (cbit.vcell.mapping.FeatureMapping)7 DBFormalSpecies (cbit.vcell.model.DBFormalSpecies)7 ImageException (cbit.image.ImageException)6