Search in sources :

Example 11 with SolverTaskDescription

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

the class FiniteVolumeFileWriter method writeSimulationParamters.

/**
 * @param timeFunction
 * @param startTime
 * @param endTime
 * @param rootFinder
 * @param uniqueRootTimes
 * @param bPrintIterations
 * @throws ExpressionException
 *
 * for testing within scrapbook, see below:
 *
 * try {
 *	edu.northwestern.at.utils.math.rootfinders.MonadicFunctionRootFinder rootFinder =
 *//			new edu.northwestern.at.utils.math.rootfinders.Brent();
 *			new edu.northwestern.at.utils.math.rootfinders.Bisection();
 *//			new edu.northwestern.at.utils.math.rootfinders.NewtonRaphson();
 *//			new edu.northwestern.at.utils.math.rootfinders.Secant();
 *	cbit.vcell.parser.SimpleSymbolTable simpleSymbolTable = new cbit.vcell.parser.SimpleSymbolTable(new String[] { "t" });
 *
 *	cbit.vcell.parser.Expression exp = new cbit.vcell.parser.Expression("t-0.56");
 *
 *	exp.bindExpression(simpleSymbolTable);
 *	java.util.TreeSet<Double> rootTimes = new java.util.TreeSet<Double>();
 *	double startTime = 0.0;
 *	double endTime = 100.0;
 *	System.out.print("exp = '"+ exp.infix() + "'");
 *	long currentTimeMS = System.currentTimeMillis();
 *	cbit.vcell.solvers.FiniteVolumeFileWriter.findAllRoots(exp,startTime,endTime,rootFinder,rootTimes,false);
 *	long finalTimeMS = System.currentTimeMillis();
 *	for (double root : rootTimes){
 *		System.out.println("root = "+root);
 *	}
 *	System.out.println("elapsedTime of computation = "+(finalTimeMS-currentTimeMS)+" ms, found " + rootTimes.size() + " roots (not unique)");
 *
 *}catch (Exception e){
 *	e.printStackTrace(System.out);
 *}
 */
/*public static void findAllRoots(Expression timeFunction, double startTime, double endTime, MonadicFunctionRootFinder rootFinder, TreeSet<Double> uniqueRootTimes, boolean bPrintIterations) throws ExpressionException{
	TreeSet<Double> allRootTimes = new TreeSet<Double>();
	final Expression function_exp = new Expression(timeFunction);
	MonadicFunction valueFunction = new MonadicFunction() {
		double[] values = new double[1];
		public double f(double t) {
			values[0] = t;
			try {
				return function_exp.evaluateVector(values);
			} catch (ExpressionException e) {
				e.printStackTrace();
				throw new RuntimeException("expression exception "+e.getMessage());
			}
		}
	};
	
	final Expression derivative_exp = new Expression(timeFunction.differentiate(ReservedVariable.TIME.getName()));
	MonadicFunction derivativeFunction = new MonadicFunction() {
		double[] values = new double[1];
		public double f(double t) {
			values[0] = t;
			try {
				return derivative_exp.evaluateVector(values);
			} catch (ExpressionException e) {
				e.printStackTrace();
				throw new RuntimeException("expression exception "+e.getMessage());
			}
		}
	};
	
	RootFinderConvergenceTest convergenceTest = new StandardRootFinderConvergenceTest();
	RootFinderIterationInformation iterationInformation = null;
	if (bPrintIterations){
		iterationInformation = new RootFinderIterationInformation() {				
			public void iterationInformation(double x, double fx, double dfx, int currentIteration) {
				System.out.println(currentIteration+") x="+x+", fx="+fx+", dfx="+dfx);
			}
		};
	}
	int NUM_BRACKETS = 1000;
	double simulationTime = endTime - startTime;
	double tolerance = simulationTime/1e10;
	int maxIter = 1000;
	
	for (int i=0;i<NUM_BRACKETS-1;i++){
		double bracketMin = startTime + simulationTime*i/NUM_BRACKETS;
		double bracketMax = startTime + simulationTime*(i+1)/NUM_BRACKETS;
	
		double root = rootFinder.findRoot(bracketMin, bracketMax, tolerance, maxIter, valueFunction, derivativeFunction, convergenceTest, iterationInformation);
		if (root>startTime && root<endTime && valueFunction.f(root)<=tolerance){
			allRootTimes.add(root);
		}
	}
	double uniqueTolerance = tolerance * 100;
	double lastUniqueRoot = Double.NEGATIVE_INFINITY;
	for (double root : allRootTimes){
		if (root-lastUniqueRoot > uniqueTolerance){
			uniqueRootTimes.add(root);
		}
		lastUniqueRoot = root;
	}

}  ---------------------------------JIM's CODE COMMENTTED FOR FUTURE DEVELOPMENT*/
/**
 *# Simulation Parameters
 *SIMULATION_PARAM_BEGIN
 *SOLVER SUNDIALS_PDE_SOLVER 1.0E-7 1.0E-9
 *DISCONTINUITY_TIMES 2 1.0E-4 3.0000000000000003E-4
 *BASE_FILE_NAME c:/Vcell/users/fgao/SimID_31746636_0_
 *ENDING_TIME 4.0E-4
 *KEEP_EVERY ONE_STEP 3
 *KEEP_AT_MOST 1000
 *SIMULATION_PARAM_END
 * @throws MathException
 * @throws ExpressionException
 */
private void writeSimulationParamters() throws ExpressionException, MathException {
    Simulation simulation = simTask.getSimulation();
    SolverTaskDescription solverTaskDesc = simulation.getSolverTaskDescription();
    printWriter.println("# Simulation Parameters");
    printWriter.println(FVInputFileKeyword.SIMULATION_PARAM_BEGIN);
    if (solverTaskDesc.getSolverDescription().equals(SolverDescription.SundialsPDE)) {
        printWriter.print(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.SUNDIALS_PDE_SOLVER + " " + solverTaskDesc.getErrorTolerance().getRelativeErrorTolerance() + " " + solverTaskDesc.getErrorTolerance().getAbsoluteErrorTolerance() + " " + solverTaskDesc.getTimeStep().getMaximumTimeStep());
        if (simulation.getMathDescription().hasVelocity()) {
            printWriter.print(" " + solverTaskDesc.getSundialsPdeSolverOptions().getMaxOrderAdvection());
        }
        printWriter.println();
        Vector<Discontinuity> discontinuities = new Vector<Discontinuity>();
        TreeSet<Double> discontinuityTimes = new TreeSet<Double>();
        MathDescription mathDesc = simulation.getMathDescription();
        Enumeration<SubDomain> enum1 = mathDesc.getSubDomains();
        while (enum1.hasMoreElements()) {
            SubDomain sd = enum1.nextElement();
            Enumeration<Equation> enum_equ = sd.getEquations();
            while (enum_equ.hasMoreElements()) {
                Equation equation = enum_equ.nextElement();
                equation.getDiscontinuities(simTask.getSimulationJob().getSimulationSymbolTable(), discontinuities);
            }
        }
        getDiscontinuityTimes(discontinuities, discontinuityTimes);
        if (discontinuityTimes.size() > 0) {
            printWriter.print(FVInputFileKeyword.DISCONTINUITY_TIMES + " " + discontinuityTimes.size());
            for (double d : discontinuityTimes) {
                printWriter.print(" " + d);
            }
            printWriter.println();
        }
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.Chombo)) {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.CHOMBO_SEMIIMPLICIT_SOLVER);
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.VCellPetsc)) {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.VCELL_PETSC_SOLVER);
    } else {
        printWriter.println(FVInputFileKeyword.SOLVER + " " + FVInputFileKeyword.FV_SOLVER + " " + solverTaskDesc.getErrorTolerance().getRelativeErrorTolerance());
    }
    printWriter.println(FVInputFileKeyword.BASE_FILE_NAME + " " + new File(workingDirectory, simTask.getSimulationJob().getSimulationJobID()).getAbsolutePath());
    if (solverTaskDesc.isParallel() && destinationDirectory != null && !destinationDirectory.equals(workingDirectory)) {
        printWriter.println(FVInputFileKeyword.PRIMARY_DATA_DIR + " " + destinationDirectory.getAbsolutePath());
    }
    printWriter.println(FVInputFileKeyword.ENDING_TIME + " " + solverTaskDesc.getTimeBounds().getEndingTime());
    OutputTimeSpec outputTimeSpec = solverTaskDesc.getOutputTimeSpec();
    if (solverTaskDesc.getSolverDescription().isChomboSolver()) {
        List<TimeInterval> timeIntervalList = solverTaskDesc.getChomboSolverSpec().getTimeIntervalList();
        printWriter.println(FVInputFileKeyword.TIME_INTERVALS + " " + timeIntervalList.size());
        for (TimeInterval ti : timeIntervalList) {
            printWriter.println(ti.getEndingTime() + " " + ti.getTimeStep() + " " + ti.getKeepEvery());
        }
    } else if (solverTaskDesc.getSolverDescription().equals(SolverDescription.SundialsPDE)) {
        if (outputTimeSpec.isDefault()) {
            DefaultOutputTimeSpec defaultOutputTimeSpec = (DefaultOutputTimeSpec) outputTimeSpec;
            printWriter.println(FVInputFileKeyword.KEEP_EVERY + " " + FVInputFileKeyword.ONE_STEP + " " + defaultOutputTimeSpec.getKeepEvery());
            printWriter.println(FVInputFileKeyword.KEEP_AT_MOST + " " + defaultOutputTimeSpec.getKeepAtMost());
        } else {
            printWriter.println(FVInputFileKeyword.TIME_STEP + " " + ((UniformOutputTimeSpec) outputTimeSpec).getOutputTimeStep());
            printWriter.println(FVInputFileKeyword.KEEP_EVERY + " 1");
        }
    } else {
        double defaultTimeStep = solverTaskDesc.getTimeStep().getDefaultTimeStep();
        printWriter.println(FVInputFileKeyword.TIME_STEP + " " + defaultTimeStep);
        int keepEvery = 1;
        if (outputTimeSpec.isDefault()) {
            keepEvery = ((DefaultOutputTimeSpec) outputTimeSpec).getKeepEvery();
        } else if (outputTimeSpec.isUniform()) {
            UniformOutputTimeSpec uots = (UniformOutputTimeSpec) outputTimeSpec;
            double ots = uots.getOutputTimeStep();
            keepEvery = (int) Math.round(ots / defaultTimeStep);
        } else {
            throw new RuntimeException("unexpected OutputTime specification type :" + outputTimeSpec.getClass().getName());
        }
        if (keepEvery <= 0) {
            throw new RuntimeException("Output KeepEvery must be a positive integer. Try to change the output option.");
        }
        printWriter.println(FVInputFileKeyword.KEEP_EVERY + " " + keepEvery);
    }
    ErrorTolerance stopAtSpatiallyUniformErrorTolerance = solverTaskDesc.getStopAtSpatiallyUniformErrorTolerance();
    if (stopAtSpatiallyUniformErrorTolerance != null) {
        printWriter.println(FVInputFileKeyword.CHECK_SPATIALLY_UNIFORM + " " + stopAtSpatiallyUniformErrorTolerance.getAbsoluteErrorTolerance() + " " + stopAtSpatiallyUniformErrorTolerance.getRelativeErrorTolerance());
    }
    printWriter.println(FVInputFileKeyword.SIMULATION_PARAM_END);
    printWriter.println();
}
Also used : Discontinuity(cbit.vcell.parser.Discontinuity) TimeInterval(org.vcell.chombo.TimeInterval) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) MathDescription(cbit.vcell.math.MathDescription) MeasureEquation(cbit.vcell.math.MeasureEquation) PdeEquation(cbit.vcell.math.PdeEquation) VolumeRegionEquation(cbit.vcell.math.VolumeRegionEquation) MembraneRegionEquation(cbit.vcell.math.MembraneRegionEquation) Equation(cbit.vcell.math.Equation) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) Simulation(cbit.vcell.solver.Simulation) TreeSet(java.util.TreeSet) ErrorTolerance(cbit.vcell.solver.ErrorTolerance) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) Vector(java.util.Vector) File(java.io.File) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec)

Example 12 with SolverTaskDescription

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

the class FiniteVolumeFileWriter method writeChomboSpec.

private void writeChomboSpec() throws ExpressionException, SolverException, PropertyVetoException, ClassNotFoundException, IOException, GeometryException, ImageException {
    if (!bChomboSolver) {
        return;
    }
    GeometrySpec geometrySpec = resampledGeometry.getGeometrySpec();
    int dimension = geometrySpec.getDimension();
    if (dimension == 1) {
        throw new SolverException(simTask.getSimulation().getSolverTaskDescription().getSolverDescription().getDisplayLabel() + " is only supported for simulations with 2D or 3D geometry.");
    }
    Simulation simulation = getSimulationTask().getSimulation();
    SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    ChomboSolverSpec chomboSolverSpec = solverTaskDescription.getChomboSolverSpec();
    printWriter.println(FVInputFileKeyword.CHOMBO_SPEC_BEGIN);
    printWriter.println(FVInputFileKeyword.DIMENSION + " " + geometrySpec.getDimension());
    Extent extent = geometrySpec.getExtent();
    Origin origin = geometrySpec.getOrigin();
    ISize isize = simulation.getMeshSpecification().getSamplingSize();
    switch(geometrySpec.getDimension()) {
        case 2:
            printWriter.println(FVInputFileKeyword.MESH_SIZE + " " + isize.getX() + " " + isize.getY());
            printWriter.println(FVInputFileKeyword.DOMAIN_SIZE + " " + extent.getX() + " " + extent.getY());
            printWriter.println(FVInputFileKeyword.DOMAIN_ORIGIN + " " + origin.getX() + " " + origin.getY());
            break;
        case 3:
            printWriter.println(FVInputFileKeyword.MESH_SIZE + " " + isize.getX() + " " + isize.getY() + " " + isize.getZ());
            printWriter.println(FVInputFileKeyword.DOMAIN_SIZE + " " + extent.getX() + " " + extent.getY() + " " + extent.getZ());
            printWriter.println(FVInputFileKeyword.DOMAIN_ORIGIN + " " + origin.getX() + " " + origin.getY() + " " + origin.getZ());
            break;
    }
    List<CompartmentSubDomain> featureList = new ArrayList<CompartmentSubDomain>();
    Enumeration<SubDomain> enum1 = simulation.getMathDescription().getSubDomains();
    while (enum1.hasMoreElements()) {
        SubDomain sd = enum1.nextElement();
        if (sd instanceof CompartmentSubDomain) {
            featureList.add((CompartmentSubDomain) sd);
        }
    }
    int numFeatures = featureList.size();
    CompartmentSubDomain[] features = featureList.toArray(new CompartmentSubDomain[0]);
    int[] phases = new int[numFeatures];
    Arrays.fill(phases, -1);
    phases[numFeatures - 1] = 0;
    int[] numAssigned = new int[] { 1 };
    assignPhases(features, numFeatures - 1, phases, numAssigned);
    Map<String, Integer> subDomainPhaseMap = new HashMap<String, Integer>();
    for (int i = 0; i < phases.length; ++i) {
        if (phases[i] == -1) {
            throw new SolverException("Failed to assign a phase to CompartmentSubdomain '" + features[i].getName() + "'. It might be caused by too coarsh a mesh.");
        }
        subDomainPhaseMap.put(features[i].getName(), phases[i]);
    }
    SubVolume[] subVolumes = geometrySpec.getSubVolumes();
    if (geometrySpec.hasImage()) {
        Geometry geometry = (Geometry) BeanUtils.cloneSerializable(simulation.getMathDescription().getGeometry());
        Geometry simGeometry = geometry;
        VCImage img = geometry.getGeometrySpec().getImage();
        int factor = Math.max(Math.max(img.getNumX(), img.getNumY()), img.getNumZ()) < 512 ? 2 : 1;
        ISize distanceMapMeshSize = new ISize(img.getNumX() * factor, img.getNumY() * factor, img.getNumZ() * factor);
        Vect3d deltaX = null;
        boolean bCellCentered = false;
        double dx = 0.5;
        double dy = 0.5;
        double dz = 0.5;
        int Nx = distanceMapMeshSize.getX();
        int Ny = distanceMapMeshSize.getY();
        int Nz = distanceMapMeshSize.getZ();
        if (dimension == 2) {
            // pad the 2D image with itself in order to obtain a 3D image used to compute the distance map
            // because the distance map algorithm is 3D only (using distance to triangles)
            byte[] oldPixels = img.getPixels();
            byte[] newPixels = new byte[oldPixels.length * 3];
            System.arraycopy(oldPixels, 0, newPixels, 0, oldPixels.length);
            System.arraycopy(oldPixels, 0, newPixels, oldPixels.length, oldPixels.length);
            System.arraycopy(oldPixels, 0, newPixels, oldPixels.length * 2, oldPixels.length);
            double distX = geometry.getExtent().getX() / img.getNumX();
            double distY = geometry.getExtent().getY() / img.getNumY();
            // we set the distance on the z axis to something that makes sense
            double distZ = Math.max(distX, distY);
            Extent newExtent = new Extent(geometry.getExtent().getX(), geometry.getExtent().getY(), distZ * 3);
            VCImage newImage = new VCImageUncompressed(null, newPixels, newExtent, img.getNumX(), img.getNumY(), 3);
            // copy the pixel classes too
            ArrayList<VCPixelClass> newPixelClasses = new ArrayList<VCPixelClass>();
            for (VCPixelClass origPixelClass : geometry.getGeometrySpec().getImage().getPixelClasses()) {
                SubVolume origSubvolume = geometry.getGeometrySpec().getImageSubVolumeFromPixelValue(origPixelClass.getPixel());
                newPixelClasses.add(new VCPixelClass(null, origSubvolume.getName(), origPixelClass.getPixel()));
            }
            newImage.setPixelClasses(newPixelClasses.toArray(new VCPixelClass[newPixelClasses.size()]));
            simGeometry = new Geometry(geometry, newImage);
            Nz = 3;
        }
        GeometrySpec simGeometrySpec = simGeometry.getGeometrySpec();
        Extent simExtent = simGeometrySpec.getExtent();
        dx = simExtent.getX() / (Nx - 1);
        dy = simExtent.getY() / (Ny - 1);
        dz = simExtent.getZ() / (Nz - 1);
        if (Math.abs(dx - dy) > 0.1 * Math.max(dx, dy)) {
            dx = Math.min(dx, dy);
            dy = dx;
            Nx = (int) (simExtent.getX() / dx + 1);
            Ny = (int) (simExtent.getY() / dx + 1);
            if (dimension == 3) {
                dz = dx;
                Nz = (int) (simExtent.getZ() / dx + 1);
            }
        }
        deltaX = new Vect3d(dx, dy, dz);
        // one more point in each direction
        distanceMapMeshSize = new ISize(Nx + 1, Ny + 1, Nz + 1);
        Extent distanceMapExtent = new Extent(simExtent.getX() + dx, simExtent.getY() + dy, simExtent.getZ() + dz);
        simGeometrySpec.setExtent(distanceMapExtent);
        GeometrySurfaceDescription geoSurfaceDesc = simGeometry.getGeometrySurfaceDescription();
        geoSurfaceDesc.setVolumeSampleSize(distanceMapMeshSize);
        geoSurfaceDesc.updateAll();
        VCImage vcImage = RayCaster.sampleGeometry(simGeometry, distanceMapMeshSize, bCellCentered);
        SubvolumeSignedDistanceMap[] distanceMaps = DistanceMapGenerator.computeDistanceMaps(simGeometry, vcImage, bCellCentered);
        if (dimension == 2) {
            distanceMaps = DistanceMapGenerator.extractMiddleSlice(distanceMaps);
        }
        printWriter.println(FVInputFileKeyword.SUBDOMAINS + " " + simGeometrySpec.getNumSubVolumes() + " " + FVInputFileKeyword.DISTANCE_MAP);
        for (int i = 0; i < subVolumes.length; i++) {
            File distanceMapFile = new File(workingDirectory, getSimulationTask().getSimulationJobID() + "_" + subVolumes[i].getName() + DISTANCE_MAP_FILE_EXTENSION);
            writeDistanceMapFile(deltaX, distanceMaps[i], distanceMapFile);
            int phase = subDomainPhaseMap.get(subVolumes[i].getName());
            printWriter.println(subVolumes[i].getName() + " " + phase + " " + distanceMapFile.getAbsolutePath());
        }
    } else {
        printWriter.println(FVInputFileKeyword.SUBDOMAINS + " " + geometrySpec.getNumSubVolumes());
        Expression[] rvachevExps = convertAnalyticGeometryToRvachevFunction(geometrySpec);
        for (int i = 0; i < subVolumes.length; i++) {
            if (subVolumes[i] instanceof AnalyticSubVolume) {
                String name = subVolumes[i].getName();
                int phase = subDomainPhaseMap.get(name);
                printWriter.println(name + " " + phase + " ");
                printWriter.println(FVInputFileKeyword.IF + " " + rvachevExps[i].infix() + ";");
                printWriter.println(FVInputFileKeyword.USER + " " + ((AnalyticSubVolume) subVolumes[i]).getExpression().infix() + ";");
            }
        }
    }
    printWriter.println(FVInputFileKeyword.MAX_BOX_SIZE + " " + chomboSolverSpec.getMaxBoxSize());
    printWriter.println(FVInputFileKeyword.FILL_RATIO + " " + chomboSolverSpec.getFillRatio());
    printWriter.println(FVInputFileKeyword.RELATIVE_TOLERANCE + " " + simulation.getSolverTaskDescription().getErrorTolerance().getRelativeErrorTolerance());
    printWriter.println(FVInputFileKeyword.SAVE_VCELL_OUTPUT + " " + chomboSolverSpec.isSaveVCellOutput());
    printWriter.println(FVInputFileKeyword.SAVE_CHOMBO_OUTPUT + " " + chomboSolverSpec.isSaveChomboOutput());
    printWriter.println(FVInputFileKeyword.ACTIVATE_FEATURE_UNDER_DEVELOPMENT + " " + chomboSolverSpec.isActivateFeatureUnderDevelopment());
    printWriter.println(FVInputFileKeyword.SMALL_VOLFRAC_THRESHOLD + " " + chomboSolverSpec.getSmallVolfracThreshold());
    printWriter.println(FVInputFileKeyword.BLOCK_FACTOR + " " + chomboSolverSpec.getBlockFactor());
    printWriter.println(FVInputFileKeyword.TAGS_GROW + " " + chomboSolverSpec.getTagsGrow());
    // Refinement
    int numLevels = chomboSolverSpec.getNumRefinementLevels();
    // Refinements #Levels ratio 1, ratio 2, etc
    printWriter.print(FVInputFileKeyword.REFINEMENTS + " " + (numLevels + 1));
    List<Integer> ratios = chomboSolverSpec.getRefineRatioList();
    for (int i : ratios) {
        printWriter.print(" " + i);
    }
    // write last refinement ratio, fake
    printWriter.println(" 2");
    // membrane rois
    List<RefinementRoi> memRios = chomboSolverSpec.getMembraneRefinementRois();
    printWriter.println(FVInputFileKeyword.REFINEMENT_ROIS + " " + RoiType.Membrane + " " + memRios.size());
    for (RefinementRoi roi : memRios) {
        if (roi.getRoiExpression() == null) {
            throw new SolverException("ROI expression cannot be null");
        }
        // level tagsGrow ROIexpression
        printWriter.println(roi.getLevel() + " " + roi.getRoiExpression().infix() + ";");
    }
    List<RefinementRoi> volRios = chomboSolverSpec.getVolumeRefinementRois();
    printWriter.println(FVInputFileKeyword.REFINEMENT_ROIS + " " + RoiType.Volume + " " + volRios.size());
    for (RefinementRoi roi : volRios) {
        if (roi.getRoiExpression() == null) {
            throw new SolverException("ROI expression cannot be null");
        }
        printWriter.println(roi.getLevel() + " " + roi.getRoiExpression().infix() + ";");
    }
    printWriter.println(FVInputFileKeyword.VIEW_LEVEL + " " + chomboSolverSpec.getViewLevel());
    printWriter.println(FVInputFileKeyword.CHOMBO_SPEC_END);
    printWriter.println();
}
Also used : Origin(org.vcell.util.Origin) VCPixelClass(cbit.image.VCPixelClass) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) HashMap(java.util.HashMap) ISize(org.vcell.util.ISize) ArrayList(java.util.ArrayList) VCImage(cbit.image.VCImage) SubvolumeSignedDistanceMap(cbit.vcell.geometry.surface.SubvolumeSignedDistanceMap) GeometrySpec(cbit.vcell.geometry.GeometrySpec) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) RefinementRoi(org.vcell.chombo.RefinementRoi) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) VCImageUncompressed(cbit.image.VCImageUncompressed) ChomboSolverSpec(org.vcell.chombo.ChomboSolverSpec) Vect3d(cbit.vcell.render.Vect3d) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SolverException(cbit.vcell.solver.SolverException) File(java.io.File) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume)

Example 13 with SolverTaskDescription

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

the class ITextWriter method writeSimulation.

// container can be a chapter or a section of a chapter.
protected void writeSimulation(Section container, Simulation sim) throws DocumentException {
    if (sim == null) {
        return;
    }
    Section simSection = container.addSection(sim.getName(), container.numberDepth() + 1);
    writeMetadata(simSection, sim.getName(), sim.getDescription(), null, "Simulation ");
    // add overriden params
    Table overParamTable = null;
    MathOverrides mo = sim.getMathOverrides();
    if (mo != null) {
        String[] constants = mo.getOverridenConstantNames();
        for (int i = 0; i < constants.length; i++) {
            String actualStr = "", defStr = "";
            Expression tempExp = mo.getDefaultExpression(constants[i]);
            if (tempExp != null) {
                defStr = tempExp.infix();
            }
            if (mo.isScan(constants[i])) {
                actualStr = mo.getConstantArraySpec(constants[i]).toString();
            } else {
                tempExp = mo.getActualExpression(constants[i], 0);
                if (tempExp != null) {
                    actualStr = tempExp.infix();
                }
            }
            if (overParamTable == null) {
                overParamTable = getTable(3, 75, 1, 3, 3);
                overParamTable.setAlignment(Table.ALIGN_LEFT);
                overParamTable.addCell(createCell("Overriden Parameters", getBold(DEF_HEADER_FONT_SIZE), 3, 1, Element.ALIGN_CENTER, true));
                overParamTable.addCell(createHeaderCell("Name", getBold(), 1));
                overParamTable.addCell(createHeaderCell("Actual Value", getBold(), 1));
                overParamTable.addCell(createHeaderCell("Default Value", getBold(), 1));
            }
            overParamTable.addCell(createCell(constants[i], getFont()));
            overParamTable.addCell(createCell(actualStr, getFont()));
            overParamTable.addCell(createCell(defStr, getFont()));
        }
    }
    if (overParamTable != null) {
        simSection.add(overParamTable);
    }
    // add spatial details
    // sim.isSpatial();
    Table meshTable = null;
    MeshSpecification mesh = sim.getMeshSpecification();
    if (mesh != null) {
        Geometry geom = mesh.getGeometry();
        Extent extent = geom.getExtent();
        String extentStr = "(" + extent.getX() + ", " + extent.getY() + ", " + extent.getZ() + ")";
        ISize meshSize = mesh.getSamplingSize();
        String meshSizeStr = "(" + meshSize.getX() + ", " + meshSize.getY() + ", " + meshSize.getZ() + ")";
        meshTable = getTable(2, 75, 1, 3, 3);
        meshTable.setAlignment(Table.ALIGN_LEFT);
        meshTable.addCell(createCell("Geometry Setting", getBold(DEF_HEADER_FONT_SIZE), 2, 1, Element.ALIGN_CENTER, true));
        meshTable.addCell(createCell("Geometry Size (um)", getFont()));
        meshTable.addCell(createCell(extentStr, getFont()));
        meshTable.addCell(createCell("Mesh Size (elements)", getFont()));
        meshTable.addCell(createCell(meshSizeStr, getFont()));
    }
    if (meshTable != null) {
        simSection.add(meshTable);
    }
    // write advanced sim settings
    Table simAdvTable = null;
    SolverTaskDescription solverDesc = sim.getSolverTaskDescription();
    if (solverDesc != null) {
        String solverName = solverDesc.getSolverDescription().getDisplayLabel();
        simAdvTable = getTable(2, 75, 1, 3, 3);
        simAdvTable.setAlignment(Table.ALIGN_LEFT);
        simAdvTable.addCell(createCell("Advanced Settings", getBold(DEF_HEADER_FONT_SIZE), 2, 1, Element.ALIGN_CENTER, true));
        simAdvTable.addCell(createCell("Solver Name", getFont()));
        simAdvTable.addCell(createCell(solverName, getFont()));
        simAdvTable.addCell(createCell("Time Bounds - Starting", getFont()));
        simAdvTable.addCell(createCell("" + solverDesc.getTimeBounds().getStartingTime(), getFont()));
        simAdvTable.addCell(createCell("Time Bounds - Ending", getFont()));
        simAdvTable.addCell(createCell("" + solverDesc.getTimeBounds().getEndingTime(), getFont()));
        simAdvTable.addCell(createCell("Time Step - Min", getFont()));
        simAdvTable.addCell(createCell("" + solverDesc.getTimeStep().getMinimumTimeStep(), getFont()));
        simAdvTable.addCell(createCell("Time Step - Default", getFont()));
        simAdvTable.addCell(createCell("" + solverDesc.getTimeStep().getDefaultTimeStep(), getFont()));
        simAdvTable.addCell(createCell("Time Step - Max", getFont()));
        simAdvTable.addCell(createCell("" + solverDesc.getTimeStep().getMaximumTimeStep(), getFont()));
        ErrorTolerance et = solverDesc.getErrorTolerance();
        if (et != null) {
            simAdvTable.addCell(createCell("Error Tolerance - Absolute", getFont()));
            simAdvTable.addCell(createCell("" + et.getAbsoluteErrorTolerance(), getFont()));
            simAdvTable.addCell(createCell("Error Tolerance - Relative", getFont()));
            simAdvTable.addCell(createCell("" + et.getRelativeErrorTolerance(), getFont()));
        }
        OutputTimeSpec ots = solverDesc.getOutputTimeSpec();
        if (ots.isDefault()) {
            simAdvTable.addCell(createCell("Keep Every", getFont()));
            simAdvTable.addCell(createCell("" + ((DefaultOutputTimeSpec) ots).getKeepEvery(), getFont()));
            simAdvTable.addCell(createCell("Keep At Most", getFont()));
            simAdvTable.addCell(createCell("" + ((DefaultOutputTimeSpec) ots).getKeepAtMost(), getFont()));
        } else if (ots.isUniform()) {
            simAdvTable.addCell(createCell("Output Time Step", getFont()));
            simAdvTable.addCell(createCell("" + ((UniformOutputTimeSpec) ots).getOutputTimeStep(), getFont()));
        } else if (ots.isExplicit()) {
            simAdvTable.addCell(createCell("Output Time Points", getFont()));
            simAdvTable.addCell(createCell("" + ((ExplicitOutputTimeSpec) ots).toCommaSeperatedOneLineOfString(), getFont()));
        }
        simAdvTable.addCell(createCell("Use Symbolic Jacobian (T/F)", getFont()));
        simAdvTable.addCell(createCell((solverDesc.getUseSymbolicJacobian() ? " T " : " F "), getFont()));
        Constant sp = solverDesc.getSensitivityParameter();
        if (sp != null) {
            simAdvTable.addCell(createCell("Sensitivity Analysis Param", getFont()));
            simAdvTable.addCell(createCell(sp.getName(), getFont()));
        }
    }
    if (simAdvTable != null) {
        simSection.add(simAdvTable);
    }
}
Also used : Table(com.lowagie.text.Table) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) Constant(cbit.vcell.math.Constant) Section(com.lowagie.text.Section) MeshSpecification(cbit.vcell.solver.MeshSpecification) Geometry(cbit.vcell.geometry.Geometry) MathOverrides(cbit.vcell.solver.MathOverrides) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) ExplicitOutputTimeSpec(cbit.vcell.solver.ExplicitOutputTimeSpec) OutputTimeSpec(cbit.vcell.solver.OutputTimeSpec) UniformOutputTimeSpec(cbit.vcell.solver.UniformOutputTimeSpec) Expression(cbit.vcell.parser.Expression) ErrorTolerance(cbit.vcell.solver.ErrorTolerance) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription)

Example 14 with SolverTaskDescription

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

the class AdamsMoultonFiveSolver method integrate.

/**
 * This method was created by a SmartGuide.
 *  THIS HAS NOT BEEN UPDATED LIKE ODEIntegrator.integrate () and
 *  RungeKuttaFehlbergIntegrator.integrate()...
 */
protected void integrate() throws SolverException, UserStopException, IOException {
    try {
        SolverTaskDescription taskDescription = simTask.getSimulation().getSolverTaskDescription();
        double timeStep = taskDescription.getTimeStep().getDefaultTimeStep();
        fieldCurrentTime = taskDescription.getTimeBounds().getStartingTime();
        // before computation begins, settle fast equilibrium
        if (getFastAlgebraicSystem() != null) {
            fieldValueVectors.copyValues(0, 1);
            getFastAlgebraicSystem().initVars(getValueVector(0), getValueVector(1));
            getFastAlgebraicSystem().solveSystem(getValueVector(0), getValueVector(1));
            fieldValueVectors.copyValues(1, 0);
        }
        // check for failure
        check(getValueVector(0));
        // Evaluate
        for (int i = 0; i < getStateVariableCount(); i++) {
            f[0][getVariableIndex(i)] = evaluate(getValueVector(0), i);
        }
        // check for failure
        check(getValueVector(0));
        updateResultSet();
        // 
        int iteration = 0;
        while (fieldCurrentTime < taskDescription.getTimeBounds().getEndingTime()) {
            checkForUserStop();
            if (iteration < 3) {
                // Take Runge-Kutta step...
                prep(fieldCurrentTime, timeStep);
            } else {
                // Take Adams-Moulton step...
                step(fieldCurrentTime, timeStep);
            }
            // update (old = new)
            fieldValueVectors.copyValuesDown();
            // compute fast system
            if (getFastAlgebraicSystem() != null) {
                fieldValueVectors.copyValues(0, 1);
                getFastAlgebraicSystem().initVars(getValueVector(0), getValueVector(1));
                getFastAlgebraicSystem().solveSystem(getValueVector(0), getValueVector(1));
                fieldValueVectors.copyValues(1, 0);
            }
            // check for failure
            check(getValueVector(0));
            if (iteration < 3) {
                for (int i = 0; i < getStateVariableCount(); i++) {
                    f[iteration + 1][getVariableIndex(i)] = evaluate(getValueVector(0), i);
                }
                // check for failure
                check(f[iteration + 1]);
            } else {
                // Evaluate
                for (int i = 0; i < getStateVariableCount(); i++) {
                    f[4][getVariableIndex(i)] = evaluate(getValueVector(0), i);
                }
                // check for failure
                check(f[4]);
                shiftWorkArrays();
            }
            // fieldCurrentTime += timeStep;
            iteration++;
            fieldCurrentTime = taskDescription.getTimeBounds().getStartingTime() + iteration * timeStep;
            // store results if it coincides with a save interval
            if (taskDescription.getOutputTimeSpec().isDefault()) {
                int keepEvery = ((DefaultOutputTimeSpec) taskDescription.getOutputTimeSpec()).getKeepEvery();
                if ((iteration % keepEvery) == 0)
                    updateResultSet();
            }
        }
        // store last time point
        if (taskDescription.getOutputTimeSpec().isDefault()) {
            int keepEvery = ((DefaultOutputTimeSpec) taskDescription.getOutputTimeSpec()).getKeepEvery();
            if ((iteration % keepEvery) == 0)
                updateResultSet();
        }
    } catch (ExpressionException expressionException) {
        throw new SolverException(expressionException.getMessage());
    } catch (MathException mathException) {
        throw new SolverException(mathException.getMessage());
    }
}
Also used : MathException(cbit.vcell.math.MathException) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) SolverException(cbit.vcell.solver.SolverException) DefaultOutputTimeSpec(cbit.vcell.solver.DefaultOutputTimeSpec) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 15 with SolverTaskDescription

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

the class OdeFileWriter method createStateVariables.

private void createStateVariables() throws Exception {
    Simulation simulation = simTask.getSimulation();
    MathDescription mathDescription = simulation.getMathDescription();
    SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    // get Ode's from MathDescription and create ODEStateVariables
    Enumeration<Equation> enum1 = mathDescription.getSubDomains().nextElement().getEquations();
    SimulationSymbolTable simSymbolTable = simTask.getSimulationJob().getSimulationSymbolTable();
    while (enum1.hasMoreElements()) {
        Equation equation = enum1.nextElement();
        if (equation instanceof OdeEquation) {
            fieldStateVariables.addElement(new ODEStateVariable((OdeEquation) equation, simSymbolTable));
        } else {
            throw new MathException("encountered non-ode equation, unsupported");
        }
    }
    // Get sensitivity variables
    Variable[] variables = simSymbolTable.getVariables();
    Vector<SensVariable> sensVariables = new Vector<SensVariable>();
    Constant sensitivityParameter = solverTaskDescription.getSensitivityParameter();
    if (sensitivityParameter != null) {
        Constant origSensParam = sensitivityParameter;
        Constant overriddenSensParam = (Constant) simSymbolTable.getVariable(origSensParam.getName());
        for (int i = 0; i < variables.length; i++) {
            if (variables[i] instanceof VolVariable) {
                VolVariable volVariable = (VolVariable) variables[i];
                SensVariable sv = new SensVariable(volVariable, overriddenSensParam);
                sensVariables.addElement(sv);
            }
        }
    }
    if (rateSensitivity == null) {
        rateSensitivity = new RateSensitivity(mathDescription, mathDescription.getSubDomains().nextElement());
    }
    if (jacobian == null) {
        jacobian = new Jacobian(mathDescription, mathDescription.getSubDomains().nextElement());
    }
    // get Jacobian and RateSensitivities from MathDescription and create SensStateVariables
    for (int v = 0; v < sensVariables.size(); v++) {
        fieldStateVariables.addElement(new SensStateVariable(sensVariables.elementAt(v), rateSensitivity, jacobian, sensVariables, simSymbolTable));
    }
}
Also used : ReservedVariable(cbit.vcell.math.ReservedVariable) ParameterVariable(cbit.vcell.math.ParameterVariable) Variable(cbit.vcell.math.Variable) VolVariable(cbit.vcell.math.VolVariable) MathDescription(cbit.vcell.math.MathDescription) VolVariable(cbit.vcell.math.VolVariable) Constant(cbit.vcell.math.Constant) SimulationSymbolTable(cbit.vcell.solver.SimulationSymbolTable) OdeEquation(cbit.vcell.math.OdeEquation) Equation(cbit.vcell.math.Equation) Simulation(cbit.vcell.solver.Simulation) OdeEquation(cbit.vcell.math.OdeEquation) MathException(cbit.vcell.math.MathException) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) Vector(java.util.Vector)

Aggregations

SolverTaskDescription (cbit.vcell.solver.SolverTaskDescription)39 DefaultOutputTimeSpec (cbit.vcell.solver.DefaultOutputTimeSpec)13 Simulation (cbit.vcell.solver.Simulation)12 UniformOutputTimeSpec (cbit.vcell.solver.UniformOutputTimeSpec)10 ExpressionException (cbit.vcell.parser.ExpressionException)7 OutputTimeSpec (cbit.vcell.solver.OutputTimeSpec)7 SolverDescription (cbit.vcell.solver.SolverDescription)7 TimeBounds (cbit.vcell.solver.TimeBounds)7 ArrayList (java.util.ArrayList)6 MathException (cbit.vcell.math.MathException)5 ExplicitOutputTimeSpec (cbit.vcell.solver.ExplicitOutputTimeSpec)5 Constant (cbit.vcell.math.Constant)4 SubDomain (cbit.vcell.math.SubDomain)4 Expression (cbit.vcell.parser.Expression)4 NonspatialStochSimOptions (cbit.vcell.solver.NonspatialStochSimOptions)4 SimulationSymbolTable (cbit.vcell.solver.SimulationSymbolTable)4 SolverException (cbit.vcell.solver.SolverException)4 IOException (java.io.IOException)4 BioModel (cbit.vcell.biomodel.BioModel)3 Geometry (cbit.vcell.geometry.Geometry)3