Search in sources :

Example 26 with CartesianMesh

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

the class ASCIIExporter method exportPDEData.

/**
 * This method was created in VisualAge.
 * @throws IOException
 */
private List<ExportOutput> exportPDEData(OutputContext outputContext, long jobID, User user, DataServerImpl dataServerImpl, final VCDataIdentifier orig_vcdID, VariableSpecs variableSpecs, TimeSpecs timeSpecs, GeometrySpecs geometrySpecs, ASCIISpecs asciiSpecs, String contextName, FileDataContainerManager fileDataContainerManager) throws DataAccessException, IOException {
    ExportSpecs.SimNameSimDataID[] simNameSimDataIDs = asciiSpecs.getSimNameSimDataIDs();
    Vector<ExportOutput[]> exportOutputV = new Vector<ExportOutput[]>();
    double progressCounter = 0;
    final int SIM_COUNT = simNameSimDataIDs.length;
    final int PARAMSCAN_COUNT = (asciiSpecs.getExportMultipleParamScans() != null ? asciiSpecs.getExportMultipleParamScans().length : 1);
    final int endTimeIndex = timeSpecs.getEndTimeIndex();
    final int beginTimeIndex = timeSpecs.getBeginTimeIndex();
    final int TIME_COUNT = endTimeIndex - beginTimeIndex + 1;
    double TOTAL_EXPORTS_OPS = 0;
    switch(geometrySpecs.getModeID()) {
        case GEOMETRY_SELECTIONS:
            TOTAL_EXPORTS_OPS = SIM_COUNT * PARAMSCAN_COUNT * variableSpecs.getVariableNames().length * (geometrySpecs.getCurves().length + (geometrySpecs.getPointCount() > 0 ? 1 : 0));
            break;
        case GEOMETRY_SLICE:
            TOTAL_EXPORTS_OPS = SIM_COUNT * PARAMSCAN_COUNT * variableSpecs.getVariableNames().length * TIME_COUNT;
            break;
    }
    if (asciiSpecs.getCSVRoiLayout() == ASCIISpecs.csvRoiLayout.time_sim_var) {
        exportOutputV.add(new ExportOutput[] { sofyaFormat(outputContext, jobID, user, dataServerImpl, orig_vcdID, variableSpecs, timeSpecs, geometrySpecs, asciiSpecs, contextName, fileDataContainerManager) });
    } else {
        for (int v = 0; v < SIM_COUNT; v++) {
            int simJobIndex = simNameSimDataIDs[v].getDefaultJobIndex();
            VCDataIdentifier vcdID = simNameSimDataIDs[v].getVCDataIdentifier(simJobIndex);
            // 3. simNameSimDataIDs[v].getExportParamScanInfo() != null and asciiSpecs.getExportMultipleParamScans() != null, parameter scan use simNameSimDataIDs[v].getExportParamScanInfo().getParamScanJobIndexes() loop through
            for (int ps = 0; ps < PARAMSCAN_COUNT; ps++) {
                if (asciiSpecs.getExportMultipleParamScans() != null) {
                    simJobIndex = simNameSimDataIDs[v].getExportParamScanInfo().getParamScanJobIndexes()[asciiSpecs.getExportMultipleParamScans()[ps]];
                    vcdID = simNameSimDataIDs[v].getVCDataIdentifier(simJobIndex);
                }
                // Get times for each sim{paramscan} because they may be different
                final double[] allTimes = dataServerImpl.getDataSetTimes(user, vcdID);
                if (allTimes.length <= beginTimeIndex || allTimes.length <= endTimeIndex) {
                    throw new DataAccessException("Sim '" + simNameSimDataIDs[v].getSimulationName() + "' id=" + vcdID.getID() + " simJob=" + simJobIndex + ", time array length=" + allTimes.length + " has no endTimeIndex=" + endTimeIndex);
                }
                String paramScanInfo = "";
                if (simNameSimDataIDs[v].getExportParamScanInfo() != null) {
                    for (int i = 0; i < simNameSimDataIDs[v].getExportParamScanInfo().getParamScanConstantNames().length; i++) {
                        String psName = simNameSimDataIDs[v].getExportParamScanInfo().getParamScanConstantNames()[i];
                        paramScanInfo = paramScanInfo + " '" + psName + "'=" + simNameSimDataIDs[v].getExportParamScanInfo().getParamScanConstantValues()[simJobIndex][i];
                    }
                }
                String simID = vcdID.getID();
                String dataType = ".csv";
                FileDataContainerID fileDataContainerID_header = fileDataContainerManager.getNewFileDataContainerID();
                SimulationDescription simulationDescription = new SimulationDescription(outputContext, user, dataServerImpl, vcdID, false, null);
                fileDataContainerManager.append(fileDataContainerID_header, "\"" + "Model: '" + contextName + "'\"\n\"Simulation: '" + simNameSimDataIDs[v].getSimulationName() + "' (" + paramScanInfo + ")\"\n" + simulationDescription.getHeader(dataType));
                switch(geometrySpecs.getModeID()) {
                    case GEOMETRY_SELECTIONS:
                        {
                            // Set mesh on SpatialSelection because mesh is transient field because it's too big for messaging
                            SpatialSelection[] spatialSelections = geometrySpecs.getSelections();
                            CartesianMesh mesh = dataServerImpl.getMesh(user, vcdID);
                            for (int i = 0; i < spatialSelections.length; i++) {
                                if (spatialSelections[i].getMesh() == null) {
                                    spatialSelections[i].setMesh(mesh);
                                } else if (!spatialSelections[i].getMesh().getISize().compareEqual(mesh.getISize()) || spatialSelections[i].getMesh().getNumMembraneElements() != mesh.getNumMembraneElements()) {
                                    // check just sizes not areas,normals,etc...
                                    // This will throw fail message
                                    spatialSelections[i].setMesh(mesh);
                                }
                            }
                            Vector<ExportOutput> outputV = new Vector<ExportOutput>();
                            if (geometrySpecs.getPointCount() > 0) {
                                // assemble single point data together (uses more compact formatting)
                                String dataID = "_Points_vars(" + geometrySpecs.getPointCount() + ")_times(" + (endTimeIndex - beginTimeIndex + 1) + ")";
                                // StringBuilder data1 = new StringBuilder(data.toString());
                                ExportOutput exportOutput1 = new ExportOutput(true, dataType, simID, dataID, /* + variableSpecs.getVariableNames()[i]*/
                                fileDataContainerManager);
                                fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), fileDataContainerID_header);
                                for (int i = 0; i < variableSpecs.getVariableNames().length; i++) {
                                    fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), getPointsTimeSeries(outputContext, user, dataServerImpl, vcdID, variableSpecs.getVariableNames()[i], geometrySpecs, allTimes, beginTimeIndex, endTimeIndex, asciiSpecs.getSwitchRowsColumns(), fileDataContainerManager));
                                    fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), "\n");
                                    progressCounter++;
                                    exportServiceImpl.fireExportProgress(jobID, orig_vcdID, "CSV", progressCounter / TOTAL_EXPORTS_OPS);
                                }
                                outputV.add(exportOutput1);
                            }
                            if (geometrySpecs.getCurves().length != 0) {
                                // assemble curve (non-single point) data together
                                String dataID = "_Curves_vars(" + (geometrySpecs.getCurves().length) + ")_times(" + (endTimeIndex - beginTimeIndex + 1) + ")";
                                // StringBuilder data1 = new StringBuilder(data.toString());
                                ExportOutput exportOutput1 = new ExportOutput(true, dataType, simID, dataID, /* + variableSpecs.getVariableNames()[i]*/
                                fileDataContainerManager);
                                fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), fileDataContainerID_header);
                                for (int i = 0; i < variableSpecs.getVariableNames().length; i++) {
                                    for (int s = 0; s < geometrySpecs.getCurves().length; s++) {
                                        if (!GeometrySpecs.isSinglePoint(geometrySpecs.getCurves()[s])) {
                                            fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), getCurveTimeSeries(outputContext, user, dataServerImpl, vcdID, variableSpecs.getVariableNames()[i], geometrySpecs.getCurves()[s], allTimes, beginTimeIndex, endTimeIndex, asciiSpecs.getSwitchRowsColumns(), fileDataContainerManager));
                                            fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), "\n");
                                            progressCounter++;
                                            exportServiceImpl.fireExportProgress(jobID, orig_vcdID, "CSV", progressCounter / TOTAL_EXPORTS_OPS);
                                        }
                                    }
                                }
                                outputV.add(exportOutput1);
                            }
                            exportOutputV.add(outputV.toArray(new ExportOutput[0]));
                            break;
                        }
                    case GEOMETRY_SLICE:
                        {
                            String dataID = "_Slice_" + Coordinate.getNormalAxisPlaneName(geometrySpecs.getAxis()) + "_" + geometrySpecs.getSliceNumber() + "_";
                            ExportOutput[] output = new ExportOutput[variableSpecs.getVariableNames().length * TIME_COUNT];
                            for (int j = 0; j < variableSpecs.getVariableNames().length; j++) {
                                for (int i = 0; i < TIME_COUNT; i++) {
                                    StringBuilder inset = new StringBuilder(Integer.toString(i + beginTimeIndex));
                                    inset.reverse();
                                    inset.append("000");
                                    inset.setLength(4);
                                    inset.reverse();
                                    String dataID1 = dataID + variableSpecs.getVariableNames()[j] + "_" + inset.toString();
                                    ExportOutput exportOutput1 = new ExportOutput(true, dataType, simID, dataID1, /* + variableSpecs.getVariableNames()[i]*/
                                    fileDataContainerManager);
                                    fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), fileDataContainerID_header);
                                    fileDataContainerManager.append(exportOutput1.getFileDataContainerID(), getSlice(outputContext, user, dataServerImpl, vcdID, variableSpecs.getVariableNames()[j], i + beginTimeIndex, Coordinate.getNormalAxisPlaneName(geometrySpecs.getAxis()), geometrySpecs.getSliceNumber(), asciiSpecs.getSwitchRowsColumns(), fileDataContainerManager));
                                    output[j * TIME_COUNT + i] = exportOutput1;
                                    progressCounter++;
                                    exportServiceImpl.fireExportProgress(jobID, orig_vcdID, "CSV", progressCounter / TOTAL_EXPORTS_OPS);
                                // data1.cleanup();
                                // data2.cleanup();
                                }
                            }
                            exportOutputV.add(output);
                            break;
                        }
                    default:
                        {
                            throw new DataAccessException("Unexpected geometry modeID");
                        }
                }
            }
        }
    }
    if (exportOutputV.size() == 1) {
        // geometry_slice
        return Arrays.asList(exportOutputV.elementAt(0));
    }
    // geometry_selections (all are same length as first element)
    ArrayList<ExportOutput> combinedExportOutput = new ArrayList<>();
    for (int i = 0; i < exportOutputV.elementAt(0).length; i++) {
        String DATATYPE = exportOutputV.elementAt(0)[i].getDataType();
        String DATAID = exportOutputV.elementAt(0)[i].getDataID();
        ExportOutput eo = new ExportOutput(true, DATATYPE, "MultiSimulation", DATAID, fileDataContainerManager);
        // FileDataContainer container = fileDataContainerManager.getFileDataContainer(combinedExportOutput[i].getFileDataContainerID());
        for (int j = 0; j < exportOutputV.size(); j++) {
            fileDataContainerManager.append(eo.getFileDataContainerID(), exportOutputV.elementAt(j)[i].getFileDataContainerID());
            fileDataContainerManager.append(eo.getFileDataContainerID(), "\n");
        }
        combinedExportOutput.add(eo);
    }
    return combinedExportOutput;
}
Also used : ArrayList(java.util.ArrayList) SinglePoint(cbit.vcell.geometry.SinglePoint) CartesianMesh(cbit.vcell.solvers.CartesianMesh) FileDataContainerID(cbit.vcell.export.server.FileDataContainerManager.FileDataContainerID) Vector(java.util.Vector) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) DataAccessException(org.vcell.util.DataAccessException)

Example 27 with CartesianMesh

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

the class PDEOffscreenRenderer method getPixelsRGB.

/**
 * Insert the method's description here.
 * Creation date: (3/1/2001 11:54:44 PM)
 * @return int[]
 */
public int[] getPixelsRGB(int imageScale, int membrScale, int meshMode, int volVarMembrOutlineThickness) {
    if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.VOLUME) || getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING)) {
        CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh();
        MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh);
        BufferedImage bufferedImage = getScaledRGBVolume(mesh, meshMode, imageScale, false);
        // 
        if (!getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.POSTPROCESSING) && volVarMembrOutlineThickness > 0) {
            cbit.vcell.geometry.CurveRenderer curveRenderer = new cbit.vcell.geometry.CurveRenderer(getDisplayAdapterService());
            curveRenderer.setNormalAxis(getNormalAxis());
            org.vcell.util.Origin origin = mesh.getOrigin();
            org.vcell.util.Extent extent = mesh.getExtent();
            curveRenderer.setWorldOrigin(new org.vcell.util.Coordinate(origin.getX(), origin.getY(), origin.getZ()));
            Coordinate pixeldelta = getPixelDelta(extent, mesh, meshMode, imageScale);
            curveRenderer.setWorldDelta(new org.vcell.util.Coordinate(pixeldelta.getX(), pixeldelta.getY(), pixeldelta.getZ()));
            Hashtable<SampledCurve, int[]> curvesAndMembraneIndexes = meshDisplayAdapter.getCurvesAndMembraneIndexes(getNormalAxis(), getSlice());
            if (curvesAndMembraneIndexes != null) {
                Curve[] curves = (Curve[]) org.vcell.util.BeanUtils.getArray(curvesAndMembraneIndexes.keys(), Curve.class);
                for (int i = 0; curves != null && i < curves.length; i++) {
                    curveRenderer.addCurve(curves[i]);
                    curveRenderer.renderPropertySegmentColors(curves[i], null);
                    curveRenderer.renderPropertyLineWidthMultiplier(curves[i], volVarMembrOutlineThickness);
                }
                Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
                // must be false or could get more than 256 colors
                curveRenderer.setAntialias(false);
                curveRenderer.draw(g);
            }
        }
        return ((DataBufferInt) bufferedImage.getData().getDataBuffer()).getData();
    } else if (getServerPDEDataContext().getDataIdentifier().getVariableType().equals(VariableType.MEMBRANE)) {
        CartesianMesh mesh = getServerPDEDataContext().getCartesianMesh();
        MeshDisplayAdapter meshDisplayAdapter = new MeshDisplayAdapter(mesh);
        BufferedImage bufferedImage = getScaledRGBVolume(mesh, meshMode, imageScale, true);
        // 
        // apply curve renderer
        // 
        cbit.vcell.geometry.CurveRenderer curveRenderer = new cbit.vcell.geometry.CurveRenderer(getDisplayAdapterService());
        curveRenderer.setNormalAxis(getNormalAxis());
        org.vcell.util.Origin origin = mesh.getOrigin();
        org.vcell.util.Extent extent = mesh.getExtent();
        curveRenderer.setWorldOrigin(new org.vcell.util.Coordinate(origin.getX(), origin.getY(), origin.getZ()));
        Coordinate pixeldelta = getPixelDelta(extent, mesh, meshMode, imageScale);
        curveRenderer.setWorldDelta(new org.vcell.util.Coordinate(pixeldelta.getX(), pixeldelta.getY(), pixeldelta.getZ()));
        Hashtable<SampledCurve, int[]> curvesAndMembraneIndexes = meshDisplayAdapter.getCurvesAndMembraneIndexes(getNormalAxis(), getSlice());
        if (curvesAndMembraneIndexes != null) {
            Curve[] curves = (Curve[]) org.vcell.util.BeanUtils.getArray(curvesAndMembraneIndexes.keys(), Curve.class);
            for (int i = 0; curves != null && i < curves.length; i++) {
                curveRenderer.addCurve(curves[i]);
                curveRenderer.renderPropertySegmentColors(curves[i], getCurveColors(curvesAndMembraneIndexes, curves[i], meshDisplayAdapter));
                curveRenderer.renderPropertyLineWidthMultiplier(curves[i], membrScale);
            }
            Graphics2D g = (Graphics2D) bufferedImage.getGraphics();
            curveRenderer.setAntialias(false);
            curveRenderer.draw(g);
        }
        return ((DataBufferInt) bufferedImage.getData().getDataBuffer()).getData();
    } else {
        throw new RuntimeException("unsupported VariableType " + getServerPDEDataContext().getDataIdentifier().getVariableType());
    }
}
Also used : Extent(org.vcell.util.Extent) DataBufferInt(java.awt.image.DataBufferInt) BufferedImage(java.awt.image.BufferedImage) MeshDisplayAdapter(cbit.vcell.solvers.MeshDisplayAdapter) SampledCurve(cbit.vcell.geometry.SampledCurve) Hashtable(java.util.Hashtable) Curve(cbit.vcell.geometry.Curve) SampledCurve(cbit.vcell.geometry.SampledCurve) Extent(org.vcell.util.Extent) Graphics2D(java.awt.Graphics2D) Coordinate(org.vcell.util.Coordinate) CartesianMesh(cbit.vcell.solvers.CartesianMesh) Coordinate(org.vcell.util.Coordinate)

Example 28 with CartesianMesh

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

the class ClientRequestManager method createNewGeometryTasks.

public AsynchClientTask[] createNewGeometryTasks(final TopLevelWindowManager requester, final VCDocument.DocumentCreationInfo documentCreationInfo, final AsynchClientTask[] afterTasks, final String okButtonText) {
    if (!isImportGeometryType(documentCreationInfo)) {
        throw new IllegalArgumentException("Analytic geometry not implemented.");
    }
    final String IMPORT_SOURCE_NAME = "IMPORT_SOURCE_NAME";
    // Get image from file
    AsynchClientTask selectImageFileTask = new AsynchClientTask("select image file", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            File imageFile = DatabaseWindowManager.showFileChooserDialog(requester, null, getUserPreferences(), JFileChooser.FILES_AND_DIRECTORIES);
            hashTable.put("imageFile", imageFile);
            hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getName());
        }
    };
    final String FDFOS = "FDFOS";
    final String INITIAL_ANNOTATION = "INITIAL_ANNOTATION";
    final String ORIG_IMAGE_SIZE_INFO = "ORIG_IMAGE_SIZE_INFO";
    final String NEW_IMAGE_SIZE_INFO = "NEW_IMAGE_SIZE_INFO";
    final String DIR_FILES = "DIR_FILES";
    final String FD_MESH = "FD_MESH";
    final String FD_MESHISIZE = "FD_MESHISIZE";
    final String FD_TIMEPOINTS = "FD_TIMEPOINTS";
    AsynchClientTask parseImageTask = new AsynchClientTask("read and parse image file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(final Hashtable<String, Object> hashTable) throws Exception {
            final Component guiParent = (Component) hashTable.get(ClientRequestManager.GUI_PARENT);
            try {
                FieldDataFileOperationSpec fdfos = null;
                if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ) {
                    hashTable.put("imageFile", ImageJHelper.vcellWantImage(getClientTaskStatusSupport(), "Image for new VCell geometry"));
                }
                if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER) {
                    hashTable.put("imageFile", ImageJHelper.vcellWantSurface(getClientTaskStatusSupport(), "Image for new VCell geometry"));
                }
                if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER) {
                    File imageFile = (File) hashTable.get("imageFile");
                    if (imageFile == null) {
                        throw new Exception("No file selected");
                    }
                    if (ExtensionFilter.isMatchingExtension(imageFile, ".nrrd")) {
                        DataInputStream dis = null;
                        try {
                            dis = new DataInputStream(new BufferedInputStream(new FileInputStream(imageFile)));
                            int xsize = 1;
                            int ysize = 1;
                            int zsize = 1;
                            double xspace = 1.0;
                            double yspace = 1.0;
                            double zspace = 1.0;
                            NRRDTYPE type = null;
                            NRRDENCODING encoding = null;
                            int dimension = -1;
                            // read header lines
                            while (true) {
                                @SuppressWarnings("deprecation") String line = dis.readLine();
                                if (line == null || line.length() == 0) {
                                    break;
                                }
                                StringTokenizer stringTokenizer = new StringTokenizer(line, ": ");
                                String headerParam = stringTokenizer.nextToken();
                                // System.out.println(headerParam);
                                if (headerParam.equals("sizes")) {
                                    if (dimension != -1) {
                                        xsize = Integer.parseInt(stringTokenizer.nextToken());
                                        if (dimension >= 2) {
                                            ysize = Integer.parseInt(stringTokenizer.nextToken());
                                        }
                                        if (dimension >= 3) {
                                            zsize = Integer.parseInt(stringTokenizer.nextToken());
                                        }
                                        for (int i = 4; i < dimension; i++) {
                                            if (Integer.parseInt(stringTokenizer.nextToken()) != 1) {
                                                throw new Exception("Dimensions > 3 not supported");
                                            }
                                        }
                                    } else {
                                        throw new Exception("dimension expected to be set before reading sizes");
                                    }
                                } else if (headerParam.equals("spacings")) {
                                    if (dimension != -1) {
                                        xspace = Double.parseDouble(stringTokenizer.nextToken());
                                        if (dimension >= 2) {
                                            yspace = Double.parseDouble(stringTokenizer.nextToken());
                                        }
                                        if (dimension >= 3) {
                                            zspace = Double.parseDouble(stringTokenizer.nextToken());
                                        }
                                    // ignore other dimension spacings
                                    } else {
                                        throw new Exception("dimension expected to be set before reading spacings");
                                    }
                                } else if (headerParam.equals("type")) {
                                    String nextToken = stringTokenizer.nextToken();
                                    if (nextToken.equalsIgnoreCase("double")) {
                                        type = NRRDTYPE.DOUBLE;
                                    } else if (nextToken.equalsIgnoreCase("float")) {
                                        type = NRRDTYPE.FLOAT;
                                    } else if (nextToken.equalsIgnoreCase("unsigned")) {
                                        nextToken = stringTokenizer.nextToken();
                                        if (nextToken.equalsIgnoreCase("char")) {
                                            type = NRRDTYPE.UNSIGNEDCHAR;
                                        } else {
                                            throw new Exception("Unknown nrrd data type=" + nextToken);
                                        }
                                    } else {
                                        throw new Exception("Unknown nrrd data type=" + nextToken);
                                    }
                                } else if (headerParam.equals("dimension")) {
                                    dimension = Integer.parseInt(stringTokenizer.nextToken());
                                    if (dimension < 1) {
                                        throw new Exception("unexpected dimension=" + dimension);
                                    }
                                } else if (headerParam.equals("encoding")) {
                                    encoding = NRRDENCODING.valueOf(stringTokenizer.nextToken().toUpperCase());
                                }
                            }
                            BufferedInputStream bis = null;
                            if (encoding == NRRDENCODING.GZIP) {
                                dis.close();
                                bis = new BufferedInputStream(new FileInputStream(imageFile));
                                boolean bnewLine = false;
                                while (true) {
                                    int currentChar = bis.read();
                                    if (currentChar == '\n') {
                                        if (bnewLine) {
                                            // 2 newlines end header
                                            break;
                                        }
                                        bnewLine = true;
                                    } else {
                                        bnewLine = false;
                                    }
                                }
                                GZIPInputStream gzipInputStream = new GZIPInputStream(bis);
                                dis = new DataInputStream(gzipInputStream);
                            }
                            double[] data = new double[xsize * ysize * zsize];
                            double minValue = Double.POSITIVE_INFINITY;
                            double maxValue = Double.NEGATIVE_INFINITY;
                            for (int i = 0; i < data.length; i++) {
                                if (i % 262144 == 0) {
                                    if (getClientTaskStatusSupport() != null) {
                                        getClientTaskStatusSupport().setMessage("Reading " + encoding + " " + type + " NRRD data " + (((long) i * (long) 100) / (long) data.length) + " % done.");
                                    }
                                }
                                if (type == NRRDTYPE.DOUBLE) {
                                    data[i] = dis.readDouble();
                                } else if (type == NRRDTYPE.FLOAT) {
                                    data[i] = dis.readFloat();
                                } else if (type == NRRDTYPE.UNSIGNEDCHAR) {
                                    data[i] = dis.readUnsignedByte();
                                } else {
                                    throw new Exception("Unexpected data type=" + type.toString());
                                }
                                minValue = Math.min(minValue, data[i]);
                                maxValue = Math.max(maxValue, data[i]);
                            }
                            dis.close();
                            if (getClientTaskStatusSupport() != null) {
                                getClientTaskStatusSupport().setMessage("Scaling " + encoding + " " + type + " NRRD data.");
                            }
                            short[] dataToSegment = new short[data.length];
                            double scaleShort = Math.pow(2, Short.SIZE) - 1;
                            for (int i = 0; i < data.length; i++) {
                                dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
                            }
                            fdfos = new FieldDataFileOperationSpec();
                            fdfos.origin = new Origin(0, 0, 0);
                            fdfos.extent = new Extent((xsize == 1 ? .5 : (xsize) * xspace), (ysize == 1 ? .5 : (ysize) * yspace), (zsize == 1 ? .5 : (zsize) * zspace));
                            fdfos.isize = new ISize(xsize, ysize, zsize);
                            fdfos.shortSpecData = new short[][][] { { dataToSegment } };
                        } finally {
                            if (dis != null) {
                                try {
                                    dis.close();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } else if ((fdfos = createFDOSFromSurfaceFile(imageFile)) != null) {
                    // try surface file formats
                    // work already done at this point
                    } else {
                        File[] dirFiles = null;
                        ImageSizeInfo origImageSizeInfo = null;
                        if (imageFile.isDirectory()) {
                            dirFiles = imageFile.listFiles(new java.io.FileFilter() {

                                public boolean accept(File pathname) {
                                    // exclude windows Thumbs.db
                                    return pathname.isFile() && !pathname.isHidden();
                                }
                            });
                            if (dirFiles.length == 0) {
                                throw new Exception("No valid files in selected directory");
                            }
                            String fileExt0 = null;
                            for (int i = 0; i < dirFiles.length; i++) {
                                int lastDot = dirFiles[i].getName().lastIndexOf('.');
                                String fileExt = (lastDot != -1 ? dirFiles[i].getName().substring(lastDot) : null);
                                if (dirFiles[i].isDirectory()) {
                                    fileExt = "dir";
                                }
                                if (i == 0) {
                                    fileExt0 = fileExt;
                                } else if (!Compare.isEqualOrNull(fileExt, fileExt0)) {
                                    String result = DialogUtils.showWarningDialog(requester.getComponent(), "Files in '" + imageFile.getAbsolutePath() + "' have different name extensions, continue?", new String[] { "OK", "Cancel" }, "Cancel");
                                    if (!"OK".equals(result)) {
                                        throw UserCancelException.CANCEL_FILE_SELECTION;
                                    }
                                    break;
                                }
                            }
                            hashTable.put(IMPORT_SOURCE_NAME, "Directory: " + imageFile.getAbsolutePath());
                            origImageSizeInfo = ImageDatasetReaderService.getInstance().getImageDatasetReader().getImageSizeInfoForceZ(dirFiles[0].getAbsolutePath(), dirFiles.length);
                            if (dirFiles.length > 1) {
                                final String importZ = "Import Z-Sections";
                                final String cancelOption = "Cancel";
                                String result = DialogUtils.showWarningDialog(guiParent, "Import all files in directory '" + imageFile.getAbsolutePath() + "' as Z-Sections", new String[] { importZ, cancelOption }, importZ);
                                if (result.equals(cancelOption)) {
                                    throw UserCancelException.CANCEL_GENERIC;
                                }
                            }
                            hashTable.put(DIR_FILES, dirFiles);
                        } else {
                            origImageSizeInfo = ImageDatasetReaderService.getInstance().getImageDatasetReader().getImageSizeInfo(imageFile.getAbsolutePath());
                            hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getAbsolutePath());
                        }
                        hashTable.put(ORIG_IMAGE_SIZE_INFO, origImageSizeInfo);
                        return;
                    }
                } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
                    getClientTaskStatusSupport().setMessage("Reading data from VCell server.");
                    VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
                    PDEDataContext pdeDataContext = getMdiManager().getFieldDataWindowManager().getPDEDataContext(docInfo.getExternalDataID(), null);
                    ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
                    pdeDataContext.setVariableNameAndTime(docInfo.getVarName(), newImageSizeInfo.getTimePoints()[newImageSizeInfo.getSelectedTimeIndex()]);
                    double[] data = pdeDataContext.getDataValues();
                    hashTable.put(INITIAL_ANNOTATION, hashTable.get(IMPORT_SOURCE_NAME));
                    CartesianMesh mesh = (CartesianMesh) hashTable.get(FD_MESH);
                    ISize meshISize = (ISize) hashTable.get(FD_MESHISIZE);
                    double minValue = Double.POSITIVE_INFINITY;
                    double maxValue = Double.NEGATIVE_INFINITY;
                    for (int i = 0; i < data.length; i++) {
                        minValue = Math.min(minValue, data[i]);
                        maxValue = Math.max(maxValue, data[i]);
                    }
                    short[] dataToSegment = new short[data.length];
                    double scaleShort = Math.pow(2, Short.SIZE) - 1;
                    for (int i = 0; i < data.length; i++) {
                        dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
                    }
                    fdfos = new FieldDataFileOperationSpec();
                    fdfos.origin = mesh.getOrigin();
                    fdfos.extent = mesh.getExtent();
                    fdfos.isize = meshISize;
                    fdfos.shortSpecData = new short[][][] { { dataToSegment } };
                } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
                    ISize isize = getISizeFromUser(guiParent, new ISize(256, 256, 8), "Enter # of pixels for  x,y,z (e.g. 3D{256,256,8}, 2D{256,256,1}, 1D{256,1,1})");
                    fdfos = new FieldDataFileOperationSpec();
                    fdfos.origin = new Origin(0, 0, 0);
                    fdfos.extent = new Extent(1, 1, 1);
                    fdfos.isize = isize;
                    hashTable.put(IMPORT_SOURCE_NAME, "Scratch: New Geometry");
                // final int SCRATCH_SIZE_LIMIT = 512*512*20;
                // if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){
                // throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+".");
                // }
                } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
                    if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
                        Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
                        ISize defaultISize = workspaceGeom.getGeometrySpec().getDefaultSampledImageSize();
                        ISize isize = getISizeFromUser(guiParent, defaultISize, "Warning: converting analytic expression geometry into an image based geometry\nwill remove analytic expressions after new image is created.\n\n" + "Enter size (x,y,z) for new geometry image (e.g. " + defaultISize.getX() + "," + defaultISize.getY() + "," + defaultISize.getZ() + ")");
                        hashTable.put(IMPORT_SOURCE_NAME, "Workspace from Analytic Geometry");
                        VCImage img = workspaceGeom.getGeometrySpec().createSampledImage(isize);
                        Enumeration<SubVolume> enumSubvolume = workspaceGeom.getGeometrySpec().getAnalyticOrCSGSubVolumes();
                        ArrayList<VCPixelClass> vcPixelClassArrList = new ArrayList<VCPixelClass>();
                        while (enumSubvolume.hasMoreElements()) {
                            SubVolume subVolume = enumSubvolume.nextElement();
                            vcPixelClassArrList.add(new VCPixelClass(null, subVolume.getName(), subVolume.getHandle()));
                        }
                        if (vcPixelClassArrList.size() > img.getPixelClasses().length) {
                            String result = DialogUtils.showOKCancelWarningDialog(requester.getComponent(), null, "Warning: sampling size is too small to include all subvolumes.");
                            if (result == null || !result.equals(SimpleUserMessage.OPTION_OK)) {
                                throw UserCancelException.CANCEL_GENERIC;
                            }
                        }
                        hashTable.put(VCPIXELCLASSES, vcPixelClassArrList.toArray(new VCPixelClass[0]));
                        fdfos = createFDOSFromVCImage(img);
                    } else {
                        throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE_ANALYTIC");
                    }
                } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
                    if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
                        Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
                        hashTable.put(IMPORT_SOURCE_NAME, "Workspace Image");
                        fdfos = createFDOSFromVCImage(workspaceGeom.getGeometrySpec().getImage());
                        if (workspaceGeom.getGeometrySpec().getImage().getDescription() != null) {
                            hashTable.put(INITIAL_ANNOTATION, workspaceGeom.getGeometrySpec().getImage().getDescription());
                        }
                        hashTable.put(VCPIXELCLASSES, workspaceGeom.getGeometrySpec().getImage().getPixelClasses());
                    } else {
                        throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE");
                    }
                }
                hashTable.put(FDFOS, fdfos);
            } catch (DataFormatException ex) {
                throw new Exception("Cannot read image file.\n" + ex.getMessage());
            }
        }
    };
    AsynchClientTask getFieldDataImageParams = new AsynchClientTask("Getting DB Image parameters...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
            PDEDataContext pdeDataContext = getMdiManager().getFieldDataWindowManager().getPDEDataContext(docInfo.getExternalDataID(), null);
            CartesianMesh mesh = pdeDataContext.getCartesianMesh();
            ISize meshISize = new ISize(mesh.getSizeX(), mesh.getSizeY(), mesh.getSizeZ());
            double[] timePoints = pdeDataContext.getTimePoints();
            hashTable.put(FD_MESH, mesh);
            hashTable.put(FD_MESHISIZE, meshISize);
            hashTable.put(FD_TIMEPOINTS, timePoints);
        }
    };
    AsynchClientTask queryImageResizeTask = new AsynchClientTask("Query File Image Resize...", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            String importSourceName = (String) hashTable.get(IMPORT_SOURCE_NAME);
            if ((ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO) != null) {
                // from file
                ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(), (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO), true);
                hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
            } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
                // from fielddata
                VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
                double[] fieldDataTimes = (double[]) hashTable.get(FD_TIMEPOINTS);
                hashTable.remove(FD_TIMEPOINTS);
                ISize fieldDataISize = (ISize) hashTable.get(FD_MESHISIZE);
                ImageSizeInfo origImageSizeInfo = new ImageSizeInfo(importSourceName, fieldDataISize, 1, fieldDataTimes, null);
                ImageSizeInfo newImagesiSizeInfo = queryImageResize(requester.getComponent(), origImageSizeInfo, true);
                hashTable.put(NEW_IMAGE_SIZE_INFO, newImagesiSizeInfo);
                hashTable.put(IMPORT_SOURCE_NAME, "FieldData: " + docInfo.getExternalDataID().getName() + " varName=" + docInfo.getVarName() + " timeIndex=" + newImagesiSizeInfo.getTimePoints()[newImagesiSizeInfo.getSelectedTimeIndex()]);
            }
        }
    };
    AsynchClientTask importFileImageTask = new AsynchClientTask("Importing Image from File...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE && hashTable.get(FDFOS) == null) {
                ImageSizeInfo origImageSizeInfo = (ImageSizeInfo) hashTable.get(ORIG_IMAGE_SIZE_INFO);
                ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
                File[] dirFiles = (File[]) hashTable.get(DIR_FILES);
                File imageFile = (File) hashTable.get("imageFile");
                FieldDataFileOperationSpec fdfos = null;
                boolean bMergeChannels = origImageSizeInfo.getNumChannels() != newImageSizeInfo.getNumChannels();
                ISize resize = (origImageSizeInfo.getiSize().compareEqual(newImageSizeInfo.getiSize()) ? null : newImageSizeInfo.getiSize());
                if (dirFiles != null) {
                    Arrays.sort(dirFiles, new Comparator<File>() {

                        public int compare(File o1, File o2) {
                            return o1.getName().compareToIgnoreCase(o2.getName());
                        }
                    });
                    hashTable.put(INITIAL_ANNOTATION, dirFiles[0].getAbsolutePath() + "\n.\n.\n.\n" + dirFiles[dirFiles.length - 1].getAbsolutePath());
                    short[][] dataToSegment = null;
                    ISize isize = null;
                    Origin origin = null;
                    Extent extent = null;
                    int sizeXY = 0;
                    ISize firstImageISize = null;
                    for (int i = 0; i < dirFiles.length; i++) {
                        ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance().getImageDatasetReader().readImageDatasetChannels(dirFiles[i].getAbsolutePath(), null, bMergeChannels, null, resize);
                        for (int c = 0; c < imageDatasets.length; c++) {
                            if (imageDatasets[c].getSizeZ() != 1 || imageDatasets[c].getSizeT() != 1) {
                                throwImportWholeDirectoryException(imageFile, dirFiles[i].getAbsolutePath() + " has Z=" + imageDatasets[c].getSizeZ() + " T=" + imageDatasets[c].getSizeT());
                            }
                            if (isize == null) {
                                firstImageISize = imageDatasets[c].getISize();
                                sizeXY = imageDatasets[c].getISize().getX() * imageDatasets[c].getISize().getY();
                                dataToSegment = new short[imageDatasets.length][sizeXY * dirFiles.length];
                                isize = new ISize(imageDatasets[c].getISize().getX(), imageDatasets[c].getISize().getY(), dirFiles.length);
                                origin = imageDatasets[c].getAllImages()[0].getOrigin();
                                extent = imageDatasets[c].getExtent();
                            }
                            if (!firstImageISize.compareEqual(imageDatasets[c].getISize())) {
                                throwImportWholeDirectoryException(imageFile, dirFiles[0].getAbsolutePath() + " " + firstImageISize + " does not equal " + dirFiles[i].getAbsolutePath() + " " + imageDatasets[c].getISize());
                            }
                            System.arraycopy(imageDatasets[c].getImage(0, 0, 0).getPixels(), 0, dataToSegment[c], sizeXY * i, sizeXY);
                        }
                    }
                    fdfos = new FieldDataFileOperationSpec();
                    fdfos.origin = origin;
                    fdfos.extent = extent;
                    fdfos.isize = isize;
                    fdfos.shortSpecData = new short[][][] { dataToSegment };
                } else {
                    hashTable.put(INITIAL_ANNOTATION, imageFile.getAbsolutePath());
                    Integer userPreferredTimeIndex = null;
                    if (origImageSizeInfo.getTimePoints().length > 1) {
                        userPreferredTimeIndex = newImageSizeInfo.getSelectedTimeIndex();
                    }
                    getClientTaskStatusSupport().setMessage("Reading file...");
                    ImageDataset[] imageDatasets = ImageDatasetReaderService.getInstance().getImageDatasetReader().readImageDatasetChannels(imageFile.getAbsolutePath(), null, bMergeChannels, userPreferredTimeIndex, resize);
                    fdfos = ClientRequestManager.createFDOSWithChannels(imageDatasets, null);
                }
                hashTable.put(FDFOS, fdfos);
                hashTable.remove(NEW_IMAGE_SIZE_INFO);
                hashTable.remove(ORIG_IMAGE_SIZE_INFO);
                hashTable.remove(DIR_FILES);
            }
        }
    };
    AsynchClientTask resizeImageTask = new AsynchClientTask("Resizing Image...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
            FieldDataFileOperationSpec fdfos = (FieldDataFileOperationSpec) hashTable.get(FDFOS);
            if (newImageSizeInfo != null && fdfos != null && !fdfos.isize.compareEqual(newImageSizeInfo.getiSize())) {
                resizeImage((FieldDataFileOperationSpec) hashTable.get(FDFOS), newImageSizeInfo.getiSize(), documentCreationInfo.getOption());
            }
        }
    };
    AsynchClientTask finishTask = new AsynchClientTask("Finishing...", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(final Hashtable<String, Object> hashTable) throws Exception {
            getClientTaskStatusSupport().setMessage("Initializing...");
            final ROIMultiPaintManager roiMultiPaintManager = new ROIMultiPaintManager();
            roiMultiPaintManager.initROIData((FieldDataFileOperationSpec) hashTable.get(FDFOS));
            final Geometry[] geomHolder = new Geometry[1];
            final VCPixelClass[] postProcessPixelClasses = (VCPixelClass[]) hashTable.get(VCPIXELCLASSES);
            AsynchClientTask task1 = new AsynchClientTask("edit geometry", AsynchClientTask.TASKTYPE_SWING_BLOCKING, false) {

                @Override
                public void run(Hashtable<String, Object> hashTable) throws Exception {
                    geomHolder[0] = roiMultiPaintManager.showGUI(okButtonText, (String) hashTable.get(IMPORT_SOURCE_NAME), (Component) hashTable.get(GUI_PARENT), (String) hashTable.get(INITIAL_ANNOTATION), postProcessPixelClasses, getUserPreferences());
                }
            };
            AsynchClientTask task2 = new AsynchClientTask("update geometry", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

                @Override
                public void run(Hashtable<String, Object> hashTable) throws Exception {
                    // Create default name for image
                    String dateTimeString = BeanUtils.generateDateTimeString();
                    geomHolder[0].getGeometrySpec().getImage().setName("img_" + dateTimeString);
                    geomHolder[0].setName("geom_" + dateTimeString);
                    // cause update in this thread so later swing threads won't be delayed
                    geomHolder[0].precomputeAll(new GeometryThumbnailImageFactoryAWT());
                    hashTable.put("doc", geomHolder[0]);
                }
            };
            AsynchClientTask[] finalTasks = afterTasks;
            if (finalTasks == null) {
                finalTasks = new AsynchClientTask[] { getSaveImageAndGeometryTask() };
            }
            AsynchClientTask[] tasks = new AsynchClientTask[2 + finalTasks.length];
            tasks[0] = task1;
            tasks[1] = task2;
            System.arraycopy(finalTasks, 0, tasks, 2, finalTasks.length);
            ClientTaskDispatcher.dispatch((Component) hashTable.get(GUI_PARENT), hashTable, tasks, false, false, null, true);
        }
    };
    Vector<AsynchClientTask> tasksV = new Vector<AsynchClientTask>();
    if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, finishTask }));
    } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, finishTask }));
    } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, finishTask }));
    } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { selectImageFileTask, parseImageTask, queryImageResizeTask, importFileImageTask, /*resizes*/
        finishTask }));
    } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { parseImageTask, queryImageResizeTask, importFileImageTask, /*resizes*/
        finishTask }));
    } else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
        tasksV.addAll(Arrays.asList(new AsynchClientTask[] { getFieldDataImageParams, queryImageResizeTask, parseImageTask, resizeImageTask, finishTask }));
    }
    return tasksV.toArray(new AsynchClientTask[0]);
}
Also used : BngUnitOrigin(org.vcell.model.bngl.BngUnitSystem.BngUnitOrigin) Origin(org.vcell.util.Origin) VCPixelClass(cbit.image.VCPixelClass) FieldDataFileOperationSpec(cbit.vcell.field.io.FieldDataFileOperationSpec) ArrayList(java.util.ArrayList) BufferedInputStream(java.io.BufferedInputStream) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) Vector(java.util.Vector) VCDocument(org.vcell.util.document.VCDocument) ROIMultiPaintManager(cbit.vcell.geometry.gui.ROIMultiPaintManager) FileInputStream(java.io.FileInputStream) ImageSizeInfo(cbit.image.ImageSizeInfo) CartesianMesh(cbit.vcell.solvers.CartesianMesh) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File) PDEDataContext(cbit.vcell.simdata.PDEDataContext) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) ImageDataset(cbit.vcell.VirtualMicroscopy.ImageDataset) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) VCImage(cbit.image.VCImage) GZIPInputStream(java.util.zip.GZIPInputStream) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) Component(java.awt.Component) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) DataInputStream(java.io.DataInputStream) ProgrammingException(org.vcell.util.ProgrammingException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) DataFormatException(java.util.zip.DataFormatException) UserCancelException(org.vcell.util.UserCancelException) Geometry(cbit.vcell.geometry.Geometry) StringTokenizer(java.util.StringTokenizer) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) DataFormatException(java.util.zip.DataFormatException)

Example 29 with CartesianMesh

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

the class PDEExportDataPanel method startExport.

/**
 * Comment
 */
private void startExport() {
    if (getExportSettings1().getSelectedFormat() == ExportFormat.QUICKTIME && getJSlider1().getValue() == getJSlider2().getValue()) {
        DialogUtils.showWarningDialog(this, "User selected 'begin' and 'end' export times are the same.  'Movie' export format 'begin' and 'end' times must be different");
        return;
    }
    DisplayPreferences[] displayPreferences = null;
    @SuppressWarnings("deprecation") Object[] variableSelections = getJListVariables().getSelectedValues();
    boolean selectionHasVolumeVariables = false;
    boolean selectionHasMembraneVariables = false;
    switch(getExportSettings1().getSelectedFormat()) {
        case PLY:
        case QUICKTIME:
        case GIF:
        case FORMAT_JPEG:
        case ANIMATED_GIF:
            {
                displayPreferences = new DisplayPreferences[variableSelections.length];
                StringBuffer noScaleInfoNames = new StringBuffer();
                for (int i = 0; i < displayPreferences.length; i++) {
                    BitSet domainValid = null;
                    try {
                        if (dataInfoProvider != null) {
                            DataIdentifier varSelectionDataIdnetDataIdentifier = null;
                            for (int j = 0; j < dataInfoProvider.getPDEDataContext().getDataIdentifiers().length; j++) {
                                if (dataInfoProvider.getPDEDataContext().getDataIdentifiers()[j].getName().equals(variableSelections[i])) {
                                    varSelectionDataIdnetDataIdentifier = dataInfoProvider.getPDEDataContext().getDataIdentifiers()[j];
                                }
                            }
                            if (varSelectionDataIdnetDataIdentifier != null) {
                                selectionHasVolumeVariables = selectionHasVolumeVariables || varSelectionDataIdnetDataIdentifier.getVariableType().equals(VariableType.VOLUME) || varSelectionDataIdnetDataIdentifier.getVariableType().equals(VariableType.POSTPROCESSING) || varSelectionDataIdnetDataIdentifier.getVariableType().equals(VariableType.VOLUME_REGION);
                                selectionHasMembraneVariables = selectionHasMembraneVariables || varSelectionDataIdnetDataIdentifier.getVariableType().equals(VariableType.MEMBRANE) || varSelectionDataIdnetDataIdentifier.getVariableType().equals(VariableType.MEMBRANE_REGION);
                                CartesianMesh cartesianMesh = dataInfoProvider.getPDEDataContext().getCartesianMesh();
                                int dataLength = cartesianMesh.getDataLength(varSelectionDataIdnetDataIdentifier.getVariableType());
                                domainValid = new BitSet(dataLength);
                                domainValid.clear();
                                for (int j = 0; j < dataLength; j++) {
                                    if (dataInfoProvider.isDefined(varSelectionDataIdnetDataIdentifier, j)) {
                                        domainValid.set(j);
                                    }
                                }
                            } else {
                                throw new Exception("No DataIdentifer found for variable name '" + variableSelections[i] + "'");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        DialogUtils.showErrorDialog(this, "Error during domain evaluation:\n" + e.getMessage());
                        return;
                    }
                    displayPreferences[i] = new DisplayPreferences(getDisplayAdapterService().getDisplayPreferences((String) variableSelections[i]), domainValid);
                    if (!getDisplayAdapterService().hasStateID((String) variableSelections[i])) {
                        noScaleInfoNames.append("--- " + (String) variableSelections[i] + "\n");
                    }
                }
                break;
            }
        case CSV:
            {
                // check for membrane variables... warn for 3D geometry...
                // one gets the whole nine yards by index, not generally useful... except for a few people like Boris :)
                boolean mbVars = false;
                DataIdentifier[] dataIDs = getPdeDataContext().getDataIdentifiers();
                for (int i = 0; i < variableSelections.length; i++) {
                    String varName = (String) variableSelections[i];
                    for (int j = 0; j < dataIDs.length; j++) {
                        if (dataIDs[j].getName().equals(varName) && dataIDs[j].getVariableType().equals(VariableType.MEMBRANE)) {
                            mbVars = true;
                            break;
                        }
                    }
                }
                if (mbVars && getPdeDataContext().getCartesianMesh().getGeometryDimension() == 3 && getJRadioButtonSlice().isSelected()) {
                    String choice = PopupGenerator.showWarningDialog(this, getDataViewerManager().getUserPreferences(), UserMessage.warn_exportMembraneData3D, null);
                    if (choice.equals(UserMessage.OPTION_CANCEL)) {
                        // user canceled
                        return;
                    }
                }
                getExportSettings1().setSimulationSelector(createSimulationSelector());
                getExportSettings1().setIsCSVExport(true);
                break;
            }
        case NRRD:
        case IMAGEJ:
        case UCD:
        case VTK_IMAGE:
        case VTK_UNSTRUCT:
            break;
        default:
            break;
    }
    ;
    if (getJRadioButtonROI().isSelected() && getROISelections().getSelectedIndex() == -1) {
        PopupGenerator.showErrorDialog(this, "To export selections, you must select at least one item from the ROI selection list");
    }
    getExportSettings1().setTimeSpecs(new TimeSpecs(getJSlider1().getValue(), getJSlider2().getValue(), getPdeDataContext().getTimePoints(), ExportConstants.TIME_RANGE));
    getExportSettings1().setDisplayPreferences(displayPreferences, Arrays.asList(variableSelections).toArray(new String[0]), viewZoom);
    getExportSettings1().setSliceCount(FormatSpecificSpecs.getSliceCount(getJRadioButtonFull().isSelected(), getNormalAxis(), getPdeDataContext().getCartesianMesh()));
    getExportSettings1().setImageSizeCalculationInfo(getPdeDataContext().getCartesianMesh(), getNormalAxis());
    getExportSettings1().setIsSmoldyn(isSmoldyn);
    ExportFormat format = getSelectedFormat();
    if (format.equals(ExportFormat.PLY)) {
        getExportSettings1().setFormatSpecificSpecs(new PLYSpecs(true, displayPreferences));
    }
    if (format.requiresFollowOn()) {
        Frame theFrame = JOptionPane.getFrameForComponent(this);
        boolean okToExport = getExportSettings1().showFormatSpecificDialog(theFrame, selectionHasVolumeVariables, selectionHasMembraneVariables);
        if (!okToExport) {
            return;
        }
    }
    if (format.equals(ExportFormat.IMAGEJ)) {
        // export nrrd for imagej direct, the we'll send to imagej from vcell client
        getExportSettings1().setFormatSpecificSpecs(new RasterSpecs(ExportConstants.NRRD_SINGLE, false));
    }
    // determine of sim result is from local (quick) run or on server.
    final OutputContext outputContext = ((ClientPDEDataContext) getPdeDataContext()).getDataManager().getOutputContext();
    final ExportSpecs exportSpecs = getExportSpecs();
    boolean isLocalSimResult = false;
    VCDataIdentifier vcId = exportSpecs.getVCDataIdentifier();
    if (vcId instanceof LocalVCDataIdentifier) {
        isLocalSimResult = true;
    }
    // find out if smoldyn export choice is 'particle' - not available at this time
    boolean isParticle = false;
    if (getExportSettings1().getFormatSpecificSpecs() instanceof ImageSpecs) {
        isParticle = ((ImageSpecs) getExportSettings1().getFormatSpecificSpecs()).getParticleMode() == FormatSpecificSpecs.PARTICLE_SELECT;
    } else if (getExportSettings1().getFormatSpecificSpecs() instanceof MovieSpecs) {
        isParticle = ((MovieSpecs) getExportSettings1().getFormatSpecificSpecs()).getParticleMode() == FormatSpecificSpecs.PARTICLE_SELECT;
    }
    if (isLocalSimResult && isParticle) {
        DialogUtils.showErrorDialog(this, "Particle export for Smoldyn particles unavailable in local data at this time.");
        return;
    }
    // pass the export request down the line; non-blocking call
    if (!isLocalSimResult) {
        // for sims that ran on server, do as before.
        getDataViewerManager().startExport(this, outputContext, exportSpecs);
    } else {
        final String SOURCE_FILE_KEY = "SOURCE_FILE_KEY";
        final String DESTINATION_FILE_KEY = "DEESTINATION_FILE_KEY";
        AsynchClientTask localExportTast = new AsynchClientTask("Start Local Export", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                try {
                    File primaryDir = ResourceUtil.getLocalRootDir();
                    User usr = User.tempUser;
                    File usrDir = new File(primaryDir.getAbsolutePath(), usr.getName());
                    System.setProperty(PropertyLoader.exportBaseDirInternalProperty, usrDir.getAbsolutePath() + File.separator);
                    System.setProperty(PropertyLoader.exportBaseURLProperty, usrDir.toURI().toURL().toString());
                    DataSetControllerImpl dataSetControllerImpl = new DataSetControllerImpl(null, primaryDir, null);
                    ExportServiceImpl localExportServiceImpl = new ExportServiceImpl();
                    DataServerImpl dataServerImpl = new DataServerImpl(dataSetControllerImpl, localExportServiceImpl);
                    ExportEvent localExportEvent = dataServerImpl.makeRemoteFile(outputContext, usr, exportSpecs);
                    File sourceFile = new File(usrDir, new File((new URL(localExportEvent.getLocation()).getPath())).getName());
                    hashTable.put(SOURCE_FILE_KEY, sourceFile);
                } catch (Exception e) {
                    throw new Exception("Unable to export local sim results data : " + e.getMessage(), e);
                }
            }
        };
        AsynchClientTask localSaveTask = new AsynchClientTask("Start Local Export", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                File sourceFile = (File) hashTable.get(SOURCE_FILE_KEY);
                JFileChooser jFileChooser = new JFileChooser();
                jFileChooser.setSelectedFile(new File(sourceFile.getName()));
                if (jFileChooser.showSaveDialog(PDEExportDataPanel.this) == JFileChooser.APPROVE_OPTION) {
                    File destinationFile = jFileChooser.getSelectedFile();
                    if (destinationFile.exists()) {
                        final String OVERWRITE = "Overwrite";
                        final String CANCEL = "Cancel";
                        String response = DialogUtils.showWarningDialog(PDEExportDataPanel.this, "OK to Overwrite " + destinationFile.getAbsolutePath() + "?", new String[] { OVERWRITE, CANCEL }, OVERWRITE);
                        if (response == null || !response.equals(OVERWRITE)) {
                            return;
                        }
                    }
                    hashTable.put(DESTINATION_FILE_KEY, destinationFile);
                }
            }
        };
        AsynchClientTask localDeleteTempTask = new AsynchClientTask("Start Local Export", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING, false, false) {

            @Override
            public void run(Hashtable<String, Object> hashTable) throws Exception {
                File sourceFile = (File) hashTable.get(SOURCE_FILE_KEY);
                File destinationFile = (File) hashTable.get(DESTINATION_FILE_KEY);
                if (sourceFile != null && sourceFile.exists()) {
                    try {
                        if (destinationFile != null) {
                            copyFile(sourceFile, destinationFile);
                        }
                    } finally {
                        sourceFile.delete();
                    }
                }
            }
        };
        ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), new AsynchClientTask[] { localExportTast, localSaveTask, localDeleteTempTask }, false, true, null);
    }
}
Also used : DataServerImpl(cbit.vcell.simdata.DataServerImpl) JFrame(javax.swing.JFrame) Frame(java.awt.Frame) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) LocalVCDataIdentifier(org.vcell.util.document.LocalVCDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) DataIdentifier(cbit.vcell.simdata.DataIdentifier) User(org.vcell.util.document.User) RasterSpecs(cbit.vcell.export.server.RasterSpecs) ExportSpecs(cbit.vcell.export.server.ExportSpecs) ExportEvent(cbit.rmi.event.ExportEvent) URL(java.net.URL) DisplayPreferences(cbit.image.DisplayPreferences) ExportServiceImpl(cbit.vcell.export.server.ExportServiceImpl) TimeSpecs(cbit.vcell.export.server.TimeSpecs) Hashtable(java.util.Hashtable) PLYSpecs(cbit.vcell.export.server.PLYSpecs) BitSet(java.util.BitSet) ExportFormat(cbit.vcell.export.server.ExportFormat) LocalVCDataIdentifier(org.vcell.util.document.LocalVCDataIdentifier) IOException(java.io.IOException) UserCancelException(org.vcell.util.UserCancelException) OutputContext(cbit.vcell.simdata.OutputContext) CartesianMesh(cbit.vcell.solvers.CartesianMesh) MovieSpecs(cbit.vcell.export.server.MovieSpecs) JFileChooser(javax.swing.JFileChooser) ImageSpecs(cbit.vcell.export.server.ImageSpecs) DataSetControllerImpl(cbit.vcell.simdata.DataSetControllerImpl) LocalVCDataIdentifier(org.vcell.util.document.LocalVCDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) File(java.io.File)

Example 30 with CartesianMesh

use of cbit.vcell.solvers.CartesianMesh 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)

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