Search in sources :

Example 61 with Feature

use of cbit.vcell.model.Feature 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 62 with Feature

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

the class ITextWriter method writeStructure.

protected void writeStructure(Model model, Structure struct, Table structTable) throws DocumentException {
    // If this structure has any reactions in it, add its name as a hyperlink to the reactions' list.
    if (hasReactions(model, struct)) {
        Paragraph linkParagraph = new Paragraph();
        Font linkFont;
        try {
            BaseFont fontBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
            linkFont = new Font(fontBaseFont, DEF_FONT_SIZE, Font.NORMAL, new java.awt.Color(0, 0, 255));
        } catch (Exception e) {
            linkFont = getFont();
            e.printStackTrace();
        }
        linkParagraph.add(new Chunk(struct.getName(), linkFont).setLocalGoto(struct.getName()));
        Cell structLinkCell = new Cell(linkParagraph);
        structLinkCell.setBorderWidth(1);
        structLinkCell.setHorizontalAlignment(Element.ALIGN_LEFT);
        structTable.addCell(structLinkCell);
    } else {
        structTable.addCell(createCell(struct.getName(), getFont()));
    }
    StructureTopology structTopology = model.getStructureTopology();
    if (struct instanceof Membrane) {
        structTable.addCell(createCell("Membrane", getFont()));
        Feature outsideFeature = structTopology.getOutsideFeature((Membrane) struct);
        Feature insideFeature = structTopology.getInsideFeature((Membrane) struct);
        structTable.addCell(createCell((insideFeature != null ? insideFeature.getName() : "N/A"), getFont()));
        structTable.addCell(createCell((outsideFeature != null ? outsideFeature.getName() : "N/A"), getFont()));
    } else {
        structTable.addCell(createCell("Feature", getFont()));
        String outsideStr = "N/A", insideStr = "N/A";
        Membrane enclosingMem = (Membrane) structTopology.getParentStructure(struct);
        if (enclosingMem != null) {
            outsideStr = enclosingMem.getName();
        }
        // To do:  retrieve the 'child' membrane here...
        structTable.addCell(createCell(insideStr, getFont()));
        structTable.addCell(createCell(outsideStr, getFont()));
    }
}
Also used : StructureTopology(cbit.vcell.model.Model.StructureTopology) Color(java.awt.Color) BaseFont(com.lowagie.text.pdf.BaseFont) Membrane(cbit.vcell.model.Membrane) Chunk(com.lowagie.text.Chunk) Cell(com.lowagie.text.Cell) Feature(cbit.vcell.model.Feature) BaseFont(com.lowagie.text.pdf.BaseFont) Font(com.lowagie.text.Font) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) Paragraph(com.lowagie.text.Paragraph)

Example 63 with Feature

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

the class StructureSizeSolver method updateUnitStructureSizes.

/**
 * Insert the method's description here.
 * Creation date: (5/17/2006 10:33:38 AM)
 * @return double[]
 * @param structName java.lang.String
 * @param structSize double
 */
public static void updateUnitStructureSizes(SimulationContext simContext, GeometryClass geometryClass) {
    if (simContext.getGeometryContext().getGeometry().getDimension() == 0) {
        return;
    }
    StructureMapping[] myStructMappings = simContext.getGeometryContext().getStructureMappings(geometryClass);
    if (myStructMappings != null && myStructMappings.length == 1) {
        // if the unitSizeParameter is dimensionless, then features are mapped to SubVolumes or Membranes are mapped to surfaces (should sum to 1)
        boolean bDimensionless = myStructMappings[0].getUnitSizeParameter().getUnitDefinition().isEquivalent(simContext.getModel().getUnitSystem().getInstance_DIMENSIONLESS());
        if (bDimensionless) {
            try {
                myStructMappings[0].getUnitSizeParameter().setExpression(new Expression(1.0));
                return;
            } catch (ExpressionException e) {
                e.printStackTrace(System.out);
                throw new RuntimeException(e.getMessage());
            }
        }
    }
    if (myStructMappings != null && myStructMappings.length == 0) {
        // nothing to solve, there are no mappings for this geometryClass
        return;
    }
    StructureMapping[] structMappings = simContext.getGeometryContext().getStructureMappings();
    try {
        ConstraintContainerImpl ccImpl = new ConstraintContainerImpl();
        Structure struct = null;
        Expression totalVolExpr = new Expression(0.0);
        StructureTopology structureTopology = simContext.getModel().getStructureTopology();
        for (int i = 0; i < structMappings.length; i++) {
            if (structMappings[i].getGeometryClass() != geometryClass) {
                continue;
            }
            // new model with unit sizes already
            if (structMappings[i].getUnitSizeParameter() != null && structMappings[i].getUnitSizeParameter().getExpression() != null) {
                return;
            }
            if (struct == null) {
                struct = structMappings[i].getStructure();
            }
            if (structMappings[i] instanceof MembraneMapping) {
                MembraneMapping membraneMapping = (MembraneMapping) structMappings[i];
                Membrane membrane = membraneMapping.getMembrane();
                String membraneSizeName = TokenMangler.mangleToSName(membrane.getName() + "_size");
                ccImpl.addSimpleBound(new SimpleBounds(membraneSizeName, new RealInterval(0, 100000), AbstractConstraint.PHYSICAL_LIMIT, "definition"));
                Feature insideFeature = structureTopology.getInsideFeature(membrane);
                String volFractName = TokenMangler.mangleToSName(insideFeature.getName() + "_volFract");
                String svRatioName = TokenMangler.mangleToSName(insideFeature.getName() + "_svRatio");
                StructureMapping.StructureMappingParameter volFractParameter = membraneMapping.getVolumeFractionParameter();
                double volFractValue = volFractParameter.getExpression().evaluateConstant();
                ccImpl.addSimpleBound(new SimpleBounds(volFractName, new RealInterval(volFractValue, volFractValue), AbstractConstraint.MODELING_ASSUMPTION, "from model"));
                StructureMapping.StructureMappingParameter surfToVolParameter = membraneMapping.getSurfaceToVolumeParameter();
                double svRatioValue = surfToVolParameter.getExpression().evaluateConstant();
                ccImpl.addSimpleBound(new SimpleBounds(svRatioName, new RealInterval(svRatioValue, svRatioValue), AbstractConstraint.MODELING_ASSUMPTION, "from model"));
                // membrane mapped to volume
                if (geometryClass instanceof SubVolume) {
                    // 
                    // EC eclosing cyt, which contains er and golgi
                    // "(cyt_size+ er_size + golgi_size) * cyt_svRatio - PM_size == 0"
                    // 
                    Expression sumOfInsideVolumeExp = new Expression(0.0);
                    for (int j = 0; j < structMappings.length; j++) {
                        if (structMappings[j] instanceof FeatureMapping && structureTopology.enclosedBy(structMappings[j].getStructure(), insideFeature)) {
                            Feature childFeatureOfInside = ((FeatureMapping) structMappings[j]).getFeature();
                            if (simContext.getGeometryContext().getStructureMapping(childFeatureOfInside).getGeometryClass() == geometryClass) {
                                sumOfInsideVolumeExp = Expression.add(sumOfInsideVolumeExp, new Expression(TokenMangler.mangleToSName(childFeatureOfInside.getName() + "_size")));
                            }
                        }
                    }
                    Expression tempExpr = Expression.mult(sumOfInsideVolumeExp, new Expression(svRatioName));
                    tempExpr = Expression.add(tempExpr, new Expression("-" + membraneSizeName));
                    ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(tempExpr.infix() + "==0"), AbstractConstraint.MODELING_ASSUMPTION, "svRatio definition"));
                    // 
                    // EC eclosing cyt, which contains er and golgi
                    // (EC_size + cyt_size + er_size + golgi_size) * cyt_vfRatio - (cyt_size + er_size + golgi_size) == 0
                    // 
                    Feature outsideFeature = structureTopology.getOutsideFeature(membrane);
                    Expression sumOfParentVolumeExp = new Expression(0.0);
                    for (int j = 0; j < structMappings.length; j++) {
                        if (structMappings[j] instanceof FeatureMapping && structureTopology.enclosedBy(structMappings[j].getStructure(), outsideFeature)) {
                            Feature childFeatureOfParent = ((FeatureMapping) structMappings[j]).getFeature();
                            if (simContext.getGeometryContext().getStructureMapping(childFeatureOfParent).getGeometryClass() == geometryClass) {
                                sumOfParentVolumeExp = Expression.add(sumOfParentVolumeExp, new Expression(TokenMangler.mangleToSName(childFeatureOfParent.getName() + "_size")));
                            }
                        }
                    }
                    Expression exp = Expression.mult(sumOfParentVolumeExp, new Expression(volFractName));
                    exp = Expression.add(exp, Expression.negate(sumOfInsideVolumeExp));
                    ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(exp.infix() + "==0.0"), AbstractConstraint.MODELING_ASSUMPTION, "volFract definition"));
                }
            } else if (structMappings[i] instanceof FeatureMapping) {
                FeatureMapping featureMapping = (FeatureMapping) structMappings[i];
                String featureSizeName = TokenMangler.mangleToSName(featureMapping.getFeature().getName() + "_size");
                totalVolExpr = Expression.add(totalVolExpr, new Expression(featureSizeName));
                ccImpl.addSimpleBound(new SimpleBounds(featureSizeName, new RealInterval(0, 1), AbstractConstraint.PHYSICAL_LIMIT, "definition"));
            }
        }
        if (geometryClass instanceof SubVolume) {
            ccImpl.addGeneralConstraint(new GeneralConstraint(new Expression(totalVolExpr.infix() + "==1.0"), AbstractConstraint.MODELING_ASSUMPTION, "total volume"));
        }
        // ccImpl.show();
        ConstraintSolver constraintSolver = new ConstraintSolver(ccImpl);
        constraintSolver.resetIntervals();
        int numTimesNarrowed = 0;
        RealInterval[] lastSolution = null;
        boolean bChanged = true;
        while (constraintSolver.narrow() && bChanged && numTimesNarrowed < 125) {
            numTimesNarrowed++;
            bChanged = false;
            RealInterval[] thisSolution = constraintSolver.getIntervals();
            if (lastSolution != null) {
                for (int i = 0; i < thisSolution.length; i++) {
                    if (!thisSolution[i].equals(lastSolution[i])) {
                        bChanged = true;
                    }
                }
            } else {
                bChanged = true;
            }
            lastSolution = thisSolution;
        }
        System.out.println("num of times narrowed = " + numTimesNarrowed);
        if (numTimesNarrowed > 0) {
            String[] symbols = constraintSolver.getSymbols();
            net.sourceforge.interval.ia_math.RealInterval[] solution = constraintSolver.getIntervals();
            double totalArea = 0;
            double totalVolume = 0;
            for (int i = 0; i < symbols.length; i++) {
                System.out.println("solution[" + i + "] \"" + symbols[i] + "\" = " + solution[i]);
                for (int j = 0; j < structMappings.length; j++) {
                    if (symbols[i].equals(TokenMangler.mangleToSName(structMappings[j].getStructure().getName() + "_size"))) {
                        if (!Double.isInfinite(solution[i].lo()) && !Double.isInfinite(solution[i].hi())) {
                            double value = (solution[i].lo() + solution[i].hi()) / 2;
                            Expression exp = new Expression(value);
                            if (structMappings[j] instanceof FeatureMapping) {
                                FeatureMapping fm = (FeatureMapping) structMappings[j];
                                totalVolume += value;
                                if (geometryClass instanceof SubVolume) {
                                    fm.getVolumePerUnitVolumeParameter().setExpression(exp);
                                } else if (geometryClass instanceof SurfaceClass) {
                                    fm.getVolumePerUnitAreaParameter().setExpression(exp);
                                }
                            } else if (structMappings[j] instanceof MembraneMapping) {
                                MembraneMapping mm = (MembraneMapping) structMappings[j];
                                totalArea += value;
                                if (geometryClass instanceof SubVolume) {
                                    mm.getAreaPerUnitVolumeParameter().setExpression(exp);
                                } else if (geometryClass instanceof SurfaceClass) {
                                    mm.getAreaPerUnitAreaParameter().setExpression(exp);
                                }
                            }
                        }
                    }
                }
            }
            // 
            // normalize all so that total volume is 1.0 for subVolumes or
            // total area is 1.0 for surfaceClasses
            // 
            double scaleFactor = 1;
            if (geometryClass instanceof SubVolume) {
                scaleFactor = totalVolume;
            } else if (geometryClass instanceof SurfaceClass) {
                scaleFactor = totalArea;
            } else {
                throw new RuntimeException("unexpected GeometryClass");
            }
            for (int j = 0; j < structMappings.length; j++) {
                if (structMappings[j].getGeometryClass() == geometryClass) {
                    if (structMappings[j] instanceof FeatureMapping) {
                        FeatureMapping fm = (FeatureMapping) structMappings[j];
                        if (geometryClass instanceof SubVolume) {
                            fm.getVolumePerUnitVolumeParameter().setExpression(new Expression(fm.getVolumePerUnitVolumeParameter().getExpression().evaluateConstant() / scaleFactor));
                        } else if (geometryClass instanceof SurfaceClass) {
                            fm.getVolumePerUnitAreaParameter().setExpression(new Expression(fm.getVolumePerUnitAreaParameter().getExpression().evaluateConstant() / scaleFactor));
                        }
                    } else if (structMappings[j] instanceof MembraneMapping) {
                        MembraneMapping mm = (MembraneMapping) structMappings[j];
                        if (geometryClass instanceof SubVolume) {
                            mm.getAreaPerUnitVolumeParameter().setExpression(new Expression(mm.getAreaPerUnitVolumeParameter().getExpression().evaluateConstant() / scaleFactor));
                        } else if (geometryClass instanceof SurfaceClass) {
                            mm.getAreaPerUnitAreaParameter().setExpression(new Expression(mm.getAreaPerUnitAreaParameter().getExpression().evaluateConstant() / scaleFactor));
                        }
                    }
                }
            }
        } else {
            throw new RuntimeException("cannot solve for size");
        }
    } catch (ExpressionException e) {
        e.printStackTrace(System.out);
        throw new RuntimeException(e.getMessage());
    } catch (java.beans.PropertyVetoException e) {
        e.printStackTrace(System.out);
        throw new RuntimeException(e.getMessage());
    }
}
Also used : MembraneMapping(cbit.vcell.mapping.MembraneMapping) SimpleBounds(cbit.vcell.constraints.SimpleBounds) SurfaceClass(cbit.vcell.geometry.SurfaceClass) ConstraintSolver(cbit.vcell.constraints.ConstraintSolver) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) StructureMapping(cbit.vcell.mapping.StructureMapping) RealInterval(net.sourceforge.interval.ia_math.RealInterval) Feature(cbit.vcell.model.Feature) ExpressionException(cbit.vcell.parser.ExpressionException) FeatureMapping(cbit.vcell.mapping.FeatureMapping) SubVolume(cbit.vcell.geometry.SubVolume) Membrane(cbit.vcell.model.Membrane) ConstraintContainerImpl(cbit.vcell.constraints.ConstraintContainerImpl) Structure(cbit.vcell.model.Structure) StructureTopology(cbit.vcell.model.Model.StructureTopology) AbstractConstraint(cbit.vcell.constraints.AbstractConstraint) GeneralConstraint(cbit.vcell.constraints.GeneralConstraint) StructureMappingParameter(cbit.vcell.mapping.StructureMapping.StructureMappingParameter) Expression(cbit.vcell.parser.Expression)

Example 64 with Feature

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

the class SimulationContextTest method getExample.

/**
 * This method was created in VisualAge.
 * @return cbit.vcell.mapping.SimulationContext
 */
public static SimulationContext getExample(int dimension) throws Exception {
    // 
    // use example model
    // 
    cbit.vcell.model.Model model = getModelFromExample();
    cbit.vcell.geometry.Geometry geo = cbit.vcell.geometry.GeometryTest.getExample(dimension);
    SimulationContext simContext = new SimulationContext(model, geo);
    GeometryContext geoContext = simContext.getGeometryContext();
    ReactionContext reactContext = simContext.getReactionContext();
    if (dimension > 0) {
        Double charSize = simContext.getCharacteristicSize();
        simContext.setCharacteristicSize(new Double(charSize.doubleValue() / 2.0));
    }
    // 
    if (geo.getDimension() > 0) {
        cbit.vcell.model.Structure[] structures = geoContext.getModel().getStructures();
        for (int i = 0; i < structures.length; i++) {
            cbit.vcell.model.Structure structure = structures[i];
            if (structure instanceof cbit.vcell.model.Feature) {
                cbit.vcell.model.Feature feature = (cbit.vcell.model.Feature) structure;
                if (feature.getName().equals("extracellular") && geo.getDimension() > 0) {
                    geoContext.assignStructure(feature, geo.getGeometrySpec().getSubVolume("extracellular"));
                } else {
                    geoContext.assignStructure(feature, geo.getGeometrySpec().getSubVolume("cytosol"));
                }
            }
        }
    }
    // 
    // alter some speciesContextSpecs
    // 
    // add initial conditions
    // 
    SpeciesContextSpec[] speciesContextSpecs = reactContext.getSpeciesContextSpecs();
    for (int i = 0; i < speciesContextSpecs.length; i++) {
        SpeciesContextSpec scs = speciesContextSpecs[i];
        scs.getInitialConditionParameter().setExpression(Expression.add(scs.getInitialConditionParameter().getExpression(), new Expression(1.0)));
        scs.getBoundaryXmParameter().setExpression(new Expression(5.5));
    }
    return simContext;
}
Also used : Feature(cbit.vcell.model.Feature) Feature(cbit.vcell.model.Feature) Expression(cbit.vcell.parser.Expression)

Example 65 with Feature

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

the class SimulationContextTest method getExampleElectrical.

/**
 * This method was created in VisualAge.
 * @return cbit.vcell.mapping.SimulationContext
 */
public static SimulationContext getExampleElectrical(int dimension) throws Exception {
    // 
    // use example model
    // 
    cbit.vcell.model.Model model = cbit.vcell.model.ModelTest.getExampleWithCurrent();
    cbit.vcell.geometry.Geometry geo = cbit.vcell.geometry.GeometryTest.getExample(dimension);
    SimulationContext simContext = new SimulationContext(model, geo);
    GeometryContext geoContext = simContext.getGeometryContext();
    ReactionContext reactContext = simContext.getReactionContext();
    if (dimension > 0) {
        Double charSize = simContext.getCharacteristicSize();
        simContext.setCharacteristicSize(new Double(charSize.doubleValue() / 2.0));
    }
    // 
    if (geo.getDimension() > 0) {
        cbit.vcell.model.Structure[] structures = geoContext.getModel().getStructures();
        for (int i = 0; i < structures.length; i++) {
            cbit.vcell.model.Structure structure = structures[i];
            if (structure instanceof cbit.vcell.model.Feature) {
                cbit.vcell.model.Feature feature = (cbit.vcell.model.Feature) structure;
                if (feature.getName().equals("extracellular") && geo.getDimension() > 0) {
                    geoContext.assignStructure(feature, geo.getGeometrySpec().getSubVolume("extracellular"));
                } else {
                    geoContext.assignStructure(feature, geo.getGeometrySpec().getSubVolume("cytosol"));
                }
            }
        }
    }
    MembraneMapping membraneMapping = (MembraneMapping) geoContext.getStructureMapping(model.getStructure("PM"));
    membraneMapping.getSpecificCapacitanceParameter().setExpression(new Expression(1.0));
    membraneMapping.getInitialVoltageParameter().setExpression(new Expression(-70.0));
    // Add Electrical Stimulus and Gnd Electrode
    cbit.vcell.mapping.Electrode gndelectrode = new cbit.vcell.mapping.Electrode((Feature) model.getStructure("extracellular"), new org.vcell.util.Coordinate(10.0, 10.0, 10.0));
    simContext.setGroundElectrode(gndelectrode);
    cbit.vcell.mapping.Electrode newelectrode = new cbit.vcell.mapping.Electrode((Feature) model.getStructure("cytosol"), new org.vcell.util.Coordinate(0.0, 0.0, 0.0));
    Expression exp = new Expression("0.1*(t>0.01 && t<0.05)");
    String stimulusName = "Electrode";
    cbit.vcell.mapping.VoltageClampStimulus voltstimulus = new cbit.vcell.mapping.VoltageClampStimulus(newelectrode, stimulusName, exp, simContext);
    cbit.vcell.mapping.CurrentDensityClampStimulus currentstimulus = new cbit.vcell.mapping.CurrentDensityClampStimulus(newelectrode, stimulusName, exp, simContext);
    // simContext.setElectricalStimuli(new cbit.vcell.mapping.ElectricalStimulus[] {currentstimulus});
    simContext.setElectricalStimuli(new cbit.vcell.mapping.ElectricalStimulus[] { voltstimulus });
    // 
    // alter some speciesContextSpecs
    // 
    // add initial conditions
    // 
    SpeciesContextSpec[] speciesContextSpecs = reactContext.getSpeciesContextSpecs();
    for (int i = 0; i < speciesContextSpecs.length; i++) {
        SpeciesContextSpec scs = speciesContextSpecs[i];
        scs.getInitialConditionParameter().setExpression(Expression.add(scs.getInitialConditionParameter().getExpression(), new Expression(1.0)));
        scs.getBoundaryXmParameter().setExpression(new Expression(5.5));
    }
    return simContext;
}
Also used : Feature(cbit.vcell.model.Feature) Feature(cbit.vcell.model.Feature) Expression(cbit.vcell.parser.Expression)

Aggregations

Feature (cbit.vcell.model.Feature)71 Membrane (cbit.vcell.model.Membrane)50 Structure (cbit.vcell.model.Structure)36 Expression (cbit.vcell.parser.Expression)29 SpeciesContext (cbit.vcell.model.SpeciesContext)25 PropertyVetoException (java.beans.PropertyVetoException)18 Model (cbit.vcell.model.Model)16 StructureTopology (cbit.vcell.model.Model.StructureTopology)16 SimpleReaction (cbit.vcell.model.SimpleReaction)15 SubVolume (cbit.vcell.geometry.SubVolume)14 MembraneMapping (cbit.vcell.mapping.MembraneMapping)14 SurfaceClass (cbit.vcell.geometry.SurfaceClass)13 FeatureMapping (cbit.vcell.mapping.FeatureMapping)13 ExpressionException (cbit.vcell.parser.ExpressionException)13 FluxReaction (cbit.vcell.model.FluxReaction)12 ReactionStep (cbit.vcell.model.ReactionStep)12 KeyValue (org.vcell.util.document.KeyValue)12 BioModel (cbit.vcell.biomodel.BioModel)11 StructureMapping (cbit.vcell.mapping.StructureMapping)11 ModelUnitSystem (cbit.vcell.model.ModelUnitSystem)11