Search in sources :

Example 76 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class MathModel method propertyChange.

/**
 * This method gets called when a bound property is changed.
 * @param evt A PropertyChangeEvent object describing the event source
 *   	and the property that has changed.
 */
public void propertyChange(java.beans.PropertyChangeEvent evt) {
    // 
    if (evt.getSource() == this && evt.getPropertyName().equals(PROPERTY_NAME_MATH_DESCRIPTION)) {
        Geometry oldGeometry = null;
        Geometry newGeometry = null;
        MathDescription oldValue = (MathDescription) evt.getOldValue();
        if (oldValue != null) {
            oldValue.removePropertyChangeListener(this);
            oldGeometry = oldValue.getGeometry();
        }
        MathDescription newValue = (MathDescription) evt.getNewValue();
        if (newValue != null) {
            newValue.addPropertyChangeListener(this);
            newGeometry = newValue.getGeometry();
            if (fieldSimulations != null) {
                for (int i = 0; i < fieldSimulations.length; i++) {
                    if (fieldSimulations[i].getMathDescription() == evt.getOldValue()) {
                        try {
                            fieldSimulations[i].setMathDescription((MathDescription) evt.getNewValue());
                        } catch (PropertyVetoException e) {
                            System.out.println("error propagating math to Simulation '" + fieldSimulations[i].getName());
                            e.printStackTrace(System.out);
                        }
                    }
                }
            }
        }
        if (oldGeometry != newGeometry) {
            firePropertyChange(GeometryOwner.PROPERTY_NAME_GEOMETRY, oldGeometry, newGeometry);
        }
    }
    if (evt.getSource() == getMathDescription() && evt.getPropertyName().equals(GeometryOwner.PROPERTY_NAME_GEOMETRY)) {
        firePropertyChange(GeometryOwner.PROPERTY_NAME_GEOMETRY, evt.getOldValue(), evt.getNewValue());
    }
    // 
    if (evt.getSource() == this && evt.getPropertyName().equals(PropertyConstants.PROPERTY_NAME_SIMULATIONS) && evt.getNewValue() != null) {
        // 
        if (evt.getOldValue() != null) {
            Simulation[] simulations = (Simulation[]) evt.getOldValue();
            for (int i = 0; i < simulations.length; i++) {
                simulations[i].removeVetoableChangeListener(this);
                simulations[i].removePropertyChangeListener(this);
            }
        }
        // 
        if (evt.getOldValue() != null) {
            Simulation[] simulations = (Simulation[]) evt.getNewValue();
            for (int i = 0; i < simulations.length; i++) {
                simulations[i].addVetoableChangeListener(this);
                simulations[i].addPropertyChangeListener(this);
            }
        }
    }
}
Also used : Geometry(cbit.vcell.geometry.Geometry) PropertyVetoException(java.beans.PropertyVetoException) Simulation(cbit.vcell.solver.Simulation) MathDescription(cbit.vcell.math.MathDescription)

Example 77 with Geometry

use of cbit.vcell.geometry.Geometry 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 78 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class TopLevelWindowManager method prepareDocumentToLoad.

public void prepareDocumentToLoad(VCDocument doc, boolean bInNewWindow) throws Exception {
    if (doc instanceof BioModel) {
        Simulation[] simulations = ((BioModel) doc).getSimulations();
        ArrayList<VCSimulationIdentifier> simIDs = new ArrayList<VCSimulationIdentifier>();
        for (int i = 0; i < simulations.length; i++) {
            SimulationInfo simulationInfo = simulations[i].getSimulationInfo();
            if (simulationInfo != null) {
                simIDs.add(simulationInfo.getAuthoritativeVCSimulationIdentifier());
            }
        }
        RequestManager rm = getRequestManager();
        ConnectionStatus stat = rm.getConnectionStatus();
        if (stat.getStatus() == ConnectionStatus.CONNECTED) {
            rm.getDocumentManager().preloadSimulationStatus(simIDs.toArray(new VCSimulationIdentifier[0]));
        }
    } else if (doc instanceof MathModel) {
        Geometry geometry = ((MathModel) doc).getMathDescription().getGeometry();
        geometry.precomputeAll(new GeometryThumbnailImageFactoryAWT());
        Simulation[] simulations = ((MathModel) doc).getSimulations();
        // VCSimulationIdentifier simIDs[] = new VCSimulationIdentifier[simulations.length];
        ArrayList<VCSimulationIdentifier> simIDs = new ArrayList<>();
        for (int i = 0; i < simulations.length; i++) {
            if (simulations[i].getSimulationInfo() != null) {
                simIDs.add(simulations[i].getSimulationInfo().getAuthoritativeVCSimulationIdentifier());
            }
        }
        getRequestManager().getDocumentManager().preloadSimulationStatus(simIDs.toArray(new VCSimulationIdentifier[0]));
    } else if (doc instanceof Geometry) {
        ((Geometry) doc).precomputeAll(new GeometryThumbnailImageFactoryAWT());
    }
}
Also used : VCSimulationIdentifier(cbit.vcell.solver.VCSimulationIdentifier) MathModel(cbit.vcell.mathmodel.MathModel) ArrayList(java.util.ArrayList) Geometry(cbit.vcell.geometry.Geometry) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) Simulation(cbit.vcell.solver.Simulation) BioModel(cbit.vcell.biomodel.BioModel) ConnectionStatus(cbit.vcell.client.server.ConnectionStatus) SimulationInfo(cbit.vcell.solver.SimulationInfo)

Example 79 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class BioModelPropertiesPanel method updateInterface.

/**
 * Comment
 */
private void updateInterface() {
    if (bioModel == null || bioModelWindowManager == null) {
        return;
    }
    nameLabel.setText(bioModel.getName());
    Version version = bioModel.getVersion();
    if (version != null) {
        ownerLabel.setText(version.getOwner().getName());
        lastModifiedLabel.setText(version.getDate().toString());
        try {
            BioModelInfo bioModelInfo = bioModelWindowManager.getRequestManager().getDocumentManager().getBioModelInfo(version.getVersionKey());
            permissionLabel.setText(bioModelInfo.getVersion().getGroupAccess().getDescription());
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        changePermissionButton.setEnabled(true);
    }
    webLinksPanel.removeAll();
    webLinksPanel.setLayout(new GridLayout(0, 1));
    Set<MiriamRefGroup> resources = new HashSet<MiriamRefGroup>();
    Set<MiriamRefGroup> isDescribedByAnnotation = bioModel.getVCMetaData().getMiriamManager().getMiriamRefGroups(bioModel, MIRIAMQualifier.MODEL_isDescribedBy);
    Set<MiriamRefGroup> isAnnotation = bioModel.getVCMetaData().getMiriamManager().getMiriamRefGroups(bioModel, MIRIAMQualifier.MODEL_is);
    resources.addAll(isDescribedByAnnotation);
    resources.addAll(isAnnotation);
    for (MiriamRefGroup refGroup : resources) {
        for (MiriamResource miriamResources : refGroup.getMiriamRefs()) {
            LinkNode linkNode = new MiriamTreeModel.LinkNode(MIRIAMQualifier.MODEL_isDescribedBy, miriamResources);
            final String link = linkNode.getLink();
            String labelText = miriamResources.getDataType() == null ? "" : miriamResources.getDataType().getDataTypeName();
            String toolTip = null;
            if (link != null) {
                toolTip = "double-click to open link " + link;
                labelText = "<html><b>" + labelText + "</b>&nbsp;" + "<font color=blue><a href=" + link + ">" + link + "</a></font></html>";
            }
            JLabel label = new JLabel(labelText);
            label.addMouseListener(new MouseListener() {

                public void mouseReleased(MouseEvent e) {
                }

                public void mousePressed(MouseEvent e) {
                }

                public void mouseExited(MouseEvent e) {
                }

                public void mouseEntered(MouseEvent e) {
                }

                public void mouseClicked(MouseEvent e) {
                    if (e.getClickCount() == 2) {
                        DialogUtils.browserLauncher(BioModelPropertiesPanel.this, link, "failed to open " + link);
                    }
                }
            });
            label.setToolTipText(toolTip);
            webLinksPanel.add(label);
        }
    }
    applicationsPanel.removeAll();
    int gridy = 0;
    SimulationContext[] simulationContexts = bioModel.getSimulationContexts();
    if (simulationContexts != null) {
        for (int i = 0; i < simulationContexts.length; i++) {
            SimulationContext simContext = simulationContexts[i];
            JLabel label = new JLabel(simContext.getName());
            label.setFont(label.getFont().deriveFont(Font.BOLD));
            if (simContext.isRuleBased()) {
                if (simContext.getGeometry().getDimension() == 0) {
                    label.setIcon(VCellIcons.appRbmNonspIcon);
                }
            } else if (simContext.isStoch()) {
                if (simContext.getGeometry().getDimension() == 0) {
                    label.setIcon(VCellIcons.appStoNonspIcon);
                } else {
                    label.setIcon(VCellIcons.appStoSpatialIcon);
                }
            } else {
                // deterministic
                if (simContext.getGeometry().getDimension() == 0) {
                    label.setIcon(VCellIcons.appDetNonspIcon);
                } else {
                    label.setIcon(VCellIcons.appDetSpatialIcon);
                }
            }
            GridBagConstraints gbc = new java.awt.GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = gridy++;
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.anchor = GridBagConstraints.FIRST_LINE_START;
            if (i > 0) {
                gbc.insets = new Insets(4, 0, 0, 0);
            }
            applicationsPanel.add(label, gbc);
            Geometry geometry = simContext.getGeometry();
            String geometryText = "Compartmental geometry";
            if (geometry != null) {
                Version geometryVersion = geometry.getVersion();
                int dimension = geometry.getDimension();
                if (dimension > 0) {
                    String description = geometry.getDimension() + "D " + (geometry.getGeometrySpec().hasImage() ? "image" : "analytic") + " geometry";
                    geometryText = description;
                    if (geometryVersion != null) {
                        geometryText += " - " + geometryVersion.getName();
                    }
                }
            }
            JLabel geometryLabel = new JLabel(geometryText);
            geometryLabel.setIcon(VCellIcons.geometryIcon);
            JLabel detStochLabel = new JLabel(simContext.getMathType().getDescription());
            detStochLabel.setIcon(VCellIcons.mathTypeIcon);
            gbc.insets = new Insets(2, 20, 2, 2);
            gbc.gridy = gridy++;
            applicationsPanel.add(detStochLabel, gbc);
            gbc.gridy = gridy++;
            if (i == simulationContexts.length - 1) {
                gbc.weighty = 1.0;
            }
            applicationsPanel.add(geometryLabel, gbc);
        }
    }
}
Also used : GridBagConstraints(java.awt.GridBagConstraints) MouseEvent(java.awt.event.MouseEvent) Insets(java.awt.Insets) BioModelInfo(org.vcell.util.document.BioModelInfo) JLabel(javax.swing.JLabel) SimulationContext(cbit.vcell.mapping.SimulationContext) Geometry(cbit.vcell.geometry.Geometry) GridLayout(java.awt.GridLayout) MouseListener(java.awt.event.MouseListener) MiriamResource(cbit.vcell.biomodel.meta.MiriamManager.MiriamResource) Version(org.vcell.util.document.Version) LinkNode(cbit.vcell.xml.gui.MiriamTreeModel.LinkNode) DataAccessException(org.vcell.util.DataAccessException) MiriamRefGroup(cbit.vcell.biomodel.meta.MiriamManager.MiriamRefGroup) HashSet(java.util.HashSet)

Example 80 with Geometry

use of cbit.vcell.geometry.Geometry in project vcell by virtualcell.

the class ClientRequestManager method continueAfterMathModelGeomChangeWarning.

public static void continueAfterMathModelGeomChangeWarning(MathModelWindowManager mathModelWindowManager, Geometry newGeometry) throws UserCancelException {
    MathModel mathModel = mathModelWindowManager.getMathModel();
    if (mathModel != null && mathModel.getMathDescription() != null) {
        Geometry oldGeometry = mathModel.getMathDescription().getGeometry();
        if (oldGeometry != null && oldGeometry.getDimension() == 0) {
            return;
        }
        boolean bMeshResolutionChange = true;
        if (oldGeometry == null) {
            bMeshResolutionChange = false;
        }
        if (newGeometry != null && oldGeometry != null && oldGeometry.getDimension() == newGeometry.getDimension()) {
            bMeshResolutionChange = false;
        }
        boolean bHasSims = (mathModel.getSimulations() != null) && (mathModel.getSimulations().length > 0);
        StringBuffer meshResolutionChangeSB = new StringBuffer();
        if (bHasSims && bMeshResolutionChange) {
            ISize newGeomISize = MeshSpecification.calulateResetSamplingSize(newGeometry);
            for (int i = 0; i < mathModel.getSimulations().length; i++) {
                if (mathModel.getSimulations()[i].getMeshSpecification() != null) {
                    String simName = mathModel.getSimulations()[i].getName();
                    ISize simMeshSize = mathModel.getSimulations()[i].getMeshSpecification().getSamplingSize();
                    meshResolutionChangeSB.append((i != 0 ? "\n" : "") + "'" + simName + "' Mesh" + simMeshSize + " will be reset to " + newGeomISize + "");
                }
            }
        }
        String result = DialogUtils.showWarningDialog(JOptionPane.getFrameForComponent(mathModelWindowManager.getComponent()), "After changing MathModel geometry please note:\n" + "  1.  Check Geometry subvolume names match MathModel compartment names." + (bHasSims && bMeshResolutionChange ? "\n" + "  2.  All existing simulations mesh sizes will be reset" + " because the new Geometry spatial dimension(" + newGeometry.getDimension() + "D)" + " does not equal the current Geometry spatial dimension(" + oldGeometry.getDimension() + "D)" + "\n" + meshResolutionChangeSB.toString() : ""), new String[] { "Continue", "Cancel" }, "Continue");
        if (result != null && result.equals("Continue")) {
            return;
        }
    } else {
        return;
    }
    throw UserCancelException.CANCEL_GENERIC;
}
Also used : Geometry(cbit.vcell.geometry.Geometry) MathModel(cbit.vcell.mathmodel.MathModel) ISize(org.vcell.util.ISize)

Aggregations

Geometry (cbit.vcell.geometry.Geometry)121 MathDescription (cbit.vcell.math.MathDescription)32 SimulationContext (cbit.vcell.mapping.SimulationContext)31 Simulation (cbit.vcell.solver.Simulation)29 PropertyVetoException (java.beans.PropertyVetoException)24 BioModel (cbit.vcell.biomodel.BioModel)23 DataAccessException (org.vcell.util.DataAccessException)23 VCImage (cbit.image.VCImage)22 SubVolume (cbit.vcell.geometry.SubVolume)21 MathModel (cbit.vcell.mathmodel.MathModel)21 Expression (cbit.vcell.parser.Expression)19 ISize (org.vcell.util.ISize)19 Hashtable (java.util.Hashtable)18 GeometryThumbnailImageFactoryAWT (cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT)17 UserCancelException (org.vcell.util.UserCancelException)17 KeyValue (org.vcell.util.document.KeyValue)17 ImageException (cbit.image.ImageException)16 Extent (org.vcell.util.Extent)16 SurfaceClass (cbit.vcell.geometry.SurfaceClass)15 ExpressionException (cbit.vcell.parser.ExpressionException)15