Search in sources :

Example 36 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh in project vcell by virtualcell.

the class DataSetControllerImpl method calcSpatialStatsInfo.

/**
 * Insert the method's description here.
 * Creation date: (3/20/2006 3:37:39 PM)
 */
private SpatialStatsInfo calcSpatialStatsInfo(OutputContext outputContext, TimeSeriesJobSpec timeSeriesJobSpec, VCDataIdentifier vcdID) throws Exception {
    if (getVCData(vcdID) instanceof SimulationData && ((SimulationData) getVCData(vcdID)).isPostProcessing(outputContext, timeSeriesJobSpec.getVariableNames()[0])) {
        return new SpatialStatsInfo();
    }
    SpatialStatsInfo ssi = new SpatialStatsInfo();
    // Determine weights for indices of each variable if we are going to be calculating spatial statistics
    ssi.bWeightsValid = true;
    // if(timeSeriesJobSpec.isCalcSpaceStats()){
    CartesianMesh myMesh = getMesh(vcdID);
    DataIdentifier[] dataIDs = getDataIdentifiers(outputContext, vcdID);
    ssi.spaceWeight = new double[timeSeriesJobSpec.getVariableNames().length][];
    ssi.totalSpace = new double[timeSeriesJobSpec.getVariableNames().length];
    for (int i = 0; i < timeSeriesJobSpec.getVariableNames().length; i += 1) {
        ssi.spaceWeight[i] = new double[timeSeriesJobSpec.getIndices()[i].length];
        Boolean isVolume = null;
        for (int j = 0; j < dataIDs.length; j += 1) {
            if (dataIDs[j].getName().equals(timeSeriesJobSpec.getVariableNames()[i])) {
                isVolume = new Boolean(dataIDs[j].getVariableType().equals(VariableType.VOLUME) || dataIDs[j].getVariableType().equals(VariableType.VOLUME_REGION));
                break;
            }
        }
        if (isVolume == null) {
            throw new RuntimeException("Couldn't find variable type for varname=" + timeSeriesJobSpec.getVariableNames()[i] + " during TimeSeries calc spatial stats");
        } else {
            for (int j = 0; j < timeSeriesJobSpec.getIndices()[i].length; j += 1) {
                if (isVolume.booleanValue()) {
                    ssi.spaceWeight[i][j] = myMesh.calculateMeshElementVolumeFromVolumeIndex(timeSeriesJobSpec.getIndices()[i][j]);
                } else {
                    // assume membrane
                    double area = myMesh.getMembraneElements()[timeSeriesJobSpec.getIndices()[i][j]].getArea();
                    if (area == MembraneElement.AREA_UNDEFINED) {
                        ssi.bWeightsValid = false;
                        break;
                    }
                    ssi.spaceWeight[i][j] = area;
                }
                ssi.totalSpace[i] += ssi.spaceWeight[i][j];
            }
        }
        if (!ssi.bWeightsValid) {
            break;
        }
    }
    // if(ssi.bWeightsValid){
    return ssi;
// }else{
// return null;
// }
}
Also used : CartesianMesh(cbit.vcell.solvers.CartesianMesh) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier)

Example 37 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh in project vcell by virtualcell.

the class DataSetControllerImpl method findFunctionIndexes.

/**
 * Insert the method's description here.
 * Creation date: (10/13/00 9:13:52 AM)
 * @return cbit.vcell.simdata.SimDataBlock
 * @param user cbit.vcell.server.User
 * @param simResults cbit.vcell.simdata.SimResults
 * @param function cbit.vcell.math.Function
 * @param time double
 */
private FunctionIndexes[] findFunctionIndexes(VCDataIdentifier vcdID, AnnotatedFunction function, int[] dataIndexes, OutputContext outputContext) throws ExpressionException, DataAccessException, IOException, MathException {
    if (function.getFunctionType().equals(VariableType.POSTPROCESSING)) {
        FunctionIndexes[] fiArr = new FunctionIndexes[dataIndexes.length];
        Vector<DataSetIdentifier> dependencyList = identifyDataDependencies(function);
        SimulationData simData = (SimulationData) getVCData(vcdID);
        String[] varNames = new String[dependencyList.size()];
        String[] simFileVarNames = new String[dependencyList.size()];
        for (int i = 0; i < varNames.length; i++) {
            varNames[i] = dependencyList.get(i).getName();
            simFileVarNames[i] = dependencyList.get(i).getName();
        }
        CartesianMesh mesh = simData.getPostProcessingMesh(function.getName(), outputContext);
        int[][] varIndexes = new int[dataIndexes.length][varNames.length];
        for (int i = 0; i < dataIndexes.length; i += 1) {
            for (int j = 0; j < varNames.length; j++) {
                varIndexes[i][j] = dataIndexes[i];
            }
        }
        // VolumeIndexNearFar[][] outside_near_far_indexes = null;//new VolumeIndexNearFar[dataIndexes.length][/*varNames.length*/];
        for (int i = 0; i < dataIndexes.length; i += 1) {
            fiArr[i] = new FunctionIndexes(function, mesh.getCoordinateFromVolumeIndex(dataIndexes[i]), varNames, simFileVarNames, varIndexes[i], null, null);
        }
        return fiArr;
    }
    VariableType variableType = function.getFunctionType();
    Vector<DataSetIdentifier> dependencyList = identifyDataDependencies(function);
    int varIndex = TXYZ_OFFSET + dependencyList.size();
    // 
    // get Indexes and simFileNames
    // 
    Coordinate initCoord = new Coordinate(0, 0, 0);
    Coordinate[] coords = new Coordinate[dataIndexes.length];
    for (int i = 0; i < coords.length; i += 1) {
        coords[i] = initCoord;
    }
    String[] varNames = new String[varIndex - TXYZ_OFFSET];
    String[] simFileVarNames = new String[varNames.length];
    int[][] varIndexes = new int[dataIndexes.length][varNames.length];
    // New data needed for INSIDE-OUTSIDE interpolation
    VolumeIndexNearFar[][] inside_near_far_indexes = new VolumeIndexNearFar[dataIndexes.length][varNames.length];
    VolumeIndexNearFar[][] outside_near_far_indexes = new VolumeIndexNearFar[dataIndexes.length][varNames.length];
    CartesianMesh mesh = getMesh(vcdID);
    // 
    for (int i = 0; i < dataIndexes.length; i += 1) {
        coords[i] = mesh.getCoordinateFromVolumeIndex(dataIndexes[i]);
        if (variableType.equals(VariableType.VOLUME)) {
            // coord = mesh.getCoordinateFromVolumeIndex(dataIndex);
            coords[i] = mesh.getCoordinateFromVolumeIndex(dataIndexes[i]);
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                if (dsi.getVariableType().equals(VariableType.VOLUME)) {
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = dataIndexes[i];
                } else if (dsi.getVariableType().equals(VariableType.VOLUME_REGION)) {
                    int volumeIndex = mesh.getVolumeRegionIndex(dataIndexes[i]);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = volumeIndex;
                }
            }
        } else if (variableType.equals(VariableType.VOLUME_REGION)) {
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                if (dsi.getVariableType().equals(VariableType.VOLUME_REGION)) {
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = dataIndexes[i];
                }
            }
        } else if (variableType.equals(VariableType.MEMBRANE)) {
            // coord = mesh.getCoordinateFromMembraneIndex(dataIndex);
            coords[i] = mesh.getCoordinateFromMembraneIndex(dataIndexes[i]);
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                if (dsi.getVariableType().equals(VariableType.VOLUME)) {
                    if (mesh.isChomboMesh()) {
                        // don't do any varname modifications here,
                        // because chombo needs this info to decide
                        // which data set to read, extrapolate values or solution.
                        // if varname doesn't have _INSIDE or _OUTSIDE
                        // add _INSIDE to varname to indicate it needs to read extrapolated values
                        String varName = dsi.getName();
                        if (!varName.endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX) && !varName.endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                            varName += InsideVariable.INSIDE_VARIABLE_SUFFIX;
                            // add this new varname to the list if it's not already there
                            getVCData(vcdID).getEntry(varName);
                        }
                        simFileVarNames[j] = varName;
                        varIndexes[i][j] = dataIndexes[i];
                    } else {
                        if (dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                            int volInsideIndex = mesh.getMembraneElements()[dataIndexes[i]].getInsideVolumeIndex();
                            varNames[j] = dsi.getName();
                            simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                            varIndexes[i][j] = volInsideIndex;
                            inside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], true, false);
                        } else if (dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                            int volOutsideIndex = mesh.getMembraneElements()[dataIndexes[i]].getOutsideVolumeIndex();
                            varNames[j] = dsi.getName();
                            simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                            varIndexes[i][j] = volOutsideIndex;
                            outside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], false, false);
                        } else {
                            varNames[j] = dsi.getName();
                            simFileVarNames[j] = dsi.getName();
                            if (isDomainInside(mesh, dsi.getDomain(), dataIndexes[i])) {
                                inside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dsi.getDomain(), dataIndexes[i], false);
                                varIndexes[i][j] = inside_near_far_indexes[i][j].volIndexNear;
                            } else {
                                outside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dsi.getDomain(), dataIndexes[i], false);
                                varIndexes[i][j] = outside_near_far_indexes[i][j].volIndexNear;
                            }
                        }
                    }
                } else if (dsi.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                    int insideVolumeIndex = mesh.getMembraneElements()[dataIndexes[i]].getInsideVolumeIndex();
                    int volRegionIndex = mesh.getVolumeRegionIndex(insideVolumeIndex);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                    varIndexes[i][j] = volRegionIndex;
                    inside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], true, true);
                } else if (dsi.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                    int outsideVolumeIndex = mesh.getMembraneElements()[dataIndexes[i]].getOutsideVolumeIndex();
                    int volRegionIndex = mesh.getVolumeRegionIndex(outsideVolumeIndex);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                    varIndexes[i][j] = volRegionIndex;
                    outside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], false, true);
                } else if (dsi.getVariableType().equals(VariableType.MEMBRANE)) {
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = dataIndexes[i];
                } else if (dsi.getVariableType().equals(VariableType.MEMBRANE_REGION)) {
                    int memRegionIndex = mesh.getMembraneRegionIndex(dataIndexes[i]);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = memRegionIndex;
                }
            }
        } else if (variableType.equals(VariableType.MEMBRANE_REGION)) {
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                if (dsi.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                    // 
                    // find "inside" volume element index for first membrane element in MembraneRegion 'i'.
                    // 
                    int insideVolumeIndex = -1;
                    for (int k = 0; k < mesh.getMembraneElements().length; k++) {
                        if (mesh.getMembraneRegionIndex(k) == dataIndexes[i]) {
                            insideVolumeIndex = mesh.getMembraneElements()[k].getInsideVolumeIndex();
                            break;
                        }
                    }
                    int volRegionIndex = mesh.getVolumeRegionIndex(insideVolumeIndex);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                    varIndexes[i][j] = volRegionIndex;
                    inside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], true, true);
                    ;
                } else if (dsi.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                    // 
                    // find "outside" volume element index for first membrane element in MembraneRegion 'i'.
                    // 
                    int outsideVolumeIndex = -1;
                    for (int k = 0; k < mesh.getMembraneElements().length; k++) {
                        if (mesh.getMembraneRegionIndex(k) == dataIndexes[i]) {
                            outsideVolumeIndex = mesh.getMembraneElements()[k].getOutsideVolumeIndex();
                            break;
                        }
                    }
                    int volRegionIndex = mesh.getVolumeRegionIndex(outsideVolumeIndex);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                    varIndexes[i][j] = volRegionIndex;
                    outside_near_far_indexes[i][j] = interpolateFindNearFarIndex(mesh, dataIndexes[i], false, true);
                } else if (dsi.getVariableType().equals(VariableType.MEMBRANE)) {
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = dataIndexes[i];
                } else if (dsi.getVariableType().equals(VariableType.MEMBRANE_REGION)) {
                    int memRegionIndex = mesh.getMembraneRegionIndex(dataIndexes[i]);
                    varNames[j] = dsi.getName();
                    simFileVarNames[j] = dsi.getName();
                    varIndexes[i][j] = memRegionIndex;
                }
            }
        }
    }
    FunctionIndexes[] fiArr = new FunctionIndexes[dataIndexes.length];
    for (int i = 0; i < dataIndexes.length; i += 1) {
        fiArr[i] = new FunctionIndexes(function, coords[i], varNames, simFileVarNames, varIndexes[i], inside_near_far_indexes[i], outside_near_far_indexes[i]);
    }
    return fiArr;
// 
}
Also used : VariableType(cbit.vcell.math.VariableType) CartesianMesh(cbit.vcell.solvers.CartesianMesh) Coordinate(org.vcell.util.Coordinate)

Example 38 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh in project vcell by virtualcell.

the class DataSetControllerImpl method writeFieldFunctionData.

/**
 * Insert the method's description here.
 * Creation date: (9/21/2006 1:28:12 PM)
 * @throws FileNotFoundException
 * @throws DataAccessException
 */
public void writeFieldFunctionData(OutputContext outputContext, FieldDataIdentifierSpec[] argFieldDataIDSpecs, boolean[] bResampleFlags, CartesianMesh newMesh, SimResampleInfoProvider simResampleInfoProvider, int simResampleMembraneDataLength, int handleExistingResampleMode) throws FileNotFoundException, DataAccessException, IOException {
    if (handleExistingResampleMode != FVSolverStandalone.HESM_KEEP_AND_CONTINUE && handleExistingResampleMode != FVSolverStandalone.HESM_OVERWRITE_AND_CONTINUE && handleExistingResampleMode != FVSolverStandalone.HESM_THROW_EXCEPTION) {
        throw new IllegalArgumentException("Unknown mode " + handleExistingResampleMode);
    }
    if (argFieldDataIDSpecs == null || argFieldDataIDSpecs.length == 0) {
        return;
    }
    HashMap<FieldDataIdentifierSpec, File> uniqueFieldDataIDSpecAndFileH = new HashMap<FieldDataIdentifierSpec, File>();
    HashMap<FieldDataIdentifierSpec, Boolean> bFieldDataResample = new HashMap<FieldDataIdentifierSpec, Boolean>();
    for (int i = 0; i < argFieldDataIDSpecs.length; i++) {
        if (!uniqueFieldDataIDSpecAndFileH.containsKey(argFieldDataIDSpecs[i])) {
            File newResampledFieldDataFile = null;
            try {
                newResampledFieldDataFile = ((SimulationData) getVCData(simResampleInfoProvider)).getFieldDataFile(simResampleInfoProvider, argFieldDataIDSpecs[i].getFieldFuncArgs());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                // use the original way
                newResampledFieldDataFile = new File(getPrimaryUserDir(simResampleInfoProvider.getOwner(), true), SimulationData.createCanonicalResampleFileName(simResampleInfoProvider, argFieldDataIDSpecs[i].getFieldFuncArgs()));
            }
            if (handleExistingResampleMode == FVSolverStandalone.HESM_THROW_EXCEPTION && newResampledFieldDataFile.exists()) {
                throw new RuntimeException("Resample Error: mode not allow overwrite or ignore of " + "existing file\n" + newResampledFieldDataFile.getAbsolutePath());
            }
            uniqueFieldDataIDSpecAndFileH.put(argFieldDataIDSpecs[i], newResampledFieldDataFile);
            bFieldDataResample.put(argFieldDataIDSpecs[i], bResampleFlags[i]);
        }
    }
    try {
        Set<Entry<FieldDataIdentifierSpec, File>> resampleSet = uniqueFieldDataIDSpecAndFileH.entrySet();
        Iterator<Entry<FieldDataIdentifierSpec, File>> resampleSetIter = resampleSet.iterator();
        while (resampleSetIter.hasNext()) {
            Entry<FieldDataIdentifierSpec, File> resampleEntry = resampleSetIter.next();
            if (handleExistingResampleMode == FVSolverStandalone.HESM_KEEP_AND_CONTINUE && resampleEntry.getValue().exists()) {
                continue;
            }
            FieldDataIdentifierSpec fieldDataIdSpec = resampleEntry.getKey();
            boolean bResample = bFieldDataResample.get(fieldDataIdSpec);
            CartesianMesh origMesh = getMesh(fieldDataIdSpec.getExternalDataIdentifier());
            SimDataBlock simDataBlock = getSimDataBlock(outputContext, fieldDataIdSpec.getExternalDataIdentifier(), fieldDataIdSpec.getFieldFuncArgs().getVariableName(), fieldDataIdSpec.getFieldFuncArgs().getTime().evaluateConstant());
            VariableType varType = fieldDataIdSpec.getFieldFuncArgs().getVariableType();
            VariableType dataVarType = simDataBlock.getVariableType();
            if (!varType.equals(VariableType.UNKNOWN) && !varType.equals(dataVarType)) {
                throw new IllegalArgumentException("field function variable type (" + varType.getTypeName() + ") doesn't match real variable type (" + dataVarType.getTypeName() + ")");
            }
            double[] origData = simDataBlock.getData();
            double[] newData = null;
            CartesianMesh resampleMesh = newMesh;
            if (!bResample) {
                if (resampleMesh.getGeometryDimension() != origMesh.getGeometryDimension()) {
                    throw new DataAccessException("Field data " + fieldDataIdSpec.getFieldFuncArgs().getFieldName() + " (" + origMesh.getGeometryDimension() + "D) should have same dimension as simulation mesh (" + resampleMesh.getGeometryDimension() + "D) because it is not resampled to simulation mesh (e.g. Point Spread Function)");
                }
                newData = origData;
                resampleMesh = origMesh;
            } else {
                if (CartesianMesh.isSpatialDomainSame(origMesh, resampleMesh)) {
                    newData = origData;
                    if (simDataBlock.getVariableType().equals(VariableType.MEMBRANE)) {
                        if (origData.length != simResampleMembraneDataLength) {
                            throw new Exception("FieldData variable \"" + fieldDataIdSpec.getFieldFuncArgs().getVariableName() + "\" (" + simDataBlock.getVariableType().getTypeName() + ") " + "resampling failed: Membrane Data lengths must be equal");
                        }
                    } else if (!simDataBlock.getVariableType().equals(VariableType.VOLUME)) {
                        throw new Exception("FieldData variable \"" + fieldDataIdSpec.getFieldFuncArgs().getVariableName() + "\" (" + simDataBlock.getVariableType().getTypeName() + ") " + "resampling failed: Only Volume and Membrane variable types are supported");
                    }
                } else {
                    if (!simDataBlock.getVariableType().compareEqual(VariableType.VOLUME)) {
                        throw new Exception("FieldData variable \"" + fieldDataIdSpec.getFieldFuncArgs().getVariableName() + "\" (" + simDataBlock.getVariableType().getTypeName() + ") " + "resampling failed: Only VOLUME FieldData variable type allowed when\n" + "FieldData spatial domain does not match Simulation spatial domain.\n" + "Check dimension, xsize, ysize, zsize, origin and extent are equal.");
                    }
                    if (origMesh.getSizeY() == 1 && origMesh.getSizeZ() == 1) {
                        newData = MathTestingUtilities.resample1DSpatialSimple(origData, origMesh, resampleMesh);
                    } else if (origMesh.getSizeZ() == 1) {
                        newData = MathTestingUtilities.resample2DSpatialSimple(origData, origMesh, resampleMesh);
                    } else {
                        newData = MathTestingUtilities.resample3DSpatialSimple(origData, origMesh, resampleMesh);
                    }
                }
            }
            DataSet.writeNew(resampleEntry.getValue(), new String[] { fieldDataIdSpec.getFieldFuncArgs().getVariableName() }, new VariableType[] { simDataBlock.getVariableType() }, new ISize(resampleMesh.getSizeX(), resampleMesh.getSizeY(), resampleMesh.getSizeZ()), new double[][] { newData });
        }
    } catch (Exception ex) {
        ex.printStackTrace(System.out);
        throw new DataAccessException(ex.getMessage());
    }
}
Also used : VariableType(cbit.vcell.math.VariableType) HashMap(java.util.HashMap) ISize(org.vcell.util.ISize) FileNotFoundException(java.io.FileNotFoundException) ObjectNotFoundException(org.vcell.util.ObjectNotFoundException) XmlParseException(cbit.vcell.xml.XmlParseException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) CacheException(org.vcell.util.CacheException) ExpressionBindingException(cbit.vcell.parser.ExpressionBindingException) FileNotFoundException(java.io.FileNotFoundException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ZipArchiveEntry(org.apache.commons.compress.archivers.zip.ZipArchiveEntry) ZipEntry(java.util.zip.ZipEntry) Entry(java.util.Map.Entry) CartesianMesh(cbit.vcell.solvers.CartesianMesh) FieldDataIdentifierSpec(cbit.vcell.field.FieldDataIdentifierSpec) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) DataAccessException(org.vcell.util.DataAccessException)

Example 39 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh in project vcell by virtualcell.

the class DataSetControllerImpl method evaluateFunction.

/**
 * Insert the method's description here.
 * Creation date: (10/13/00 9:13:52 AM)
 * @return cbit.vcell.simdata.SimDataBlock
 * @param user cbit.vcell.server.User
 * @param simResults cbit.vcell.simdata.SimResults
 * @param function cbit.vcell.math.Function
 * @param time double
 */
private SimDataBlock evaluateFunction(OutputContext outputContext, final VCDataIdentifier vcdID, VCData simData, AnnotatedFunction function, double time) throws ExpressionException, DataAccessException, IOException, MathException {
    Expression exp = new Expression(function.getExpression());
    exp = SolverUtilities.substituteSizeAndNormalFunctions(exp, function.getFunctionType().getVariableDomain());
    exp.bindExpression(simData);
    exp = fieldFunctionSubstitution(outputContext, vcdID, exp);
    // 
    // get Dependent datasets
    // 
    // variables are indexed by a number, t=0, x=1, y=2, z=3, a(i) = 4+i where a's are other variables
    // these variables
    // 
    CartesianMesh mesh = null;
    if (function.getFunctionType().equals(VariableType.POSTPROCESSING)) {
        mesh = ((SimulationData) simData).getPostProcessingMesh(function.getName(), outputContext);
    }
    if (mesh == null) {
        mesh = getMesh(vcdID);
    }
    String[] dependentIDs = exp.getSymbols();
    Vector<SimDataHolder> dataSetList = new Vector<SimDataHolder>();
    Vector<DataSetIdentifier> dependencyList = new Vector<DataSetIdentifier>();
    int varIndex = TXYZ_OFFSET;
    int dataLength = 0;
    long lastModified = 0;
    VariableType variableType = function.getFunctionType();
    if (variableType.equals(VariableType.VOLUME) || variableType.equals(VariableType.POSTPROCESSING)) {
        dataLength = mesh.getNumVolumeElements();
    } else if (variableType.equals(VariableType.MEMBRANE)) {
        dataLength = mesh.getNumMembraneElements();
    } else if (variableType.equals(VariableType.VOLUME_REGION)) {
        dataLength = mesh.getNumVolumeRegions();
    } else if (variableType.equals(VariableType.MEMBRANE_REGION)) {
        dataLength = mesh.getNumMembraneRegions();
    }
    VariableType computedVariableType = null;
    int computedDataLength = 0;
    for (int i = 0; dependentIDs != null && i < dependentIDs.length; i++) {
        SymbolTableEntry ste = exp.getSymbolBinding(dependentIDs[i]);
        if (ste instanceof DataSetIdentifier) {
            DataSetIdentifier dsi = (DataSetIdentifier) ste;
            dependencyList.addElement(dsi);
            dsi.setIndex(varIndex++);
            if (dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX) || dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                String volVarName = dsi.getName().substring(0, dsi.getName().lastIndexOf("_"));
                SimDataBlock simDataBlock = getSimDataBlock(outputContext, vcdID, volVarName, time);
                lastModified = simDataBlock.getPDEDataInfo().getTimeStamp();
                // 
                if (simDataBlock.getVariableType().equals(VariableType.VOLUME)) {
                    computedVariableType = VariableType.MEMBRANE;
                    computedDataLength = mesh.getMembraneElements().length;
                // 
                // if inside/outside volume element dependent, then can only be a membrane type
                // 
                } else if (simDataBlock.getVariableType().equals(VariableType.VOLUME_REGION) && variableType == null) {
                    computedVariableType = VariableType.MEMBRANE_REGION;
                    computedDataLength = mesh.getNumMembraneRegions();
                }
                dataSetList.addElement(simDataBlock);
            } else {
                SimDataBlock simDataBlock = getSimDataBlock(outputContext, vcdID, dsi.getName(), time);
                if (variableType == null || simDataBlock.getVariableType().isExpansionOf(variableType)) {
                    lastModified = simDataBlock.getPDEDataInfo().getTimeStamp();
                    computedDataLength = simDataBlock.getData().length;
                    computedVariableType = simDataBlock.getVariableType();
                }
                dataSetList.addElement(simDataBlock);
            }
        } else if (ste instanceof ReservedVariable) {
            ReservedVariable rv = (ReservedVariable) ste;
            if (rv.isTIME()) {
                rv.setIndex(0);
            } else if (rv.isX()) {
                rv.setIndex(1);
            } else if (rv.isY()) {
                rv.setIndex(2);
            } else if (rv.isZ()) {
                rv.setIndex(3);
            }
        } else if (ste instanceof FieldDataParameterVariable) {
            // Field Data
            ((FieldDataParameterVariable) ste).setIndex(varIndex++);
            final double[] steResampledFieldData = ((FieldDataParameterVariable) ste).getResampledFieldData();
            final VariableType newVariableType = (steResampledFieldData.length == mesh.getNumVolumeElements() ? VariableType.VOLUME : (steResampledFieldData.length == mesh.getNumMembraneElements() ? VariableType.MEMBRANE : null));
            if (newVariableType == null) {
                throw new DataAccessException("Couldn't determine VariableType for FieldData");
            }
            if (variableType != null && !variableType.equals(newVariableType)) {
                throw new DataAccessException("Incompatible VariableType for FieldData");
            }
            SimDataHolder newSimDataHolder = new SimDataHolder() {

                public double[] getData() {
                    return steResampledFieldData;
                }

                public VariableType getVariableType() {
                    return newVariableType;
                }
            };
            dataSetList.addElement(newSimDataHolder);
            dependencyList.add(new DataSetIdentifier(ste.getName(), newVariableType, ((FieldDataParameterVariable) ste).getDomain()));
            if (variableType == null) {
                computedVariableType = newVariableType;
                computedDataLength = newSimDataHolder.getData().length;
            }
        }
    }
    if (computedDataLength <= 0) {
        if (lg.isWarnEnabled())
            lg.warn("dependencies for function '" + function + "' not found, assuming datalength of volume");
        computedDataLength = mesh.getDataLength(VariableType.VOLUME);
        computedVariableType = VariableType.VOLUME;
    // try {
    // computedDataLength = mesh.getDataLength(VariableType.VOLUME);
    // computedVariableType = VariableType.VOLUME;
    // }catch (MathException e){
    // lg.error(e.getMessage(), e);
    // throw new RuntimeException("MathException, cannot determine domain for function '"+function+"'");
    // }catch (FileNotFoundException e){
    // lg.error(e.getMessage(), e);
    // throw new RuntimeException("Mesh not found, cannot determine domain for function '"+function+"'");
    // }
    }
    if (!variableType.equals(computedVariableType)) {
        System.err.println("function [" + function.getName() + "] variable type [" + variableType.getTypeName() + "] is not equal to computed variable type [" + computedVariableType.getTypeName() + "].");
    }
    if (dataLength == 0) {
        dataLength = computedDataLength;
        variableType = computedVariableType;
    }
    // 
    // Gradient Info for special processing
    // 
    boolean isGrad = hasGradient(exp);
    if (isGrad && !variableType.equals(VariableType.VOLUME)) {
        throw new DataAccessException("Gradient function is not implemented for datatype " + variableType.getTypeName());
    }
    double[] args = new double[varIndex + (isGrad ? 12 * varIndex : 0)];
    double[] data = new double[dataLength];
    // time
    args[0] = time;
    // x
    args[1] = 0.0;
    // y
    args[2] = 0.0;
    // z
    args[3] = 0.0;
    String dividedByZeroMsg = "";
    for (int i = 0; i < dataLength; i++) {
        // 
        if (variableType.equals(VariableType.VOLUME) || variableType.equals(VariableType.POSTPROCESSING)) {
            Coordinate coord = mesh.getCoordinateFromVolumeIndex(i);
            args[1] = coord.getX();
            args[2] = coord.getY();
            args[3] = coord.getZ();
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                SimDataHolder simDataHolder = dataSetList.elementAt(j);
                if (simDataHolder.getVariableType().equals(VariableType.VOLUME) || simDataHolder.getVariableType().equals(VariableType.POSTPROCESSING)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[i];
                } else if (simDataHolder.getVariableType().equals(VariableType.VOLUME_REGION)) {
                    int volumeIndex = mesh.getVolumeRegionIndex(i);
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[volumeIndex];
                } else if (simDataHolder.getVariableType().equals(VariableType.POINT_VARIABLE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[0];
                }
            }
            if (isGrad) {
                getSpatialNeighborData(mesh, i, varIndex, time, dataSetList, args);
            }
        } else if (variableType.equals(VariableType.VOLUME_REGION)) {
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                SimDataHolder simDataHolder = dataSetList.elementAt(j);
                if (simDataHolder.getVariableType().equals(VariableType.VOLUME_REGION)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[i];
                } else if (simDataHolder.getVariableType().equals(VariableType.POINT_VARIABLE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[0];
                }
            }
        } else if (variableType.equals(VariableType.MEMBRANE)) {
            Coordinate coord = mesh.getCoordinateFromMembraneIndex(i);
            args[1] = coord.getX();
            args[2] = coord.getY();
            args[3] = coord.getZ();
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                SimDataHolder simDataHolder = dataSetList.elementAt(j);
                if (simDataHolder.getVariableType().equals(VariableType.VOLUME)) {
                    if (mesh.isChomboMesh()) {
                        String varName = dsi.getName();
                        if (dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                            varName = varName.substring(0, varName.lastIndexOf(InsideVariable.INSIDE_VARIABLE_SUFFIX));
                        } else if (dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                            varName = varName.substring(0, varName.lastIndexOf(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX));
                        }
                        args[TXYZ_OFFSET + j] = getChomboExtrapolatedValues(vcdID, varName, time).getData()[i];
                    } else {
                        if (dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                            args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, true, false);
                        } else if (dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                            args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, false, false);
                        } else {
                            args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, dsi.getDomain(), i, simDataHolder, false);
                        }
                    }
                } else if (simDataHolder.getVariableType().equals(VariableType.VOLUME_REGION)) {
                    if (dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                        args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, true, true);
                    } else if (dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                        args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, false, true);
                    } else {
                        args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, dsi.getDomain(), i, simDataHolder, true);
                    }
                } else if (simDataHolder.getVariableType().equals(VariableType.MEMBRANE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[i];
                } else if (simDataHolder.getVariableType().equals(VariableType.MEMBRANE_REGION)) {
                    int memRegionIndex = mesh.getMembraneRegionIndex(i);
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[memRegionIndex];
                } else if (simDataHolder.getVariableType().equals(VariableType.POINT_VARIABLE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[0];
                }
            }
        } else if (variableType.equals(VariableType.MEMBRANE_REGION)) {
            for (int j = 0; j < varIndex - TXYZ_OFFSET; j++) {
                DataSetIdentifier dsi = (DataSetIdentifier) dependencyList.elementAt(j);
                SimDataHolder simDataHolder = dataSetList.elementAt(j);
                if (simDataHolder.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(InsideVariable.INSIDE_VARIABLE_SUFFIX)) {
                    // 
                    for (int k = 0; k < mesh.getMembraneElements().length; k++) {
                        if (mesh.getMembraneRegionIndex(k) == i) {
                            args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, true, true);
                            break;
                        }
                    }
                } else if (simDataHolder.getVariableType().equals(VariableType.VOLUME_REGION) && dsi.getName().endsWith(OutsideVariable.OUTSIDE_VARIABLE_SUFFIX)) {
                    // 
                    for (int k = 0; k < mesh.getMembraneElements().length; k++) {
                        if (mesh.getMembraneRegionIndex(k) == i) {
                            args[TXYZ_OFFSET + j] = interpolateVolDataValToMemb(mesh, i, simDataHolder, false, true);
                            break;
                        }
                    }
                } else if (simDataHolder.getVariableType().equals(VariableType.MEMBRANE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[i];
                } else if (simDataHolder.getVariableType().equals(VariableType.MEMBRANE_REGION)) {
                    int memRegionIndex = i;
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[memRegionIndex];
                } else if (simDataHolder.getVariableType().equals(VariableType.POINT_VARIABLE)) {
                    args[TXYZ_OFFSET + j] = simDataHolder.getData()[0];
                }
            }
        }
        try {
            data[i] = exp.evaluateVector(args);
        // if(time ==0){
        // System.out.print("non-multi evalFunction ");
        // for (int m = 0; m < args.length; m++) {
        // System.out.print(args[m]);
        // }
        // System.out.println(" "+(args[args.length-2]/args[args.length-1]));
        // }
        } catch (DivideByZeroException e) {
            dividedByZeroMsg = e.getMessage();
            data[i] = Double.POSITIVE_INFINITY;
        }
    }
    if (dividedByZeroMsg.length() != 0) {
        System.out.println("DataSetControllerImpl.evaluateFunction(): DivideByZero " + dividedByZeroMsg);
    }
    PDEDataInfo pdeDataInfo = new PDEDataInfo(vcdID.getOwner(), vcdID.getID(), function.getName(), time, lastModified);
    return new SimDataBlock(pdeDataInfo, data, variableType);
}
Also used : VariableType(cbit.vcell.math.VariableType) DivideByZeroException(cbit.vcell.parser.DivideByZeroException) CartesianMesh(cbit.vcell.solvers.CartesianMesh) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) ReservedVariable(cbit.vcell.math.ReservedVariable) Expression(cbit.vcell.parser.Expression) Coordinate(org.vcell.util.Coordinate) Vector(java.util.Vector) DataAccessException(org.vcell.util.DataAccessException) FieldDataParameterVariable(cbit.vcell.field.FieldDataParameterVariable)

Example 40 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh in project vcell by virtualcell.

the class MergedData method getSimDataBlock.

/**
 * This method was created in VisualAge.
 * @return cbit.vcell.simdata.DataBlock
 * @param user cbit.vcell.server.User
 * @param simID java.lang.String
 */
public SimDataBlock getSimDataBlock(OutputContext outputContext, String varName, double time) throws DataAccessException, IOException {
    VCDataIdentifier vcDataID = getVCDataIdentifierFromDataId(varName);
    if (vcDataID == null) {
        return null;
    }
    DataSetIdentifier varDatasetID = getDataSetIdentifier(varName);
    int actualVarNameIndx = varName.indexOf(".");
    String actualVarName = varName.substring(actualVarNameIndx + 1);
    SimDataBlock simDataBlk = null;
    // 
    if (vcDataID.getID().equals(datasetsIDList[0].getID())) {
        simDataBlk = getDatasetControllerImpl().getSimDataBlock(outputContext, vcDataID, actualVarName, time);
        return simDataBlk;
    } else {
        // TIME INTERPOLATION of datablock
        double[] timeArray = getDatasetControllerImpl().getDataSetTimes(vcDataID);
        boolean bTimesEqual = checkTimeArrays(timeArray);
        double[] timeResampledData = null;
        int timeArrayCounter = 0;
        long lastModified = Long.MIN_VALUE;
        if (bTimesEqual) {
            // If time arrays for both datasets are equal, no need to resample/interpolate in time, just obtain the datablock
            simDataBlk = getDatasetControllerImpl().getSimDataBlock(outputContext, vcDataID, actualVarName, time);
            timeResampledData = simDataBlk.getData();
        } else {
            while ((timeArrayCounter < timeArray.length - 2) && (time > timeArray[timeArrayCounter + 1])) {
                timeArrayCounter++;
            }
            SimDataBlock simDataBlock_1 = getDatasetControllerImpl().getSimDataBlock(outputContext, vcDataID, actualVarName, timeArray[timeArrayCounter]);
            double[] data_1 = simDataBlock_1.getData();
            if ((timeArrayCounter + 1) < (timeArray.length - 1)) {
                SimDataBlock simDataBlock_2 = getDatasetControllerImpl().getSimDataBlock(outputContext, vcDataID, actualVarName, timeArray[timeArrayCounter + 1]);
                lastModified = simDataBlock_2.getPDEDataInfo().getTimeStamp();
                double[] data_2 = simDataBlock_2.getData();
                timeResampledData = new double[data_1.length];
                // 
                for (int m = 0; m < data_1.length; m++) {
                    timeResampledData[m] = data_1[m] + (data_2[m] - data_1[m]) * (time - timeArray[timeArrayCounter]) / (timeArray[timeArrayCounter + 1] - timeArray[timeArrayCounter]);
                }
            } else {
                // past end of array, zero order interpolation
                lastModified = simDataBlock_1.getPDEDataInfo().getTimeStamp();
                timeResampledData = data_1;
            }
        }
        // SPATIAL INTERPOLATION
        CartesianMesh refMesh = null;
        CartesianMesh mesh = null;
        try {
            refMesh = getDatasetControllerImpl().getMesh(datasetsIDList[0]);
            mesh = getDatasetControllerImpl().getMesh(vcDataID);
        } catch (MathException e) {
            e.printStackTrace(System.out);
            throw new RuntimeException("Could not get Mesh for reference or given dataID");
        }
        double[] spaceResampledData = null;
        // Check origin and extent of reference and given dataset. If they don't match, cannot resample spatially
        if (!mesh.getExtent().compareEqual(refMesh.getExtent()) || !mesh.getOrigin().compareEqual(refMesh.getOrigin())) {
            throw new RuntimeException("Different origins and/or extents for the 2 geometries. Cannot compare the 2 simulations");
        }
        // Get dimension of geometry for reference and given datasets (using mesh variables!) to use appropriate
        // resampling algorithm. Check if mesh sizes for the 2 datasets are equal, then there is no need to
        // spatially resample the second dataset.
        int dimension = mesh.getGeometryDimension();
        int refDimension = refMesh.getGeometryDimension();
        if (mesh.getSizeX() != refMesh.getSizeX() || mesh.getSizeY() != refMesh.getSizeY() || mesh.getSizeZ() != refMesh.getSizeZ()) {
            if (varDatasetID.getVariableType().equals(VariableType.VOLUME)) {
                if (dimension == 1 && refDimension == 1) {
                    spaceResampledData = MathTestingUtilities.resample1DSpatial(timeResampledData, mesh, refMesh);
                } else if (dimension == 2 && refDimension == 2) {
                    spaceResampledData = MathTestingUtilities.resample2DSpatial(timeResampledData, mesh, refMesh);
                } else if (dimension == 3 && refDimension == 3) {
                    spaceResampledData = MathTestingUtilities.resample3DSpatial(timeResampledData, mesh, 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: " + varDatasetID.getVariableType().getTypeName() + " not supported");
            }
        } else {
            // 
            if (varDatasetID.getVariableType().equals(VariableType.MEMBRANE)) {
                // 
                if (membraneIndexMapping == null) {
                    membraneIndexMapping = mesh.getMembraneIndexMapping(refMesh);
                }
                spaceResampledData = new double[timeResampledData.length];
                for (int i = 0; i < timeResampledData.length; i++) {
                    spaceResampledData[i] = timeResampledData[membraneIndexMapping[i]];
                }
            } else {
                // 
                // no reordering needed for other variable types.
                // 
                spaceResampledData = timeResampledData;
            }
        }
        if (simDataBlk != null) {
            lastModified = simDataBlk.getPDEDataInfo().getTimeStamp();
        }
        PDEDataInfo pdeDataInfo = new PDEDataInfo(vcDataID.getOwner(), vcDataID.getID(), varName, time, lastModified);
        if (spaceResampledData != null) {
            return new SimDataBlock(pdeDataInfo, spaceResampledData, varDatasetID.getVariableType());
        } else {
            return null;
        }
    }
}
Also used : CartesianMesh(cbit.vcell.solvers.CartesianMesh) MathException(cbit.vcell.math.MathException) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier)

Aggregations

CartesianMesh (cbit.vcell.solvers.CartesianMesh)49 ISize (org.vcell.util.ISize)24 Extent (org.vcell.util.Extent)19 Origin (org.vcell.util.Origin)18 VariableType (cbit.vcell.math.VariableType)17 VCImageUncompressed (cbit.image.VCImageUncompressed)15 RegionImage (cbit.vcell.geometry.RegionImage)15 DataAccessException (org.vcell.util.DataAccessException)15 VCDataIdentifier (org.vcell.util.document.VCDataIdentifier)14 FieldDataFileOperationSpec (cbit.vcell.field.io.FieldDataFileOperationSpec)13 File (java.io.File)13 ExternalDataIdentifier (org.vcell.util.document.ExternalDataIdentifier)12 IOException (java.io.IOException)11 DataIdentifier (cbit.vcell.simdata.DataIdentifier)9 SimDataBlock (cbit.vcell.simdata.SimDataBlock)9 VCSimulationDataIdentifier (cbit.vcell.solver.VCSimulationDataIdentifier)9 VCImage (cbit.image.VCImage)8 UserCancelException (org.vcell.util.UserCancelException)8 Expression (cbit.vcell.parser.Expression)7 Vector (java.util.Vector)7