Search in sources :

Example 31 with UniformOutputTimeSpec

use of cbit.vcell.solver.UniformOutputTimeSpec in project vcell by virtualcell.

the class SmoldynFileWriter method writeRuntimeCommands.

// uncomment for debug
/*private void writeGraphicsLegend() throws MathException{
	try {
		java.awt.image.BufferedImage cmapImage = new java.awt.image.BufferedImage(200, particleVariableList.size()*30,java.awt.image.BufferedImage.TYPE_INT_RGB);
		Graphics g = cmapImage.getGraphics();
		for (int i = 0; i < particleVariableList.size(); i ++) {
			Color c = colors[i];
			System.out.println("color for legend: " + "red--"+ c.getRed() + "  green--" + c.getGreen() + "  blue--" + c.getBlue());
			String variableName = getVariableName(particleVariableList.get(i),null);
			g.setColor(c);
			g.drawString(variableName, 5, 30*i + 20);
			g.fillRect(105, 30*i + 10, 20, 10);
		}
		g.dispose();
		File tmpFile = File.createTempFile("legend", ".jpg");

		FileOutputStream fios = null;
		try {
			printWriter.println("# legend file: " + tmpFile.getAbsolutePath());
			fios = new FileOutputStream(tmpFile);
			ImageIO.write(cmapImage,"jpg",fios);
		}  finally {
			if(fios != null) {fios.close();}
		}
	} catch (Exception e) {
		e.printStackTrace();
		throw new MathException(e.getMessage());
	}
}*/
private void writeRuntimeCommands() throws SolverException, DivideByZeroException, DataAccessException, IOException, MathException, ExpressionException {
    printWriter.println("# " + SmoldynVCellMapper.SmoldynKeyword.killmolincmpt + " runtime command to kill molecules misplaced during initial condtions");
    for (ParticleVariable pv : particleVariableList) {
        CompartmentSubDomain varDomain = mathDesc.getCompartmentSubDomain(pv.getDomain().getName());
        if (varDomain == null) {
            continue;
        }
        boolean bkillMol = false;
        ArrayList<ParticleInitialCondition> iniConditionList = varDomain.getParticleProperties(pv).getParticleInitialConditions();
        for (ParticleInitialCondition iniCon : iniConditionList) {
            if (iniCon instanceof ParticleInitialConditionConcentration) {
                try {
                    subsituteFlattenToConstant(((ParticleInitialConditionConcentration) iniCon).getDistribution());
                } catch (// can not be evaluated to a constant
                Exception e) {
                    bkillMol = true;
                    break;
                }
            }
        }
        if (bkillMol) {
            Enumeration<SubDomain> subDomainEnumeration = mathDesc.getSubDomains();
            while (subDomainEnumeration.hasMoreElements()) {
                SubDomain subDomain = subDomainEnumeration.nextElement();
                if (subDomain instanceof CompartmentSubDomain && varDomain != subDomain) {
                    printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.B + " " + SmoldynVCellMapper.SmoldynKeyword.killmolincmpt + " " + pv.getName() + "(" + SmoldynVCellMapper.SmoldynKeyword.all + ") " + subDomain.getName());
                }
            }
        }
    }
    printWriter.println();
    // write command to kill molecules on membrane for adsortption to nothing
    printWriter.println("# kill membrane molecues that are absorbed (to nothing)");
    for (String killMolCmd : killMolCommands) {
        printWriter.println(killMolCmd);
    }
    printWriter.println();
    printWriter.println("# runtime command");
    printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.E + " " + VCellSmoldynKeyword.vcellPrintProgress);
    if (outputFile != null && cartesianMesh != null) {
        OutputTimeSpec ots = simulation.getSolverTaskDescription().getOutputTimeSpec();
        if (ots.isUniform()) {
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.output_files + " " + outputFile.getName());
            ISize sampleSize = simulation.getMeshSpecification().getSamplingSize();
            TimeStep timeStep = simulation.getSolverTaskDescription().getTimeStep();
            int n = (int) Math.round(((UniformOutputTimeSpec) ots).getOutputTimeStep() / timeStep.getDefaultTimeStep());
            if (simulation.getSolverTaskDescription().getSmoldynSimulationOptions().isSaveParticleLocations()) {
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + SmoldynVCellMapper.SmoldynKeyword.incrementfile + " " + outputFile.getName());
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + SmoldynVCellMapper.SmoldynKeyword.listmols + " " + outputFile.getName());
            }
            // DON'T CHANGE THE ORDER HERE.
            // DataProcess must be before vcellWriteOutput
            writeDataProcessor();
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " begin");
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.dimension + " " + dimension);
            printWriter.print(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.sampleSize + " " + sampleSize.getX());
            if (dimension > 1) {
                printWriter.print(" " + sampleSize.getY());
                if (dimension > 2) {
                    printWriter.print(" " + sampleSize.getZ());
                }
            }
            printWriter.println();
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.numMembraneElements + " " + cartesianMesh.getNumMembraneElements());
            for (ParticleVariable pv : particleVariableList) {
                String type = pv instanceof MembraneParticleVariable ? VCellSmoldynKeyword.membrane.name() : VCellSmoldynKeyword.volume.name();
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " " + VCellSmoldynKeyword.variable + " " + pv.getName() + " " + type + " " + pv.getDomain().getName());
            }
            printWriter.println(SmoldynVCellMapper.SmoldynKeyword.cmd + " " + SmoldynVCellMapper.SmoldynKeyword.N + " " + n + " " + VCellSmoldynKeyword.vcellWriteOutput + " end");
        } else {
            throw new SolverException(SolverDescription.Smoldyn.getDisplayLabel() + " only supports uniform output.");
        }
    }
    printWriter.println();
}
Also used : ParticleInitialConditionConcentration(cbit.vcell.math.ParticleProperties.ParticleInitialConditionConcentration) VolumeParticleVariable(cbit.vcell.math.VolumeParticleVariable) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) ParticleVariable(cbit.vcell.math.ParticleVariable) ISize(org.vcell.util.ISize) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) ImageException(cbit.image.ImageException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) SolverException(cbit.vcell.solver.SolverException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) TimeStep(cbit.vcell.solver.TimeStep) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) MembraneParticleVariable(cbit.vcell.math.MembraneParticleVariable) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) ParticleInitialCondition(cbit.vcell.math.ParticleProperties.ParticleInitialCondition) SolverException(cbit.vcell.solver.SolverException)

Example 32 with UniformOutputTimeSpec

use of cbit.vcell.solver.UniformOutputTimeSpec in project vcell by virtualcell.

the class RunRefSimulationFastOp method createRefSimBioModel.

private BioModel createRefSimBioModel(KeyValue simKey, User owner, Origin origin, Extent extent, ROI cellROI_2D, double timeStepVal, TimeBounds timeBounds, String varName, Expression initialConcentration, FieldFunctionArguments psfFFA, Expression chirpedDiffusionRate) throws Exception {
    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);
    geometry.getGeometrySpec().setOrigin(origin);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    String EXTRACELLULAR_NAME = "ec";
    String CYTOSOL_NAME = "cyt";
    String PLASMAMEMBRANE_NAME = "pm";
    ImageSubVolume subVolume0 = (ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0);
    ImageSubVolume subVolume1 = (ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1);
    if (subVolume0.getPixelValue() == EXTRACELLULAR_PIXVAL) {
        subVolume0.setName(EXTRACELLULAR_NAME);
        subVolume1.setName(CYTOSOL_NAME);
    } else {
        subVolume0.setName(CYTOSOL_NAME);
        subVolume1.setName(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);
    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));
    // Mobile Species
    Species diffusingSpecies = model.addSpecies(new Species("species", "Mobile bleachable species"));
    SpeciesContext diffusingSpeciesContext = model.addSpeciesContext(diffusingSpecies, cytosol);
    diffusingSpeciesContext.setName(varName);
    SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(diffusingSpeciesContext);
    scs.getInitialConditionParameter().setExpression(initialConcentration);
    chirpedDiffusionRate.bindExpression(scs);
    scs.getDiffusionParameter().setExpression(chirpedDiffusionRate);
    // simContext.getMicroscopeMeasurement().addFluorescentSpecies(speciesContexts[0]);
    // simContext.getMicroscopeMeasurement().setConvolutionKernel(new MicroscopeMeasurement.ProjectionZKernel());
    MathDescription mathDescription = simContext.createNewMathMapping().getMathDescription();
    // maybe there is a way that works for simContext.getMicroscopeMeasurement().... but this is needed now.
    mathDescription.addVariable(new Function(Simulation.PSF_FUNCTION_NAME, new Expression(psfFFA.infix()), null));
    simContext.setMathDescription(mathDescription);
    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) 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) 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) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ImageException(cbit.image.ImageException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) IOException(java.io.IOException) 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)

Example 33 with UniformOutputTimeSpec

use of cbit.vcell.solver.UniformOutputTimeSpec in project vcell by virtualcell.

the class RunRefSimulationOp method createRefSimBioModel.

private static BioModel createRefSimBioModel(KeyValue simKey, User owner, Origin origin, Extent extent, ROI cellROI_2D, double timeStepVal, TimeBounds timeBounds, String varName, Expression initialConcentration, double baseDiffusionRate) throws Exception {
    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);
    geometry.getGeometrySpec().setOrigin(origin);
    if (geometry.getGeometrySpec().getNumSubVolumes() != 2) {
        throw new Exception("Cell ROI has no ExtraCellular.");
    }
    String EXTRACELLULAR_NAME = "ec";
    String CYTOSOL_NAME = "cyt";
    String PLASMAMEMBRANE_NAME = "pm";
    ImageSubVolume subVolume0 = (ImageSubVolume) geometry.getGeometrySpec().getSubVolume(0);
    ImageSubVolume subVolume1 = (ImageSubVolume) geometry.getGeometrySpec().getSubVolume(1);
    if (subVolume0.getPixelValue() == EXTRACELLULAR_PIXVAL) {
        subVolume0.setName(EXTRACELLULAR_NAME);
        subVolume1.setName(CYTOSOL_NAME);
    } else {
        subVolume0.setName(CYTOSOL_NAME);
        subVolume1.setName(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);
    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));
    // Mobile Species
    Species diffusingSpecies = model.addSpecies(new Species("species", "Mobile bleachable species"));
    SpeciesContext diffusingSpeciesContext = model.addSpeciesContext(diffusingSpecies, cytosol);
    diffusingSpeciesContext.setName(varName);
    SpeciesContextSpec scs = simContext.getReactionContext().getSpeciesContextSpec(diffusingSpeciesContext);
    scs.getInitialConditionParameter().setExpression(initialConcentration);
    scs.getDiffusionParameter().setExpression(new Expression(baseDiffusionRate));
    // simContext.getMicroscopeMeasurement().addFluorescentSpecies(speciesContexts[0]);
    // simContext.getMicroscopeMeasurement().setConvolutionKernel(new MicroscopeMeasurement.ProjectionZKernel());
    simContext.setMathDescription(simContext.createNewMathMapping().getMathDescription());
    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) SurfaceClass(cbit.vcell.geometry.SurfaceClass) VCImage(cbit.image.VCImage) SpeciesContext(cbit.vcell.model.SpeciesContext) SpeciesContextSpec(cbit.vcell.mapping.SpeciesContextSpec) Feature(cbit.vcell.model.Feature) 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) VCImageUncompressed(cbit.image.VCImageUncompressed) SimulationContext(cbit.vcell.mapping.SimulationContext) ImageException(cbit.image.ImageException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) IOException(java.io.IOException) 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)

Example 34 with UniformOutputTimeSpec

use of cbit.vcell.solver.UniformOutputTimeSpec in project vcell by virtualcell.

the class Generate2DSimBioModelOp method generateBioModel.

public BioModel generateBioModel(Extent extent, ROI cellROI_2D, double[] timeStamps, Integer indexFirstPostbleach, double primaryDiffusionRate, double primaryFraction, double bleachMonitorRate, Double secondaryDiffusionRate, double secondaryFraction, Double bindingSiteConcentration, double bindingOnRate, double bindingOffRate, String extracellularName, String cytosolName, User owner, KeyValue simKey) throws PropertyVetoException, ExpressionException, ModelException, GeometryException, ImageException, MappingException, MathException, MatrixException {
    if (owner == null) {
        throw new IllegalArgumentException("Owner is not defined");
    }
    double df = primaryDiffusionRate;
    double ff = primaryFraction;
    double bwmRate = bleachMonitorRate;
    double dc = 0.0;
    double fc = 0.0;
    if (secondaryDiffusionRate != null) {
        dc = secondaryDiffusionRate;
        fc = secondaryFraction;
    }
    double bs = 0.0;
    double onRate = 0.0;
    double offRate = 0.0;
    if (bindingSiteConcentration != null) {
        bs = bindingSiteConcentration;
        onRate = bindingOnRate;
        offRate = bindingOffRate;
    }
    // immobile fraction
    double fimm = 1 - ff - fc;
    if (fimm < epsilon && fimm > (0 - epsilon)) {
        fimm = 0;
    }
    if (fimm < (1 + epsilon) && fimm > (1 - epsilon)) {
        fimm = 1;
    }
    int startingIndexForRecovery = indexFirstPostbleach;
    TimeBounds timeBounds = new TimeBounds(0.0, timeStamps[timeStamps.length - 1] - timeStamps[startingIndexForRecovery]);
    double timeStepVal = timeStamps[startingIndexForRecovery + 1] - timeStamps[startingIndexForRecovery];
    ROI cellROI = cellROI_2D;
    int numX = cellROI.getISize().getX();
    int numY = cellROI.getISize().getY();
    int numZ = cellROI.getISize().getZ();
    short[] shortPixels = cellROI.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 IllegalArgumentException("Cell ROI has no ExtraCellular.");
    }
    String EXTRACELLULAR_NAME = extracellularName;
    String CYTOSOL_NAME = cytosolName;
    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 = 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(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(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(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(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(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);
    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);
    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(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.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) 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) 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) BioModel(cbit.vcell.biomodel.BioModel) Model(cbit.vcell.model.Model) MathMapping(cbit.vcell.mapping.MathMapping) MassActionKinetics(cbit.vcell.model.MassActionKinetics)

Aggregations

UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)34 Simulation (cbit.vcell.solver.Simulation)18 OutputTimeSpec (cbit.vcell.solver.OutputTimeSpec)17 TimeBounds (cbit.vcell.solver.TimeBounds)15 DefaultOutputTimeSpec (cbit.vcell.solver.DefaultOutputTimeSpec)14 BioModel (cbit.vcell.biomodel.BioModel)13 SimulationContext (cbit.vcell.mapping.SimulationContext)13 SpeciesContextSpec (cbit.vcell.mapping.SpeciesContextSpec)10 MathDescription (cbit.vcell.math.MathDescription)10 KeyValue (org.vcell.util.document.KeyValue)10 Expression (cbit.vcell.parser.Expression)9 TimeStep (cbit.vcell.solver.TimeStep)9 IOException (java.io.IOException)9 ImageException (cbit.image.ImageException)8 Model (cbit.vcell.model.Model)8 SimulationVersion (org.vcell.util.document.SimulationVersion)8 Geometry (cbit.vcell.geometry.Geometry)7 MathMapping (cbit.vcell.mapping.MathMapping)7 ErrorTolerance (cbit.vcell.solver.ErrorTolerance)7 ExplicitOutputTimeSpec (cbit.vcell.solver.ExplicitOutputTimeSpec)7