Search in sources :

Example 11 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class XmlReader method getSimulationContext.

/**
 * This method returns a SimulationContext from a XML representation.
 * Creation date: (4/2/2001 3:19:01 PM)
 * @return cbit.vcell.mapping.SimulationContext
 * @param param org.jdom.Element
 */
private SimulationContext getSimulationContext(Element param, BioModel biomodel) throws XmlParseException {
    // get the attributes
    // name
    String name = unMangle(param.getAttributeValue(XMLTags.NameAttrTag));
    boolean bStoch = false;
    boolean bRuleBased = false;
    boolean bUseConcentration = true;
    boolean bRandomizeInitCondition = false;
    boolean bInsufficientIterations = false;
    boolean bInsufficientMaxMolecules = false;
    NetworkConstraints nc = null;
    Element ncElement = param.getChild(XMLTags.RbmNetworkConstraintsTag, vcNamespace);
    if (ncElement != null) {
        // one network constraint element
        nc = getAppNetworkConstraints(ncElement, biomodel.getModel());
    } else {
        if (legacyNetworkConstraints != null) {
            nc = legacyNetworkConstraints;
        }
    }
    if ((param.getAttributeValue(XMLTags.StochAttrTag) != null) && (param.getAttributeValue(XMLTags.StochAttrTag).equals("true"))) {
        bStoch = true;
    }
    if (bStoch) {
        // stochastic and using concentration vs amount
        if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
            bUseConcentration = false;
        }
        // stochastic and randomizing initial conditions or not (for non-spatial)
        if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
            bRandomizeInitCondition = true;
        }
    }
    if ((param.getAttributeValue(XMLTags.InsufficientIterationsTag) != null) && (param.getAttributeValue(XMLTags.InsufficientIterationsTag).equals("true"))) {
        bInsufficientIterations = true;
    }
    if ((param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag) != null) && (param.getAttributeValue(XMLTags.InsufficientMaxMoleculesTag).equals("true"))) {
        bInsufficientMaxMolecules = true;
    }
    if ((param.getAttributeValue(XMLTags.RuleBasedAttrTag) != null) && (param.getAttributeValue(XMLTags.RuleBasedAttrTag).equals("true"))) {
        bRuleBased = true;
        if ((param.getAttributeValue(XMLTags.ConcentrationAttrTag) != null) && (param.getAttributeValue(XMLTags.ConcentrationAttrTag).equals("false"))) {
            bUseConcentration = false;
        }
        if ((param.getAttributeValue(XMLTags.RandomizeInitConditionTag) != null) && (param.getAttributeValue(XMLTags.RandomizeInitConditionTag).equals("true"))) {
            // we propagate the flag but we don't use it for now
            bRandomizeInitCondition = true;
        }
    }
    // Retrieve Geometry
    Geometry newgeometry = null;
    try {
        newgeometry = getGeometry(param.getChild(XMLTags.GeometryTag, vcNamespace));
    } catch (Throwable e) {
        e.printStackTrace();
        String stackTrace = null;
        try {
            java.io.ByteArrayOutputStream bos = new java.io.ByteArrayOutputStream();
            java.io.PrintStream ps = new java.io.PrintStream(bos);
            e.printStackTrace(ps);
            ps.flush();
            bos.flush();
            stackTrace = new String(bos.toByteArray());
            ps.close();
            bos.close();
        } catch (Exception e2) {
        // do Nothing
        }
        throw new XmlParseException("A Problem occurred while retrieving the geometry for the simulationContext " + name, e);
    }
    // Retrieve MathDescription(if there is no MathDescription skip it)
    MathDescription newmathdesc = null;
    Element xmlMathDescription = param.getChild(XMLTags.MathDescriptionTag, vcNamespace);
    if (xmlMathDescription != null) {
        newmathdesc = getMathDescription(xmlMathDescription, newgeometry);
    }
    // Retrieve Version (Metada)
    Version version = getVersion(param.getChild(XMLTags.VersionTag, vcNamespace));
    // ------ Create SimContext ------
    SimulationContext newsimcontext = null;
    try {
        newsimcontext = new SimulationContext(biomodel.getModel(), newgeometry, newmathdesc, version, bStoch, bRuleBased);
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("A propertyveto exception was generated when creating the new SimulationContext " + name, e);
    }
    // set attributes
    try {
        newsimcontext.setName(name);
        // Add annotation
        String annotation = param.getChildText(XMLTags.AnnotationTag, vcNamespace);
        if (annotation != null && annotation.length() > 0) {
            newsimcontext.setDescription(unMangle(annotation));
        }
        // set if using concentration
        newsimcontext.setUsingConcentration(bUseConcentration);
        // set if randomizing init condition or not (for stochastic applications
        if (bStoch) {
            newsimcontext.setRandomizeInitConditions(bRandomizeInitCondition);
        }
        if (bInsufficientIterations) {
            newsimcontext.setInsufficientIterations(bInsufficientIterations);
        }
        if (bInsufficientMaxMolecules) {
            newsimcontext.setInsufficientMaxMolecules(bInsufficientMaxMolecules);
        }
        if (nc != null) {
            newsimcontext.setNetworkConstraints(nc);
        }
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("Exception", e);
    }
    String tempchar = param.getAttributeValue(XMLTags.CharacteristicSizeTag);
    if (tempchar != null) {
        try {
            newsimcontext.setCharacteristicSize(Double.valueOf(tempchar));
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException was fired when setting the CharacteristicSize " + tempchar, e);
        }
    }
    // Retrieve DataContext
    Element dataContextElement = param.getChild(XMLTags.DataContextTag, vcNamespace);
    if (dataContextElement != null) {
        DataContext dataContext = newsimcontext.getDataContext();
        ArrayList<DataSymbol> dataSymbols = getDataSymbols(dataContextElement, dataContext, newsimcontext.getModel().getUnitSystem());
        for (int i = 0; i < dataSymbols.size(); i++) {
            dataContext.addDataSymbol(dataSymbols.get(i));
        }
    }
    // Retrieve spatialObjects and add to simContext
    Element spatialObjectsElement = param.getChild(XMLTags.SpatialObjectsTag, vcNamespace);
    if (spatialObjectsElement != null) {
        SpatialObject[] spatialObjects = getSpatialObjects(newsimcontext, spatialObjectsElement);
        try {
            newsimcontext.setSpatialObjects(spatialObjects);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding spatialObjects to simulationContext", e);
        }
    }
    // Retrieve application parameters and add to simContext
    Element appParamsElement = param.getChild(XMLTags.ApplicationParametersTag, vcNamespace);
    if (appParamsElement != null) {
        SimulationContextParameter[] appParameters = getSimulationContextParams(appParamsElement, newsimcontext);
        try {
            newsimcontext.setSimulationContextParameters(appParameters);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding application parameters to simulationContext", e);
        }
    }
    // 
    // -Process the GeometryContext-
    // 
    Element tempelement = param.getChild(XMLTags.GeometryContextTag, vcNamespace);
    LinkedList<StructureMapping> maplist = new LinkedList<StructureMapping>();
    // Retrieve FeatureMappings
    Iterator<Element> iterator = tempelement.getChildren(XMLTags.FeatureMappingTag, vcNamespace).iterator();
    while (iterator.hasNext()) {
        maplist.add(getFeatureMapping((Element) (iterator.next()), newsimcontext));
    }
    // Retrieve MembraneMappings
    iterator = tempelement.getChildren(XMLTags.MembraneMappingTag, vcNamespace).iterator();
    while (iterator.hasNext()) {
        maplist.add(getMembraneMapping((Element) (iterator.next()), newsimcontext));
    }
    // Add these mappings to the internal geometryContext of this simcontext
    StructureMapping[] structarray = new StructureMapping[maplist.size()];
    maplist.toArray(structarray);
    try {
        newsimcontext.getGeometryContext().setStructureMappings(structarray);
        newsimcontext.getGeometryContext().refreshStructureMappings();
        newsimcontext.refreshSpatialObjects();
    } catch (MappingException e) {
        e.printStackTrace();
        throw new XmlParseException("A MappingException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new XmlParseException("A PopertyVetoException was fired when trying to set the StructureMappings array to the Geometrycontext of the SimContext " + name, e);
    }
    // 
    // -Process the ReactionContext-
    // 
    tempelement = param.getChild(XMLTags.ReactionContextTag, vcNamespace);
    // Retrieve ReactionSpecs
    List<Element> children = tempelement.getChildren(XMLTags.ReactionSpecTag, vcNamespace);
    if (children.size() != 0) {
        if (children.size() != biomodel.getModel().getReactionSteps().length) {
            throw new XmlParseException("The number of reactions is not consistent.\n" + "Model reactions=" + biomodel.getModel().getReactionSteps().length + ", Reaction specs=" + children.size());
        }
        // *NOTE: Importing a model from other languages does not generates reaction specs.
        // A more robust code will read the reactions in the source file and replace the ones created by the default by the VirtualCell framework.
        ReactionSpec[] reactionSpecs = new ReactionSpec[children.size()];
        int rSpecCounter = 0;
        for (Element rsElement : children) {
            reactionSpecs[rSpecCounter] = getReactionSpec(rsElement, newsimcontext);
            rSpecCounter++;
        }
        try {
            newsimcontext.getReactionContext().setReactionSpecs(reactionSpecs);
        } catch (java.beans.PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionSpecs to the SimContext " + name, e);
        }
    }
    // Retrieve ReactionRuleSpecs
    Element reactionRuleSpecsElement = tempelement.getChild(XMLTags.ReactionRuleSpecsTag, vcNamespace);
    if (reactionRuleSpecsElement != null) {
        ReactionRuleSpec[] reactionRuleSpecs = getReactionRuleSpecs(newsimcontext, reactionRuleSpecsElement);
        try {
            newsimcontext.getReactionContext().setReactionRuleSpecs(reactionRuleSpecs);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException("A PropertyVetoException occurred while setting the ReactionRuleSpecs to the SimContext " + name, e);
        }
    }
    children = tempelement.getChildren(XMLTags.SpeciesContextSpecTag, vcNamespace);
    getSpeciesContextSpecs(children, newsimcontext.getReactionContext(), biomodel.getModel());
    // Retrieve output functions
    Element outputFunctionsElement = param.getChild(XMLTags.OutputFunctionsTag, vcNamespace);
    if (outputFunctionsElement != null) {
        ArrayList<AnnotatedFunction> outputFunctions = getOutputFunctions(outputFunctionsElement);
        try {
            // construct OutputFnContext from mathDesc in newSimContext and add output functions that were read in from XML.
            OutputFunctionContext outputFnContext = newsimcontext.getOutputFunctionContext();
            for (AnnotatedFunction outputFunction : outputFunctions) {
                outputFnContext.addOutputFunction(outputFunction);
            }
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new XmlParseException(e);
        }
    }
    // Retrieve Electrical context
    org.jdom.Element electElem = param.getChild(XMLTags.ElectricalContextTag, vcNamespace);
    // this information is optional!
    if (electElem != null) {
        if (electElem.getChild(XMLTags.ClampTag, vcNamespace) != null) {
            // read clamp
            ElectricalStimulus[] electArray = new ElectricalStimulus[1];
            electArray[0] = getElectricalStimulus(electElem.getChild(XMLTags.ClampTag, vcNamespace), newsimcontext);
            try {
                newsimcontext.setElectricalStimuli(electArray);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
        }
        // read ground electrode
        if (electElem.getChild(XMLTags.ElectrodeTag, vcNamespace) != null) {
            Electrode groundElectrode = getElectrode(electElem.getChild(XMLTags.ElectrodeTag, vcNamespace), newsimcontext);
            try {
                newsimcontext.setGroundElectrode(groundElectrode);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException(e);
            }
        }
    }
    // Retrieve (bio)events and add to simContext
    tempelement = param.getChild(XMLTags.BioEventsTag, vcNamespace);
    if (tempelement != null) {
        BioEvent[] bioEvents = getBioEvents(newsimcontext, tempelement);
        try {
            newsimcontext.setBioEvents(bioEvents);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding events to simulationContext", e);
        }
    }
    // Retrieve spatialProcesses and add to simContext
    tempelement = param.getChild(XMLTags.SpatialProcessesTag, vcNamespace);
    if (tempelement != null) {
        SpatialProcess[] spatialProcesses = getSpatialProcesses(newsimcontext, tempelement);
        try {
            newsimcontext.setSpatialProcesses(spatialProcesses);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding spatialProcesses to simulationContext", e);
        }
    }
    // Retrieve rate rules and add to simContext
    tempelement = param.getChild(XMLTags.RateRulesTag, vcNamespace);
    if (tempelement != null) {
        RateRule[] rateRules = getRateRules(newsimcontext, tempelement);
        try {
            newsimcontext.setRateRules(rateRules);
        } catch (PropertyVetoException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Error adding rate rules to simulationContext", e);
        }
    }
    org.jdom.Element analysisTaskListElement = param.getChild(XMLTags.AnalysisTaskListTag, vcNamespace);
    if (analysisTaskListElement != null) {
        children = analysisTaskListElement.getChildren(XMLTags.ParameterEstimationTaskTag, vcNamespace);
        if (children.size() != 0) {
            Vector<ParameterEstimationTask> analysisTaskList = new Vector<ParameterEstimationTask>();
            for (Element parameterEstimationTaskElement : children) {
                try {
                    ParameterEstimationTask parameterEstimationTask = ParameterEstimationTaskXMLPersistence.getParameterEstimationTask(parameterEstimationTaskElement, newsimcontext);
                    analysisTaskList.add(parameterEstimationTask);
                } catch (Exception e) {
                    e.printStackTrace(System.out);
                    throw new XmlParseException("An Exception occurred when parsing AnalysisTasks of SimContext " + name, e);
                }
            }
            try {
                AnalysisTask[] analysisTasks = (AnalysisTask[]) BeanUtils.getArray(analysisTaskList, AnalysisTask.class);
                newsimcontext.setAnalysisTasks(analysisTasks);
            } catch (java.beans.PropertyVetoException e) {
                e.printStackTrace(System.out);
                throw new XmlParseException("A PropertyVetoException occurred when setting the AnalysisTasks of the SimContext " + name, e);
            }
        }
    }
    // Microscope Measurement
    org.jdom.Element element = param.getChild(XMLTags.MicroscopeMeasurement, vcNamespace);
    if (element != null) {
        getMicroscopeMeasurement(element, newsimcontext);
    }
    for (GeometryClass gc : newsimcontext.getGeometry().getGeometryClasses()) {
        try {
            StructureSizeSolver.updateUnitStructureSizes(newsimcontext, gc);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    newsimcontext.getGeometryContext().enforceHierarchicalBoundaryConditions(newsimcontext.getModel().getStructureTopology());
    return newsimcontext;
}
Also used : MathDescription(cbit.vcell.math.MathDescription) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) Version(org.vcell.util.document.Version) RedistributionVersion(cbit.vcell.solvers.mb.MovingBoundarySolverOptions.RedistributionVersion) SimulationVersion(org.vcell.util.document.SimulationVersion) VCellSoftwareVersion(org.vcell.util.document.VCellSoftwareVersion) SpatialProcess(cbit.vcell.mapping.spatial.processes.SpatialProcess) RateRule(cbit.vcell.mapping.RateRule) Vector(java.util.Vector) AnnotatedFunction(cbit.vcell.solver.AnnotatedFunction) Electrode(cbit.vcell.mapping.Electrode) ReactionSpec(cbit.vcell.mapping.ReactionSpec) ReactionRuleSpec(cbit.vcell.mapping.ReactionRuleSpec) LinkedList(java.util.LinkedList) PropertyVetoException(java.beans.PropertyVetoException) OutputFunctionContext(cbit.vcell.solver.OutputFunctionContext) FieldDataSymbol(cbit.vcell.data.FieldDataSymbol) DataSymbol(cbit.vcell.data.DataSymbol) ParameterEstimationTask(cbit.vcell.modelopt.ParameterEstimationTask) AnalysisTask(cbit.vcell.modelopt.AnalysisTask) NetworkConstraints(org.vcell.model.rbm.NetworkConstraints) GeometryClass(cbit.vcell.geometry.GeometryClass) Element(org.jdom.Element) StructureMapping(cbit.vcell.mapping.StructureMapping) SpatialObject(cbit.vcell.mapping.spatial.SpatialObject) DataContext(cbit.vcell.data.DataContext) SimulationContext(cbit.vcell.mapping.SimulationContext) SimulationContextParameter(cbit.vcell.mapping.SimulationContext.SimulationContextParameter) GeometryException(cbit.vcell.geometry.GeometryException) MathFormatException(cbit.vcell.math.MathFormatException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) ModelException(cbit.vcell.model.ModelException) DataConversionException(org.jdom.DataConversionException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) Geometry(cbit.vcell.geometry.Geometry) ElectricalStimulus(cbit.vcell.mapping.ElectricalStimulus) BioEvent(cbit.vcell.mapping.BioEvent) Element(org.jdom.Element)

Example 12 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class CellQuanVCTranslator method addGeometry.

// use a dummy compartmental geometry
protected void addGeometry() {
    try {
        // Create dummy compartmental geometry for now ?
        Geometry geometry = new Geometry("Default", 0);
        geometry.getGeometrySpec().setExtent(new org.vcell.util.Extent(10.0, 10.0, 10.0));
        geometry.getGeometrySpec().setOrigin(new org.vcell.util.Origin(0.0, 0.0, 0.0));
        mathDescription.setGeometry(geometry);
    } catch (Exception e) {
        e.printStackTrace(System.out);
        throw new RuntimeException("Error creating geometry for model : " + e.getMessage());
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 13 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class SimulationContext method refreshCharacteristicSize.

/**
 * This method was created in VisualAge.
 * @return java.lang.Double
 */
private void refreshCharacteristicSize() throws PropertyVetoException {
    Geometry geo = getGeometryContext().getGeometry();
    int dimension = geo.getDimension();
    if (dimension == 0) {
        setCharacteristicSize(null);
        return;
    }
    Extent extent = geo.getExtent();
    if (characteristicSize == null) {
        // 
        // if characteristicSize is not specified, estimate a 'good' value
        // 
        VCImage image = geo.getGeometrySpec().getImage();
        if (image != null) {
            double pixelSizeX = extent.getX() / image.getNumX();
            double pixelSizeY = extent.getY() / image.getNumY();
            double pixelSizeZ = extent.getZ() / image.getNumZ();
            switch(dimension) {
                case 1:
                    {
                        setCharacteristicSize(new Double(pixelSizeX));
                        break;
                    }
                case 2:
                    {
                        setCharacteristicSize(new Double(Math.min(pixelSizeX, pixelSizeY)));
                        break;
                    }
                case 3:
                    {
                        setCharacteristicSize(new Double(Math.min(pixelSizeX, Math.min(pixelSizeY, pixelSizeZ))));
                        break;
                    }
                default:
                    {
                        throw new RuntimeException("unexpected geometry dimension = '" + dimension + "'");
                    }
            }
        } else {
            // 
            // image doesn't exist, apply heuristics
            // 
            // 
            // 
            // choose spatial steps to give reasonable size mesh ( < MaxNumberElements)
            // 
            // start with very small elements (~0.01 * smallest dimension)
            // 
            // if number of elements exceed 100,000 then take larger steps
            // 
            long MaxNumberElements = 1000000;
            long MaxPerDimension = 500;
            long totalElements = MaxNumberElements + 1;
            double elementLength = Math.min(extent.getX(), Math.min(extent.getY(), extent.getZ())) / (MaxPerDimension);
            while (true) {
                // 
                // calculate total elements based on characteristic length
                // 
                int numY = -1;
                int numZ = -1;
                int numX = (int) Math.round(extent.getX() / elementLength);
                if (dimension > 1) {
                    numY = (int) Math.round(extent.getY() / elementLength);
                } else {
                    numY = 1;
                }
                if (dimension > 2) {
                    numZ = (int) Math.round(extent.getZ() / elementLength);
                } else {
                    numZ = 1;
                }
                totalElements = numX * numY * numZ;
                if ((numX <= MaxPerDimension) && (numY <= MaxPerDimension) && (numZ <= MaxPerDimension) && (totalElements <= MaxNumberElements)) {
                    break;
                } else {
                    elementLength *= 1.125;
                }
            }
            setCharacteristicSize(new Double(elementLength));
        }
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) Extent(org.vcell.util.Extent) VCImage(cbit.image.VCImage)

Example 14 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class FRAPStudy method createNewRefBioModel.

public static BioModel createNewRefBioModel(FRAPStudy sourceFrapStudy, String baseDiffusionRate, TimeStep tStep, KeyValue simKey, User owner, FieldDataIdentifierSpec psfFDIS, 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());
    Extent extent = sourceFrapStudy.getFrapData().getImageDataset().getExtent();
    TimeBounds timeBounds = FRAPOptData.getEstimatedRefTimeBound(sourceFrapStudy);
    double timeStepVal = FRAPOptData.REFERENCE_DIFF_DELTAT;
    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);
    Feature extracellular = model.addFeature(EXTRACELLULAR_NAME);
    Feature cytosol = model.addFeature(CYTOSOL_NAME);
    Membrane plasmaMembrane = model.addMembrane(PLASMAMEMBRANE_NAME);
    String roiDataName = FRAPStudy.ROI_EXTDATA_NAME;
    final int ONE_DIFFUSION_SPECIES_COUNT = 1;
    final int MOBILE_SPECIES_INDEX = 0;
    Expression[] diffusionConstants = new Expression[ONE_DIFFUSION_SPECIES_COUNT];
    Species[] species = new Species[ONE_DIFFUSION_SPECIES_COUNT];
    SpeciesContext[] speciesContexts = new SpeciesContext[ONE_DIFFUSION_SPECIES_COUNT];
    Expression[] initialConditions = new Expression[ONE_DIFFUSION_SPECIES_COUNT];
    // Mobile Species
    diffusionConstants[MOBILE_SPECIES_INDEX] = new Expression(baseDiffusionRate);
    species[MOBILE_SPECIES_INDEX] = new Species(SPECIES_NAME_PREFIX_MOBILE, "Mobile bleachable species");
    speciesContexts[MOBILE_SPECIES_INDEX] = new SpeciesContext(null, species[MOBILE_SPECIES_INDEX].getCommonName(), species[MOBILE_SPECIES_INDEX], cytosol);
    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());
    initialConditions[MOBILE_SPECIES_INDEX] = Expression.div(expPostBleach_first, expPreBleach_avg);
    SimulationContext simContext = new SimulationContext(bioModel.getModel(), geometry);
    bioModel.addSimulationContext(simContext);
    FeatureMapping cytosolFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(cytosol);
    FeatureMapping extracellularFeatureMapping = (FeatureMapping) simContext.getGeometryContext().getStructureMapping(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));
    plasmaMembraneMapping.getUnitSizeParameter().setExpression(new Expression(1.0));
    for (int i = 0; i < initialConditions.length; i++) {
        model.addSpecies(species[i]);
        model.addSpeciesContext(speciesContexts[i]);
    }
    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 PSF function
    mathDesc.addVariable(new Function(Simulation.PSF_FUNCTION_NAME, new Expression(psfFDIS.getFieldFuncArgs().infix()), 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, simContext.getMathDescription());
    newSimulation.getSolverTaskDescription().setSolverDescription(SolverDescription.FiniteVolumeStandalone);
    simContext.addSimulation(newSimulation);
    newSimulation.getSolverTaskDescription().setTimeBounds(timeBounds);
    newSimulation.getSolverTaskDescription().setOutputTimeSpec(new UniformOutputTimeSpec(timeStepVal));
    newSimulation.getMeshSpecification().setSamplingSize(cellROI_2D.getISize());
    newSimulation.getSolverTaskDescription().setTimeStep(new TimeStep(timeStepVal, timeStepVal, timeStepVal));
    return bioModel;
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) 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) TimeStep(cbit.vcell.solver.TimeStep) SimulationVersion(org.vcell.util.document.SimulationVersion) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Membrane(cbit.vcell.model.Membrane) Species(cbit.vcell.model.Species) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) 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)

Example 15 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class DatabaseWindowManager method createNewGeometry.

public void createNewGeometry() {
    AsynchClientTask editSelectTask = new AsynchClientTask("Edit/Apply Geometry", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            Geometry newGeom = (Geometry) hashTable.get("doc");
            if (newGeom == null) {
                throw new Exception("No Geometry found in edit task");
            }
            DocumentCreationInfo documentCreationInfo = new DocumentCreationInfo(VCDocumentType.GEOMETRY_DOC, -1);
            documentCreationInfo.setPreCreatedDocument(newGeom);
            AsynchClientTask[] newGeometryTaskArr = getRequestManager().newDocument(DatabaseWindowManager.this, documentCreationInfo);
            ClientTaskDispatcher.dispatch(DatabaseWindowManager.this.getComponent(), hashTable, newGeometryTaskArr);
        }
    };
    createGeometry(null, new AsynchClientTask[] { editSelectTask }, TopLevelWindowManager.DEFAULT_CREATEGEOM_SELECT_DIALOG_TITLE, "Create Geometry", null);
}
Also used : Geometry(cbit.vcell.geometry.Geometry) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) DocumentCreationInfo(org.vcell.util.document.VCDocument.DocumentCreationInfo) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) DataAccessException(org.vcell.util.DataAccessException) UserCancelException(org.vcell.util.UserCancelException)

Aggregations

Geometry (cbit.vcell.geometry.Geometry)121 MathDescription (cbit.vcell.math.MathDescription)32 SimulationContext (cbit.vcell.mapping.SimulationContext)31 Simulation (cbit.vcell.solver.Simulation)29 PropertyVetoException (java.beans.PropertyVetoException)24 BioModel (cbit.vcell.biomodel.BioModel)23 DataAccessException (org.vcell.util.DataAccessException)23 VCImage (cbit.image.VCImage)22 SubVolume (cbit.vcell.geometry.SubVolume)21 MathModel (cbit.vcell.mathmodel.MathModel)21 Expression (cbit.vcell.parser.Expression)19 ISize (org.vcell.util.ISize)19 Hashtable (java.util.Hashtable)18 GeometryThumbnailImageFactoryAWT (cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT)17 UserCancelException (org.vcell.util.UserCancelException)17 KeyValue (org.vcell.util.document.KeyValue)17 ImageException (cbit.image.ImageException)16 Extent (org.vcell.util.Extent)16 SurfaceClass (cbit.vcell.geometry.SurfaceClass)15 ExpressionException (cbit.vcell.parser.ExpressionException)15