Search in sources :

Example 1 with CartesianMesh

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

the class RunRefSimulationOp method saveExternalData.

private static void saveExternalData(Image image, String varName, ExternalDataIdentifier newROIExtDataID, LocalWorkspace localWorkspace) throws ObjectNotFoundException, ImageException, IOException {
    Extent extent = image.getExtent();
    Origin origin = image.getOrigin();
    ISize isize = image.getISize();
    VCImage vcImage = new VCImageUncompressed(null, new byte[isize.getXYZ()], extent, isize.getX(), isize.getY(), isize.getZ());
    RegionImage regionImage = new RegionImage(vcImage, 0, null, null, RegionImage.NO_SMOOTHING);
    CartesianMesh simpleCartesianMesh = CartesianMesh.createSimpleCartesianMesh(origin, extent, isize, regionImage);
    int NumTimePoints = 1;
    int NumChannels = 1;
    // dimensions: time points, channels, whole image ordered by z slices.
    double[][][] pixData = new double[NumTimePoints][NumChannels][];
    pixData[0][0] = image.getDoublePixels();
    FieldDataFileOperationSpec fdos = new FieldDataFileOperationSpec();
    fdos.opType = FieldDataFileOperationSpec.FDOS_ADD;
    fdos.cartesianMesh = simpleCartesianMesh;
    fdos.doubleSpecData = pixData;
    fdos.specEDI = newROIExtDataID;
    fdos.varNames = new String[] { varName };
    fdos.owner = LocalWorkspace.getDefaultOwner();
    fdos.times = new double[] { 0.0 };
    fdos.variableTypes = new VariableType[] { VariableType.VOLUME };
    fdos.origin = origin;
    fdos.extent = extent;
    fdos.isize = isize;
    localWorkspace.getDataSetControllerImpl().fieldDataFileOperation(fdos);
}
Also used : Origin(org.vcell.util.Origin) CartesianMesh(cbit.vcell.solvers.CartesianMesh) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) FieldDataFileOperationSpec(cbit.vcell.field.io.FieldDataFileOperationSpec) RegionImage(cbit.vcell.geometry.RegionImage) VCImage(cbit.image.VCImage) VCImageUncompressed(cbit.image.VCImageUncompressed)

Example 2 with CartesianMesh

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

the class ClientRequestManager method getParseImageTask.

public static AsynchClientTask getParseImageTask(final Component requesterComp, final VCDocument.DocumentCreationInfo documentCreationInfo, final MDIManager mdiManager) {
    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_FILE) // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ ||
                // documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER
                {
                    File imageFile = (File) hashTable.get(IMAGE_FILE);
                    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;
                        ImageDatasetReaderService imageDatasetReaderServiceInstance = ImageDatasetReaderService.getInstance();
                        ImageDatasetReader imageDatasetReader = imageDatasetReaderServiceInstance.getImageDatasetReader();
                        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(requesterComp, "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 = imageDatasetReader.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 = imageDatasetReader.getImageSizeInfoForceZ(imageFile.getAbsolutePath(), null);
                            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 = mdiManager.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(requesterComp, 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());
                        }
                        GeometryClass[] myGeometryClasses = workspaceGeom.getGeometryClasses();
                        VCPixelClass[] myPixelClasses = workspaceGeom.getGeometrySpec().getImage().getPixelClasses();
                        VCPixelClass[] newPixelClasses = new VCPixelClass[myPixelClasses.length];
                        for (int i = 0; i < myPixelClasses.length; i++) {
                            for (int j = 0; j < myGeometryClasses.length; j++) {
                                if (myGeometryClasses[j] instanceof ImageSubVolume && myPixelClasses[i].getPixel() == ((ImageSubVolume) myGeometryClasses[j]).getPixelValue()) {
                                    newPixelClasses[i] = new VCPixelClass(null, myGeometryClasses[j].getName(), myPixelClasses[i].getPixel());
                                    break;
                                }
                            }
                        }
                        hashTable.put(VCPIXELCLASSES, newPixelClasses);
                    } 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());
            }
        }
    };
    return parseImageTask;
}
Also used : BngUnitOrigin(org.vcell.model.bngl.BngUnitSystem.BngUnitOrigin) Origin(org.vcell.util.Origin) PDEDataContext(cbit.vcell.simdata.PDEDataContext) GeometryClass(cbit.vcell.geometry.GeometryClass) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) VCPixelClass(cbit.image.VCPixelClass) Extent(org.vcell.util.Extent) FieldDataFileOperationSpec(cbit.vcell.field.io.FieldDataFileOperationSpec) ISize(org.vcell.util.ISize) ArrayList(java.util.ArrayList) VCImage(cbit.image.VCImage) GZIPInputStream(java.util.zip.GZIPInputStream) ImageDatasetReaderService(org.vcell.vcellij.ImageDatasetReaderService) BufferedInputStream(java.io.BufferedInputStream) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Component(java.awt.Component) ImageSubVolume(cbit.vcell.geometry.ImageSubVolume) Enumeration(java.util.Enumeration) VCDocument(org.vcell.util.document.VCDocument) Hashtable(java.util.Hashtable) DataInputStream(java.io.DataInputStream) ProgrammingException(org.vcell.util.ProgrammingException) MatrixException(cbit.vcell.matrix.MatrixException) GeometryException(cbit.vcell.geometry.GeometryException) IOException(java.io.IOException) DataAccessException(org.vcell.util.DataAccessException) MappingException(cbit.vcell.mapping.MappingException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UtilCancelException(org.vcell.util.UtilCancelException) ModelException(cbit.vcell.model.ModelException) DataFormatException(java.util.zip.DataFormatException) ExpressionException(cbit.vcell.parser.ExpressionException) MathException(cbit.vcell.math.MathException) UserCancelException(org.vcell.util.UserCancelException) FileInputStream(java.io.FileInputStream) ImageSizeInfo(cbit.image.ImageSizeInfo) Geometry(cbit.vcell.geometry.Geometry) StringTokenizer(java.util.StringTokenizer) CommentStringTokenizer(org.vcell.util.CommentStringTokenizer) CartesianMesh(cbit.vcell.solvers.CartesianMesh) DataFormatException(java.util.zip.DataFormatException) ChooseFile(cbit.vcell.client.task.ChooseFile) File(java.io.File) ImageDatasetReader(org.vcell.vcellij.ImageDatasetReader)

Example 3 with CartesianMesh

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

the class ClientRequestManager method resize0.

private static void resize0(Hashtable hashTable) /*ImageSizeInfo sourceSize,ImageSizeInfo newSize*/
{
    // OrigOrigin = new Origin
    // CartesianMesh origMesh = CartesianMesh.createSimpleCartesianMesh(orig, extent, size, regionImage);
    // ISize varISize = dataProcessingOutputInfo.getVariableISize(varName);
    // Extent varExtent = dataProcessingOutputInfo.getVariableExtent(varName);
    // Origin varOrigin = dataProcessingOutputInfo.getVariableOrigin(varName);
    // VCImage vcImage = new VCImageUncompressed(null,
    // new byte[varISize.getXYZ()],
    // varExtent,
    // varISize.getX(),
    // varISize.getY(),
    // varISize.getZ());
    // RegionImage regionImage = new RegionImage(vcImage,
    // 1+(varISize.getY()>0?1:0)+(varISize.getZ()>0?1:0),
    // varExtent,
    // varOrigin,
    // RegionImage.NO_SMOOTHING);
    // return CartesianMesh.createSimpleCartesianMesh(
    // dataProcessingOutputInfo.getVariableOrigin(varName),
    // varExtent,
    // varISize, regionImage);
    CartesianMesh origMesh = (CartesianMesh) hashTable.get("sourceMesh");
    CartesianMesh resampleMesh = (CartesianMesh) hashTable.get("newMesh");
    FieldDataFileOperationSpec fdfos = (FieldDataFileOperationSpec) hashTable.get(FDFOS);
    double[] origData = new double[fdfos.isize.getXYZ()];
    for (int i = 0; i < origData.length; i++) {
        origData[i] = fdfos.shortSpecData[0][0][i];
    }
    double[] newData = null;
    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);
    }
    short[][][] newShort = new short[1][1][resampleMesh.getISize().getXYZ()];
    for (int i = 0; i < newShort[0][0].length; i++) {
        newShort[0][0][i] = (short) newData[i];
    }
    fdfos.isize = resampleMesh.getISize();
    fdfos.extent = resampleMesh.getExtent();
    fdfos.origin = resampleMesh.getOrigin();
    fdfos.shortSpecData = newShort;
// hashTable.put(VCPIXELCLASSES, newPixelClasses);
}
Also used : CartesianMesh(cbit.vcell.solvers.CartesianMesh) FieldDataFileOperationSpec(cbit.vcell.field.io.FieldDataFileOperationSpec)

Example 4 with CartesianMesh

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

the class VFrapXmlHelper method SaveVFrapSpecialImagesAsFieldData.

// 
// save the special images in the database as field data
// 
public static ExternalDataIdentifier SaveVFrapSpecialImagesAsFieldData(Hashtable<String, Object> hashTable, DocumentManager documentManager) throws DataAccessException {
    CartesianMesh mesh = (CartesianMesh) hashTable.get("mesh");
    double[][][] pixData = (double[][][]) hashTable.get("pixData");
    String[] channelNames = (String[]) hashTable.get("channelNames");
    VariableType[] channelTypes = (VariableType[]) hashTable.get("channelTypes");
    // DataSymbolType[] channelVFrapImageType = (DataSymbolType[])hashTable.get("channelVFrapImageType");
    String mixedFieldDataName = (String) hashTable.get("mixedFieldDataName");
    FieldDataFileOperationSpec vfrapMiscFieldDataOpSpec = new FieldDataFileOperationSpec();
    vfrapMiscFieldDataOpSpec.opType = FieldDataFileOperationSpec.FDOS_ADD;
    vfrapMiscFieldDataOpSpec.cartesianMesh = mesh;
    vfrapMiscFieldDataOpSpec.doubleSpecData = pixData;
    vfrapMiscFieldDataOpSpec.specEDI = null;
    // item name as it comes from vFrap
    vfrapMiscFieldDataOpSpec.varNames = channelNames;
    vfrapMiscFieldDataOpSpec.owner = documentManager.getUser();
    vfrapMiscFieldDataOpSpec.times = new double[] { 0.0 };
    vfrapMiscFieldDataOpSpec.variableTypes = channelTypes;
    vfrapMiscFieldDataOpSpec.origin = new Origin(0, 0, 0);
    vfrapMiscFieldDataOpSpec.extent = mesh.getExtent();
    vfrapMiscFieldDataOpSpec.isize = new ISize(mesh.getSizeX(), mesh.getSizeY(), mesh.getSizeZ());
    ExternalDataIdentifier vfrapMisc = documentManager.saveFieldData(vfrapMiscFieldDataOpSpec, mixedFieldDataName);
    return vfrapMisc;
}
Also used : Origin(org.vcell.util.Origin) CartesianMesh(cbit.vcell.solvers.CartesianMesh) VariableType(cbit.vcell.math.VariableType) FieldDataFileOperationSpec(cbit.vcell.field.io.FieldDataFileOperationSpec) ISize(org.vcell.util.ISize) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier)

Example 5 with CartesianMesh

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

the class VFrapXmlHelper method LoadVFrapSpecialImages.

// // load and compute prebleach average and first postbleach images
// public void LoadVFrapSpecialImages(AnnotatedImageDataset annotatedImages, int startingIndexRecovery)
// {
// // unnormalized prebleach average
// prebleachAvg = new double[annotatedImages.getImageDataset().getImage(0, 0, startingIndexRecovery).getNumXYZ()];
// for(int j = 0; j < prebleachAvg.length; j++)
// {
// double pixelTotal = 0;
// for(int i = 0 ; i < startingIndexRecovery; i++)
// {
// pixelTotal = pixelTotal + (annotatedImages.getImageDataset().getImage(0, 0, i).getPixels()[j] & 0x0000FFFF);
// }
// prebleachAvg[j] = pixelTotal/startingIndexRecovery;
// }
// 
// // unnormalized first post bleach
// firstPostBleach = new double[annotatedImages.getImageDataset().getImage(0, 0, startingIndexRecovery).getNumXYZ()];
// short[] pixels = annotatedImages.getImageDataset().getImage(0, 0, startingIndexRecovery).getPixels();
// for(int i = 0; i< pixels.length; i++)
// {
// firstPostBleach[i] = pixels[i] & 0x0000FFFF;
// }
// }
// 
// Locate the special images within the vFrap files and load them in memory
// 
public static boolean LoadVFrapSpecialImages(Hashtable<String, Object> hashTable, Element vFrapRoot) throws IOException, DataAccessException, MathException, ImageException {
    // ------ parse the vfrap file and the log/zip files referred within -----
    // many channels of 1 timepoint each
    int NumTimePoints = 1;
    // the channels: prebleach, postbleach, roi1, roi2 ... roiN
    int NumChannels = tokenNames.length;
    String[] channelNames = new String[NumChannels];
    VariableType[] channelTypes = new VariableType[NumChannels];
    DataSymbolType[] channelVFrapImageType = new DataSymbolType[NumChannels];
    double[][][] pixData = new double[NumTimePoints][NumChannels][];
    // get the path of the file tagged with "ROIExternalDataInfoTag" and open it
    Element roiExternalDataInfoElement = vFrapRoot.getChild(MicroscopyXMLTags.ROIExternalDataInfoTag);
    if (roiExternalDataInfoElement == null) {
        // can't load FieldData for some reason, fall back to importing the biomodel only
        return false;
    }
    // <ROIExternalDataInfo Filename="c:\vFrap\VirtualMicroscopy\SimulationData\SimID_1282941232246_0_.log">
    // <ExternalDataIdentifier Name="timeData" KeyValue="1282941232246" OwnerName="SimulationData" OwnerKey="0" />
    // </ImageDatasetExternalDataInfo>
    // c:\VirtualMicroscopy\SimulationData\SimID_1284149203811_0_.log
    String filename = (roiExternalDataInfoElement).getAttributeValue("Filename");
    Element childElement = (roiExternalDataInfoElement).getChild("ExternalDataIdentifier");
    if (childElement == null) {
        // can't load FieldData for some reason, fall back to importing the biomodel only
        return false;
    }
    StringTokenizer tokens = new StringTokenizer(filename, "/\\.");
    final ArrayList<String> tokenArray = new ArrayList<String>();
    while (tokens.hasMoreElements()) {
        tokenArray.add(tokens.nextToken());
    }
    final String dataID = tokenArray.get(tokenArray.size() - 2);
    final String userName = tokenArray.get(tokenArray.size() - 3);
    VCDataIdentifier vcDataIdentifier = new VCDataIdentifier() {

        public String getID() {
            return dataID;
        }

        public KeyValue getDataKey() {
            return null;
        }

        public User getOwner() {
            return new User(userName, new KeyValue("123345432334"));
        }
    };
    // ------- recover simulation data for this user name, load the images in memory ------------
    // ex  c:\\VirtualMicroscopy\\SimulationData
    String userDirName = filename.substring(0, filename.indexOf(dataID) - 1);
    File userDir = new File(userDirName);
    SimulationData.SimDataAmplistorInfo simDataAmplistorInfo = AmplistorUtils.getSimDataAmplistorInfoFromPropertyLoader();
    SimulationData simData = new SimulationData(vcDataIdentifier, userDir, null, simDataAmplistorInfo);
    // build a valid mesh in 2 steps, what we have in simData is incomplete
    CartesianMesh incompleteMesh = simData.getMesh();
    Extent extent = incompleteMesh.getExtent();
    ISize isize = new ISize(incompleteMesh.getSizeX(), incompleteMesh.getSizeY(), incompleteMesh.getSizeZ());
    Origin origin = new Origin(0, 0, 0);
    CartesianMesh mesh = CartesianMesh.createSimpleCartesianMesh(origin, extent, isize, new RegionImage(new VCImageUncompressed(null, new byte[isize.getXYZ()], extent, isize.getX(), isize.getY(), isize.getZ()), 0, null, null, RegionImage.NO_SMOOTHING));
    DataIdentifier[] dataIdentifiers = simData.getVarAndFunctionDataIdentifiers(null);
    double[] times = simData.getDataTimes();
    for (int i = 0; i < dataIdentifiers.length; i++) {
        // ex: prebleach_avg, postbleach_first, postbleach_last, bleached_mask, cell_mask, ring1_mask,... ring8_mask
        System.out.println(dataIdentifiers[i].getName());
        for (double time : times) {
            // this loops only once, we have just 1 timepoint for each "special" image
            SimDataBlock simDataBlock = simData.getSimDataBlock(null, dataIdentifiers[i].getName(), time);
            channelNames[i] = dataIdentifiers[i].getName();
            channelTypes[i] = VariableType.VOLUME;
            channelVFrapImageType[i] = SymbolEquivalence.typeFromToken(dataIdentifiers[i].getName());
            pixData[0][i] = simDataBlock.getData();
            // var = prebleach_avg, time = 0.0, data = { 1.0832530361887216 1.0832530361887216 1.0832530361887216 1.0 .... }
            System.out.print("var = " + dataIdentifiers[i].getName() + ", time = " + time + ", data = { ");
            // show a few
            for (int j = 0; j < 5; j++) {
                System.out.print(pixData[0][i][j] + " ");
            }
            // show a few
            ;
            // show a few
            System.out.println(" ... ");
        }
    }
    hashTable.put("mesh", mesh);
    hashTable.put("pixData", pixData);
    hashTable.put("channelNames", channelNames);
    hashTable.put("channelTypes", channelTypes);
    hashTable.put("channelVFrapImageType", channelVFrapImageType);
    return true;
}
Also used : Origin(org.vcell.util.Origin) User(org.vcell.util.document.User) KeyValue(org.vcell.util.document.KeyValue) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) DataIdentifier(cbit.vcell.simdata.DataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) Extent(org.vcell.util.Extent) ISize(org.vcell.util.ISize) Element(org.jdom.Element) ArrayList(java.util.ArrayList) SimDataBlock(cbit.vcell.simdata.SimDataBlock) VariableType(cbit.vcell.math.VariableType) VCImageUncompressed(cbit.image.VCImageUncompressed) StringTokenizer(java.util.StringTokenizer) CartesianMesh(cbit.vcell.solvers.CartesianMesh) SimulationData(cbit.vcell.simdata.SimulationData) DataSymbolType(cbit.vcell.data.DataSymbol.DataSymbolType) RegionImage(cbit.vcell.geometry.RegionImage) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) File(java.io.File)

Aggregations

CartesianMesh (cbit.vcell.solvers.CartesianMesh)55 ISize (org.vcell.util.ISize)27 Extent (org.vcell.util.Extent)19 VCImageUncompressed (cbit.image.VCImageUncompressed)18 RegionImage (cbit.vcell.geometry.RegionImage)18 Origin (org.vcell.util.Origin)18 VariableType (cbit.vcell.math.VariableType)17 DataAccessException (org.vcell.util.DataAccessException)17 FieldDataFileOperationSpec (cbit.vcell.field.io.FieldDataFileOperationSpec)16 File (java.io.File)14 VCDataIdentifier (org.vcell.util.document.VCDataIdentifier)14 ExternalDataIdentifier (org.vcell.util.document.ExternalDataIdentifier)13 IOException (java.io.IOException)12 VCImage (cbit.image.VCImage)10 SimDataBlock (cbit.vcell.simdata.SimDataBlock)10 DataIdentifier (cbit.vcell.simdata.DataIdentifier)9 VCSimulationDataIdentifier (cbit.vcell.solver.VCSimulationDataIdentifier)9 UserCancelException (org.vcell.util.UserCancelException)9 ImageException (cbit.image.ImageException)7 AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)7