Search in sources :

Example 21 with MembraneSubDomain

use of cbit.vcell.math.MembraneSubDomain in project vcell by virtualcell.

the class FiniteVolumeFileWriter method assignPhases.

private void assignPhases(CompartmentSubDomain[] subDomains, int startingIndex, int[] phases, int[] numAssigned) throws SolverException {
    if (phases[startingIndex] == -1) {
        return;
    }
    if (numAssigned[0] == subDomains.length) {
        return;
    }
    for (int j = subDomains.length - 1; j >= 0; j--) {
        if (startingIndex == j) {
            continue;
        }
        MembraneSubDomain mem = getSimulationTask().getSimulation().getMathDescription().getMembraneSubDomain(subDomains[startingIndex], subDomains[j]);
        if (mem != null) {
            int newPhase = phases[startingIndex] == 0 ? 1 : 0;
            if (phases[j] == -1) {
                numAssigned[0]++;
                // membrane between i and j, different phase
                phases[j] = newPhase;
                assignPhases(subDomains, j, phases, numAssigned);
            } else if (phases[j] != newPhase) {
                throw new SolverException("Geometry is invalid for " + getSimulationTask().getSimulation().getSolverTaskDescription().getSolverDescription().getDisplayLabel() + ": domains are not properly nested (membrane branching). \n\n(domain " + subDomains[j].getName() + " was assigned to phase " + phases[j] + ", is again being assigned to phase " + newPhase + ".)");
            }
        }
    }
}
Also used : MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) SolverException(cbit.vcell.solver.SolverException)

Example 22 with MembraneSubDomain

use of cbit.vcell.math.MembraneSubDomain in project vcell by virtualcell.

the class FiniteVolumeFileWriter method writeModelDescription.

/**
 *# Model description: FEATURE name handle priority boundary_conditions
 *MODEL_BEGIN
 *FEATURE Nucleus 0 value value value value
 *FEATURE Cytosol 1 flux flux value value
 *FEATURE ExtraCellular 2 flux flux value value
 *MEMBRANE Nucleus_Cytosol_membrane Nucleus Cytosol value value value value
 *MEMBRANE Cytosol_ExtraCellular_membrane Cytosol ExtraCellular flux flux value value
 *MODEL_END
 * @throws MathException
 */
private void writeModelDescription() throws MathException {
    Simulation simulation = simTask.getSimulation();
    printWriter.println("# Model description: FEATURE name handle boundary_conditions");
    printWriter.println(FVInputFileKeyword.MODEL_BEGIN);
    MathDescription mathDesc = simulation.getMathDescription();
    Enumeration<SubDomain> enum1 = mathDesc.getSubDomains();
    while (enum1.hasMoreElements()) {
        SubDomain sd = enum1.nextElement();
        if (sd instanceof CompartmentSubDomain) {
            CompartmentSubDomain csd = (CompartmentSubDomain) sd;
            printWriter.print(FVInputFileKeyword.FEATURE + " " + csd.getName() + " " + mathDesc.getHandle(csd) + " ");
            writeFeature_boundaryConditions(csd);
        } else if (sd instanceof MembraneSubDomain) {
            MembraneSubDomain msd = (MembraneSubDomain) sd;
            printWriter.print(FVInputFileKeyword.MEMBRANE + " " + msd.getName() + " " + msd.getInsideCompartment().getName() + " " + msd.getOutsideCompartment().getName() + " ");
            writeMembrane_boundaryConditions(msd);
        }
    }
    printWriter.println(FVInputFileKeyword.MODEL_END);
    printWriter.println();
}
Also used : CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Simulation(cbit.vcell.solver.Simulation) MathDescription(cbit.vcell.math.MathDescription) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain)

Example 23 with MembraneSubDomain

use of cbit.vcell.math.MembraneSubDomain in project vcell by virtualcell.

the class MathTestingUtilities method comparePDEResults.

/**
 * Insert the method's description here.
 * Creation date: (8/20/2003 12:58:10 PM)
 */
public static SimulationComparisonSummary comparePDEResults(SimulationSymbolTable testSimSymbolTable, PDEDataManager testDataManager, SimulationSymbolTable refSimSymbolTable, PDEDataManager refDataManager, String[] varsToCompare, double absErrorThreshold, double relErrorThreshold, VCDocument refDocument, DataInfoProvider refDataInfoProvider, VCDocument testDocument, DataInfoProvider testDataInfoProvider) throws DataAccessException, ExpressionException {
    java.util.Hashtable<String, DataErrorSummary> tempVarHash = new java.util.Hashtable<String, DataErrorSummary>();
    boolean bTimesEqual = true;
    double[] testTimeArray = testDataManager.getDataSetTimes();
    double[] refTimeArray = refDataManager.getDataSetTimes();
    if (testTimeArray.length != refTimeArray.length) {
        bTimesEqual = false;
    // throw new RuntimeException("Data times for reference and test simulations don't match, cannot compare the two simulations!");
    } else {
        for (int i = 0; i < testTimeArray.length; i++) {
            if (testTimeArray[i] != refTimeArray[i]) {
                bTimesEqual = false;
            }
        }
    }
    // if (!checkSimVars(testSim, refSim)) {
    // //String errorS = "TestVars - ";
    // Variable[] testVars = testSim.getVariables();
    // //for(int i =0;i<vars.length;i+= 1){
    // //errorS+= vars[i].getName()+" ";
    // //}
    // //errorS+=" <<>> RefVars - ";
    // Variable[] refVars = refSim.getVariables();
    // //for(int i =0;i<vars.length;i+= 1){
    // //errorS+= vars[i].getName()+" ";
    // //}
    // throw new RuntimeException(
    // "VarNotMatch testLength="+(testVars != null?testVars.length+"":"null")+" refLength="+(refVars != null?refVars.length+"":"null"));
    // }
    CartesianMesh testMesh = testDataManager.getMesh();
    MathDescription testMathDesc = testSimSymbolTable.getSimulation().getMathDescription();
    // Variable[] refVars = refSim.getVariables();
    MathDescription refMathDesc = refSimSymbolTable.getSimulation().getMathDescription();
    CartesianMesh refMesh = refDataManager.getMesh();
    int[] membraneIndexMapping = null;
    // Get volumeSubdomains from mathDesc/mesh and store in lookupTable for testSimulation
    int testNumVol = testMesh.getSizeX() * testMesh.getSizeY() * testMesh.getSizeZ();
    CompartmentSubDomain[] testVolSubDomainLookup = new CompartmentSubDomain[testNumVol];
    for (int i = 0; i < testNumVol; i++) {
        int subVolumeIndex = testMesh.getSubVolumeFromVolumeIndex(i);
        SubVolume subVolume = testMathDesc.getGeometry().getGeometrySpec().getSubVolume(subVolumeIndex);
        CompartmentSubDomain compSubDomain = testMathDesc.getCompartmentSubDomain(subVolume.getName());
        testVolSubDomainLookup[i] = compSubDomain;
    }
    // Get membraneSubdomains from mathDesc/mesh and store in lookupTable for testSimulation
    int testNumMem = testMesh.getMembraneElements().length;
    MembraneSubDomain[] testMemSubDomainLookup = new MembraneSubDomain[testNumMem];
    for (int i = 0; i < testNumMem; i++) {
        int insideVolIndex = testMesh.getMembraneElements()[i].getInsideVolumeIndex();
        int outsideVolIndex = testMesh.getMembraneElements()[i].getOutsideVolumeIndex();
        MembraneSubDomain memSubDomain = testMathDesc.getMembraneSubDomain(testVolSubDomainLookup[insideVolIndex], testVolSubDomainLookup[outsideVolIndex]);
        testMemSubDomainLookup[i] = memSubDomain;
    }
    // Get volumeSubdomains from mathDesc/mesh and store in lookupTable for refSimulation
    int refNumVol = refMesh.getSizeX() * refMesh.getSizeY() * refMesh.getSizeZ();
    CompartmentSubDomain[] refVolSubDomainLookup = new CompartmentSubDomain[refNumVol];
    for (int i = 0; i < refNumVol; i++) {
        int subVolumeIndex = refMesh.getSubVolumeFromVolumeIndex(i);
        SubVolume subVolume = refMathDesc.getGeometry().getGeometrySpec().getSubVolume(subVolumeIndex);
        CompartmentSubDomain compSubDomain = refMathDesc.getCompartmentSubDomain(subVolume.getName());
        refVolSubDomainLookup[i] = compSubDomain;
    }
    // Get membraneSubdomains from mathDesc/mesh and store in lookupTable for refSimulation
    int refNumMem = refMesh.getMembraneElements().length;
    MembraneSubDomain[] refMemSubDomainLookup = new MembraneSubDomain[refNumMem];
    for (int i = 0; i < refNumMem; i++) {
        int insideVolIndex = refMesh.getMembraneElements()[i].getInsideVolumeIndex();
        int outsideVolIndex = refMesh.getMembraneElements()[i].getOutsideVolumeIndex();
        MembraneSubDomain memSubDomain = refMathDesc.getMembraneSubDomain(refVolSubDomainLookup[insideVolIndex], refVolSubDomainLookup[outsideVolIndex]);
        refMemSubDomainLookup[i] = memSubDomain;
    }
    SimulationComparisonSummary simComparisonSummary = new SimulationComparisonSummary();
    String hashKey = new String("");
    DataErrorSummary tempVar = null;
    DataIdentifier[] refDataIDs = refDataManager.getDataIdentifiers();
    // for each var, do the following :
    for (int i = 0; i < varsToCompare.length; i++) {
        DataIdentifier refDataID = null;
        for (int j = 0; j < refDataIDs.length; j++) {
            if (refDataIDs[j].getName().equals(varsToCompare[i])) {
                refDataID = refDataIDs[j];
                break;
            }
        }
        // 
        // Find REFERENCE variable
        // 
        Variable refVar = getSimVar(refSimSymbolTable, varsToCompare[i]);
        if (refVar == null) {
            // Should only happen if TEST sims were generated 'post-domains' and REFERENCE sims were generated 'pre-domains'
            if (refDataID != null) {
                throw new RuntimeException("Unexpected reference condition: '" + varsToCompare[i] + "' not found in symboltable but was found in dataidentifiers");
            }
            if (testDocument instanceof BioModel) {
                // Only BioModels need to be checked
                // Look in TEST for a speciescontext with matching species name
                System.out.println("ReferenceVariable: using alternate method to find '" + varsToCompare[i] + "'");
                BioModel refBioModel = (BioModel) refDocument;
                BioModel testBioModel = (BioModel) testDocument;
                SpeciesContext testSpeciesContext = testBioModel.getModel().getSpeciesContext(varsToCompare[i]);
                if (testSpeciesContext != null) {
                    refVar = refSimSymbolTable.getVariable(testSpeciesContext.getSpecies().getCommonName());
                    for (int j = 0; j < refDataIDs.length; j++) {
                        if (refDataIDs[j].getName().equals(testSpeciesContext.getSpecies().getCommonName())) {
                            refDataID = refDataIDs[j];
                            break;
                        }
                    }
                }
            }
            if (refVar == null || refDataID == null) {
                Simulation refSim = refSimSymbolTable.getSimulation();
                throw new RuntimeException("The variable " + varsToCompare[i] + " was not found in Simulation (" + refSim.getName() + " " + refSim.getVersion().getDate() + ")\n");
            }
        }
        // 
        // Find TEST variable (assumed to have sims generated with a software version later than REFERENCE)
        // 
        Variable testVar = getSimVar(testSimSymbolTable, varsToCompare[i]);
        if (testVar == null) {
            // Should only happen if TEST sims were generated 'post-domains' and REFERENCE sims were generated 'pre-domains'
            System.out.println("TestVariable: using alternate method to find '" + varsToCompare[i] + "'");
            BioModel testBioModel = (BioModel) testDocument;
            SpeciesContext[] speciesContexts = testBioModel.getModel().getSpeciesContexts();
            boolean bSkip = false;
            for (int j = 0; j < speciesContexts.length; j++) {
                if (speciesContexts[j].getSpecies().getCommonName().equals(varsToCompare[i])) {
                    testVar = testSimSymbolTable.getVariable(speciesContexts[j].getName());
                    if (testVar == null) {
                        throw new RuntimeException("Speciescontext name '" + speciesContexts[j].getName() + "' not found in testsimsymboltable");
                    }
                    // If we got here it means at least one matching speciescontext was found in TEST with
                    // a species name matching varsToCompare[i].  We can skip because the matching speciesconetext
                    // will be used to do a comparison at some point.
                    bSkip = true;
                    break;
                }
            }
            if (bSkip) {
                // these are tested already using full simcontext names
                System.out.println("Skipping '" + varsToCompare[i] + "' as lookup in testSimSymbolTable");
                continue;
            }
            Simulation refSim = refSimSymbolTable.getSimulation();
            throw new RuntimeException("The variable " + varsToCompare[i] + " was not found in Simulation (" + refSim.getName() + " " + refSim.getVersion().getDate() + ")\n");
        }
        // for each time in timeArray. ('t' is used to index the testTimeArray, for interpolation purposes.)
        int t = 0;
        for (int j = 0; j < refTimeArray.length; j++) {
            // get data block from varName, data from datablock
            SimDataBlock refSimDataBlock = refDataManager.getSimDataBlock(refVar.getName(), refTimeArray[j]);
            double[] refData = refSimDataBlock.getData();
            double[] resampledTestData = null;
            if (bTimesEqual) {
                // If time arrays for both sims are equal, no need to resample/interpolate, just obtain the datablock from dataManager
                SimDataBlock testSimDataBlock = testDataManager.getSimDataBlock(testVar.getName(), testTimeArray[j]);
                resampledTestData = testSimDataBlock.getData();
            } else {
                // Time resampling (interpolation) needed.
                while ((t < testTimeArray.length - 2) && (refTimeArray[j] >= testTimeArray[t + 1])) {
                    t++;
                }
                SimDataBlock testSimDataBlock_1 = testDataManager.getSimDataBlock(testVar.getName(), testTimeArray[t]);
                double[] testData_1 = testSimDataBlock_1.getData();
                SimDataBlock testSimDataBlock_2 = testDataManager.getSimDataBlock(testVar.getName(), testTimeArray[t + 1]);
                double[] testData_2 = testSimDataBlock_2.getData();
                resampledTestData = new double[testData_1.length];
                // 
                for (int m = 0; m < testData_1.length; m++) {
                    resampledTestData[m] = testData_1[m] + (testData_2[m] - testData_1[m]) * (refTimeArray[j] - testTimeArray[t]) / (testTimeArray[t + 1] - testTimeArray[t]);
                }
            }
            // Spatial resampling (interpolation) ...
            double[] spaceResampledData = new double[refData.length];
            if (!testMathDesc.getGeometry().getExtent().compareEqual(refMathDesc.getGeometry().getExtent()) || !testMathDesc.getGeometry().getOrigin().compareEqual(refMathDesc.getGeometry().getOrigin())) {
                throw new RuntimeException("Different origins and/or extents for the 2 geometries. Cannot compare the 2 simulations");
            }
            if (testMesh.getSizeX() != refMesh.getSizeX() || testMesh.getSizeY() != refMesh.getSizeY() || testMesh.getSizeZ() != refMesh.getSizeZ()) {
                if (testVar instanceof VolVariable) {
                    if (testMathDesc.getGeometry().getDimension() == 1 && refMathDesc.getGeometry().getDimension() == 1) {
                        spaceResampledData = resample1DSpatial(resampledTestData, testMesh, refMesh);
                    } else if (testMathDesc.getGeometry().getDimension() == 2 && refMathDesc.getGeometry().getDimension() == 2) {
                        spaceResampledData = resample2DSpatial(resampledTestData, testMesh, refMesh);
                    } else if (testMathDesc.getGeometry().getDimension() == 3 && refMathDesc.getGeometry().getDimension() == 3) {
                        spaceResampledData = resample3DSpatial(resampledTestData, testMesh, refMesh);
                    } else {
                        throw new RuntimeException("Comparison of 2 simulations with different geometry dimensions are not handled at this time!");
                    }
                } else {
                    throw new RuntimeException("spatial resampling for variable type: " + testVar.getClass().getName() + " not supported");
                }
            } else {
                // no space resampling required
                if (testVar instanceof MemVariable) {
                    // 
                    if (membraneIndexMapping == null) {
                        membraneIndexMapping = testMesh.getMembraneIndexMapping(refMesh);
                    }
                    spaceResampledData = new double[resampledTestData.length];
                    for (int k = 0; k < resampledTestData.length; k++) {
                        spaceResampledData[k] = resampledTestData[membraneIndexMapping[k]];
                    }
                } else {
                    // 
                    // no reordering needed for other variable types.
                    // 
                    spaceResampledData = resampledTestData;
                }
            }
            // for each point in data block ...
            testDataInfoProvider.getPDEDataContext().setVariableName(testVar.getName());
            for (int k = 0; k < refData.length; k++) {
                if (!testDataInfoProvider.isDefined(k)) {
                    continue;
                }
                // Determine maxRef, minRef, maxAbsErr for variable
                // SubDomain testSubDomain = null;
                String sn = null;
                VariableType refVarType = refDataID.getVariableType();
                if (refVarType.equals(VariableType.VOLUME)) {
                    // testSubDomain = refVolSubDomainLookup[k];
                    sn = refVolSubDomainLookup[k].getName();
                } else if (refVarType.equals(VariableType.MEMBRANE)) {
                    // testSubDomain = refMemSubDomainLookup[k];
                    sn = refMemSubDomainLookup[k].getName();
                } else if (refVarType.equals(VariableType.MEMBRANE_REGION)) {
                    sn = "MRV_" + i;
                } else if (refVarType.equals(VariableType.VOLUME_REGION)) {
                    sn = "VRV_" + i;
                } else {
                    throw new RuntimeException("Var " + refVar.getName() + " not supported yet!");
                }
                // hashKey = refVar.getName()+":"+testSubDomain.getName();
                hashKey = refVar.getName() + ":" + sn;
                tempVar = tempVarHash.get(hashKey);
                if (tempVar == null) {
                    tempVar = new DataErrorSummary(null);
                    tempVarHash.put(hashKey, tempVar);
                }
                tempVar.addDataValues(refData[k], spaceResampledData[k], refTimeArray[j], k, absErrorThreshold, relErrorThreshold);
            }
        // end for (k)
        }
    // end for (j)
    }
    // end for (i)
    Enumeration<String> enumKeys = tempVarHash.keys();
    while (enumKeys.hasMoreElements()) {
        String key = enumKeys.nextElement();
        DataErrorSummary tempVarSummary = tempVarHash.get(key);
        simComparisonSummary.addVariableComparisonSummary(new VariableComparisonSummary(key, tempVarSummary.getMinRef(), tempVarSummary.getMaxRef(), tempVarSummary.getMaxAbsoluteError(), tempVarSummary.getMaxRelativeError(), tempVarSummary.getL2Norm(), tempVarSummary.getTimeAtMaxAbsoluteError(), tempVarSummary.getIndexAtMaxAbsoluteError(), tempVarSummary.getTimeAtMaxRelativeError(), tempVarSummary.getIndexAtMaxRelativeError()));
    }
    return simComparisonSummary;
}
Also used : MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) DataIdentifier(cbit.vcell.simdata.DataIdentifier) MembraneRegionVariable(cbit.vcell.math.MembraneRegionVariable) InsideVariable(cbit.vcell.math.InsideVariable) SensVariable(cbit.vcell.solver.ode.SensVariable) FilamentVariable(cbit.vcell.math.FilamentVariable) VolVariable(cbit.vcell.math.VolVariable) VolumeRegionVariable(cbit.vcell.math.VolumeRegionVariable) ReservedVariable(cbit.vcell.math.ReservedVariable) MemVariable(cbit.vcell.math.MemVariable) OutsideVariable(cbit.vcell.math.OutsideVariable) FilamentRegionVariable(cbit.vcell.math.FilamentRegionVariable) Variable(cbit.vcell.math.Variable) MathDescription(cbit.vcell.math.MathDescription) SpeciesContext(cbit.vcell.model.SpeciesContext) SimDataBlock(cbit.vcell.simdata.SimDataBlock) MemVariable(cbit.vcell.math.MemVariable) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) VariableType(cbit.vcell.math.VariableType) VolVariable(cbit.vcell.math.VolVariable) CartesianMesh(cbit.vcell.solvers.CartesianMesh) Simulation(cbit.vcell.solver.Simulation) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) BioModel(cbit.vcell.biomodel.BioModel)

Example 24 with MembraneSubDomain

use of cbit.vcell.math.MembraneSubDomain in project vcell by virtualcell.

the class SmoldynFileWriter method writeDiffusions.

private void writeDiffusions() throws ExpressionBindingException, ExpressionException, MathException {
    // writer diffusion properties
    printWriter.println("# diffusion properties");
    Enumeration<SubDomain> subDomainEnumeration = mathDesc.getSubDomains();
    while (subDomainEnumeration.hasMoreElements()) {
        SubDomain subDomain = subDomainEnumeration.nextElement();
        List<ParticleProperties> particlePropertiesList = subDomain.getParticleProperties();
        for (ParticleProperties pp : particlePropertiesList) {
            String variableName = null;
            if (subDomain instanceof MembraneSubDomain) {
                variableName = getVariableName(pp.getVariable(), subDomain);
            } else {
                variableName = getVariableName(pp.getVariable(), null);
            }
            try {
                double diffConstant = subsituteFlattenToConstant(pp.getDiffusion());
                printWriter.println(SmoldynVCellMapper.SmoldynKeyword.difc + " " + variableName + " " + diffConstant);
            } catch (NotAConstantException ex) {
                throw new ExpressionException("diffusion coefficient for variable " + variableName + " is not a constant. Constants are required for all diffusion coefficients");
            }
        }
    }
    printWriter.println();
}
Also used : CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) ParticleProperties(cbit.vcell.math.ParticleProperties) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 25 with MembraneSubDomain

use of cbit.vcell.math.MembraneSubDomain in project vcell by virtualcell.

the class SmoldynFileWriter method writeInitialConcentration.

private int writeInitialConcentration(ParticleInitialConditionConcentration initialConcentration, SubDomain subDomain, Variable variable, String variableName, StringBuilder sb) throws ExpressionException, MathException {
    SimpleSymbolTable simpleSymbolTable = new SimpleSymbolTable(new String[] { ReservedVariable.X.getName(), ReservedVariable.Y.getName(), ReservedVariable.Z.getName() });
    Expression disExpression = new Expression(initialConcentration.getDistribution());
    disExpression.bindExpression(simulationSymbolTable);
    disExpression = simulationSymbolTable.substituteFunctions(disExpression).flatten();
    disExpression.bindExpression(simpleSymbolTable);
    double[] values = new double[3];
    if (dimension == 1) {
        if (disExpression.getSymbolBinding(ReservedVariable.Y.getName()) != null || disExpression.getSymbolBinding(ReservedVariable.Z.getName()) != null) {
            throw new MathException(VCellErrorMessages.getSmoldynWrongCoordinates("'y' or 'z'", dimension, variable, disExpression));
        }
    } else if (dimension == 2) {
        if (disExpression.getSymbolBinding(ReservedVariable.Z.getName()) != null) {
            throw new MathException(VCellErrorMessages.getSmoldynWrongCoordinates("'z'", dimension, variable, disExpression));
        }
    }
    int totalCount = 0;
    StringBuilder localsb = new StringBuilder();
    if (subDomain instanceof CompartmentSubDomain) {
        MeshSpecification meshSpecification = simulation.getMeshSpecification();
        ISize sampleSize = meshSpecification.getSamplingSize();
        int numX = sampleSize.getX();
        int numY = dimension < 2 ? 1 : sampleSize.getY();
        int numZ = dimension < 3 ? 1 : sampleSize.getZ();
        boolean bCellCentered = simulation.hasCellCenteredMesh();
        double dx = meshSpecification.getDx(bCellCentered);
        double dy = meshSpecification.getDy(bCellCentered);
        double dz = meshSpecification.getDz(bCellCentered);
        Origin origin = resampledGeometry.getGeometrySpec().getOrigin();
        double ox = origin.getX();
        double oy = origin.getY();
        double oz = origin.getZ();
        Extent extent = resampledGeometry.getExtent();
        double ex = extent.getX();
        double ey = extent.getY();
        double ez = extent.getZ();
        int offset = 0;
        for (int k = 0; k < numZ; k++) {
            double centerz = oz + k * dz;
            double loz = Math.max(oz, centerz - dz / 2);
            double hiz = Math.min(oz + ez, centerz + dz / 2);
            double lz = hiz - loz;
            values[2] = centerz;
            for (int j = 0; j < numY; j++) {
                double centery = oy + j * dy;
                double loy = Math.max(oy, centery - dy / 2);
                double hiy = Math.min(oy + ey, centery + dy / 2);
                values[1] = centery;
                double ly = hiy - loy;
                for (int i = 0; i < numX; i++) {
                    int regionIndex = resampledGeometry.getGeometrySurfaceDescription().getRegionImage().getRegionInfoFromOffset(offset).getRegionIndex();
                    offset++;
                    GeometricRegion region = resampledGeometry.getGeometrySurfaceDescription().getGeometricRegions(regionIndex);
                    if (region instanceof VolumeGeometricRegion) {
                        if (!((VolumeGeometricRegion) region).getSubVolume().getName().equals(subDomain.getName())) {
                            continue;
                        }
                    }
                    double centerx = ox + i * dx;
                    double lox = Math.max(ox, centerx - dx / 2);
                    double hix = Math.min(ox + ex, centerx + dx / 2);
                    double lx = hix - lox;
                    values[0] = centerx;
                    double volume = lx;
                    if (dimension > 1) {
                        volume *= ly;
                        if (dimension > 2) {
                            volume *= lz;
                        }
                    }
                    double expectedCount = disExpression.evaluateVector(values) * volume;
                    if (expectedCount <= 0) {
                        continue;
                    }
                    long count = dist.nextPoisson(expectedCount);
                    if (count <= 0) {
                        continue;
                    }
                    totalCount += count;
                    localsb.append(SmoldynVCellMapper.SmoldynKeyword.mol + " " + count + " " + variableName + " " + (float) lox + "-" + (float) hix);
                    if (lg.isDebugEnabled()) {
                        lg.debug("Component subdomain " + variableName + " count " + count);
                    }
                    if (dimension > 1) {
                        localsb.append(" " + loy + "-" + hiy);
                        if (dimension > 2) {
                            localsb.append(" " + loz + "-" + hiz);
                        }
                    }
                    localsb.append("\n");
                }
            }
        }
        // otherwise we append the distributed molecules in different small boxes
        try {
            subsituteFlattenToConstant(disExpression);
            sb.append(SmoldynVCellMapper.SmoldynKeyword.compartment_mol);
            sb.append(" " + totalCount + " " + variableName + " " + subDomain.getName() + "\n");
        } catch (// can not be evaluated to a constant
        Exception e) {
            sb.append(localsb);
        }
    } else if (subDomain instanceof MembraneSubDomain) {
        ArrayList<TrianglePanel> trianglePanelList = membraneSubdomainTriangleMap.get(subDomain);
        for (TrianglePanel trianglePanel : trianglePanelList) {
            Triangle triangle = trianglePanel.triangle;
            switch(dimension) {
                case 1:
                    values[0] = triangle.getNodes(0).getX();
                    break;
                case 2:
                    {
                        double centroidX = triangle.getNodes(0).getX();
                        double centroidY = triangle.getNodes(0).getY();
                        if (triangle.getNodes(0).getX() == triangle.getNodes(1).getX() && triangle.getNodes(0).getY() == triangle.getNodes(1).getY()) {
                            centroidX += triangle.getNodes(2).getX();
                            centroidY += triangle.getNodes(2).getY();
                        } else {
                            centroidX += triangle.getNodes(1).getX();
                            centroidY += triangle.getNodes(1).getY();
                        }
                        values[0] = centroidX / 2;
                        values[1] = centroidY / 2;
                        break;
                    }
                case 3:
                    {
                        double centroidX = triangle.getNodes(0).getX() + triangle.getNodes(1).getX() + triangle.getNodes(2).getX();
                        double centroidY = triangle.getNodes(0).getY() + triangle.getNodes(1).getY() + triangle.getNodes(2).getY();
                        double centroidZ = triangle.getNodes(0).getZ() + triangle.getNodes(1).getZ() + triangle.getNodes(2).getZ();
                        values[0] = centroidX / 3;
                        values[1] = centroidY / 3;
                        values[2] = centroidZ / 3;
                        break;
                    }
            }
            double expectedCount = disExpression.evaluateVector(values) * triangle.getArea();
            if (expectedCount <= 0) {
                continue;
            }
            long count = dist.nextPoisson(expectedCount);
            if (count <= 0) {
                continue;
            }
            totalCount += count;
            if (lg.isDebugEnabled()) {
                lg.debug("Membrane subdomain " + subDomain.getName() + ' ' + variableName + " count " + count);
            }
            localsb.append(SmoldynVCellMapper.SmoldynKeyword.surface_mol + " " + count + " " + variableName + " " + subDomain.getName() + " " + SmoldynVCellMapper.SmoldynKeyword.tri + " " + trianglePanel.name + "\n");
        }
        // otherwise we append the distributed molecules in different small boxes
        try {
            subsituteFlattenToConstant(disExpression);
            sb.append(SmoldynVCellMapper.SmoldynKeyword.surface_mol);
            sb.append(" " + totalCount + " " + variableName + " " + subDomain.getName() + " " + SmoldynVCellMapper.SmoldynKeyword.all + " " + SmoldynVCellMapper.SmoldynKeyword.all + "\n");
        } catch (// can not be evaluated to a constant
        Exception e) {
            sb.append(localsb);
        }
    }
    if (lg.isDebugEnabled()) {
        lg.debug("Subdomain " + subDomain.getName() + ' ' + variableName + " total count " + totalCount);
    }
    return totalCount;
}
Also used : Origin(org.vcell.util.Origin) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) ArrayList(java.util.ArrayList) Triangle(cbit.vcell.geometry.surface.Triangle) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) MeshSpecification(cbit.vcell.solver.MeshSpecification) 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) SurfaceGeometricRegion(cbit.vcell.geometry.surface.SurfaceGeometricRegion) VolumeGeometricRegion(cbit.vcell.geometry.surface.VolumeGeometricRegion) GeometricRegion(cbit.vcell.geometry.surface.GeometricRegion) SimpleSymbolTable(cbit.vcell.parser.SimpleSymbolTable) Expression(cbit.vcell.parser.Expression) MathException(cbit.vcell.math.MathException) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain)

Aggregations

MembraneSubDomain (cbit.vcell.math.MembraneSubDomain)31 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)26 SubDomain (cbit.vcell.math.SubDomain)21 Expression (cbit.vcell.parser.Expression)13 ArrayList (java.util.ArrayList)13 MathDescription (cbit.vcell.math.MathDescription)12 SubVolume (cbit.vcell.geometry.SubVolume)10 ExpressionException (cbit.vcell.parser.ExpressionException)10 Variable (cbit.vcell.math.Variable)9 SurfaceClass (cbit.vcell.geometry.SurfaceClass)8 Constant (cbit.vcell.math.Constant)7 Equation (cbit.vcell.math.Equation)7 MathException (cbit.vcell.math.MathException)7 OdeEquation (cbit.vcell.math.OdeEquation)7 JumpCondition (cbit.vcell.math.JumpCondition)6 ParticleProperties (cbit.vcell.math.ParticleProperties)6 HashMap (java.util.HashMap)6 AnalyticSubVolume (cbit.vcell.geometry.AnalyticSubVolume)5 Function (cbit.vcell.math.Function)5 MemVariable (cbit.vcell.math.MemVariable)5