Search in sources :

Example 11 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class GeometrySpec method vetoableChange.

/**
 * Insert the method's description here.
 * Creation date: (6/3/00 9:58:08 AM)
 * @param event java.beans.PropertyChangeEvent
 */
public void vetoableChange(java.beans.PropertyChangeEvent event) throws PropertyVetoException {
    if (event.getSource() == this && event.getPropertyName().equals("image")) {
        if (event.getNewValue() != null) {
            VCImage newVCImage = (VCImage) event.getNewValue();
            if (newVCImage.getNumXYZ() > IMAGE_SIZE_LIMIT) {
                // throw new PropertyVetoException("image size "+newVCImage.getNumXYZ()+" pixels exceeded limit of "+IMAGE_SIZE_LIMIT,event);
                if (lg.isEnabledFor(Level.WARN)) {
                    lg.warn("WARNING: image size " + newVCImage.getNumXYZ() + " pixels exceeded limit of " + IMAGE_SIZE_LIMIT);
                }
            }
        }
    }
    if (event.getSource() == this && event.getPropertyName().equals("subVolumes")) {
        SubVolume[] subVolumes = (SubVolume[]) event.getNewValue();
        // 
        // add subvolumes
        // (handles must be unique and non-negative, and analytic subvolumes must be first in array)
        // 
        boolean bFoundImageSubVolume = false;
        for (int i = 0; i < subVolumes.length; i++) {
            SubVolume sv = subVolumes[i];
            // 
            if (sv.getHandle() < 0) {
                throw new PropertyVetoException("subdomain handle=" + sv.getHandle() + " must be non-negative", event);
            }
            if (sv.getName() == null || sv.getName().length() < 1) {
                throw new PropertyVetoException("Subdomain name cannot be null or blank : ", event);
            }
            // 
            for (int j = i + 1; j < subVolumes.length; j++) {
                if (subVolumes[j].getHandle() == subVolumes[i].getHandle()) {
                    throw new PropertyVetoException("subdomain handle=" + sv.getHandle() + " has already been used in geometry", event);
                }
                if (subVolumes[j].getName().equals(subVolumes[i].getName())) {
                    throw new PropertyVetoException("subdomain name=" + sv.getName() + " has already been used in geometry", event);
                }
            }
            // 
            if (sv instanceof ImageSubVolume) {
                bFoundImageSubVolume = true;
            } else if (sv instanceof AnalyticSubVolume) {
                if (bFoundImageSubVolume) {
                    throw new PropertyVetoException("subdomains are out of order, all analytic subdomains must preceed all image subdomains", event);
                }
            }
        }
        // 
        for (int i = 0; i < subVolumes.length; i++) {
            if (subVolumes[i] instanceof ImageSubVolume) {
                if (vcImage == null) {
                    throw new PropertyVetoException("adding image subdomain, an image must be set first", event);
                }
            }
        }
    // 
    // check for uniqueness of name and handles
    // check for handle values of (0..N-1)
    // 
    } else if (event.getSource() == this && event.getPropertyName().equals("extent")) {
        Extent newExtent = (Extent) event.getNewValue();
        if (newExtent == null) {
            throw new PropertyVetoException("extent cannot be null", event);
        }
        if (newExtent.getX() <= 0 || newExtent.getY() <= 0.0 || newExtent.getZ() <= 0) {
            throw new PropertyVetoException("extent must be positive in X,Y,Z", event);
        }
    } else if (event.getSource() instanceof SubVolume && event.getPropertyName().equals("name")) {
        String newName = (String) event.getNewValue();
        if (newName == null || newName.length() < 1) {
            throw new PropertyVetoException("subdomain name must be at least one character", event);
        }
        // 
        // check if name already used
        // 
        SubVolume sv = getSubVolume(newName);
        if (sv != null && sv != event.getSource()) {
            throw new PropertyVetoException("A subdomain with name '" + newName + "' already exists.", event);
        }
    }
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) Extent(org.vcell.util.Extent) VCImage(cbit.image.VCImage)

Example 12 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class GeometrySpec method gatherIssues.

public void gatherIssues(IssueContext issueContext, Geometry geometry, List<Issue> issueVector) {
    // 
    if (getDimension() > 0) {
        VCImage argSampledImage = getSampledImage().getCurrentValue();
        if (argSampledImage == null) {
            return;
        }
        try {
            // 
            // make sure that each sample was assigned to a SubVolume
            // 
            int count = 0;
            byte[] samples = argSampledImage.getPixels();
            for (int i = 0; i < samples.length; i++) {
                if (samples[i] == -1) {
                    count++;
                }
            }
            if (count > 0) {
                String errorMessage = "Invalid Geometry - " + count + " of " + samples.length + " samples of geometry domain didn't map to any subdomain";
                Issue issue = new Issue(geometry, issueContext, IssueCategory.SubVolumeVerificationError, errorMessage, Issue.SEVERITY_ERROR);
                issueVector.add(issue);
            }
            // 
            // make sure that each subvolume is resolved in the geometry
            // 
            ArrayList<SubVolume> missingSubVolumeList = new ArrayList<SubVolume>();
            SubVolume[] subVolumes = getSubVolumes();
            for (int i = 0; i < subVolumes.length; i++) {
                if (argSampledImage.getPixelClassFromPixelValue(subVolumes[i].getHandle()) == null) {
                    missingSubVolumeList.add(subVolumes[i]);
                }
            }
            if (missingSubVolumeList.size() > 0) {
                for (int i = 0; i < missingSubVolumeList.size(); i++) {
                    String errorMessage = "Subdomain '" + missingSubVolumeList.get(i).getName() + "' is not resolved in geometry domain";
                    Issue issue = new Issue(geometry, issueContext, IssueCategory.SubVolumeVerificationError, errorMessage, Issue.SEVERITY_ERROR);
                    issueVector.add(issue);
                }
            }
        } catch (Exception ex) {
            Issue issue = new Issue(geometry, issueContext, IssueCategory.SubVolumeVerificationError, ex.getMessage(), Issue.SEVERITY_ERROR);
            issueVector.add(issue);
        }
    }
}
Also used : Issue(org.vcell.util.Issue) ArrayList(java.util.ArrayList) VCImage(cbit.image.VCImage) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) ExpressionException(cbit.vcell.parser.ExpressionException)

Example 13 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class FiniteVolumeFileWriter method writeChomboSpec.

private void writeChomboSpec() throws ExpressionException, SolverException, PropertyVetoException, ClassNotFoundException, IOException, GeometryException, ImageException {
    if (!bChomboSolver) {
        return;
    }
    GeometrySpec geometrySpec = resampledGeometry.getGeometrySpec();
    int dimension = geometrySpec.getDimension();
    if (dimension == 1) {
        throw new SolverException(simTask.getSimulation().getSolverTaskDescription().getSolverDescription().getDisplayLabel() + " is only supported for simulations with 2D or 3D geometry.");
    }
    Simulation simulation = getSimulationTask().getSimulation();
    SolverTaskDescription solverTaskDescription = simulation.getSolverTaskDescription();
    ChomboSolverSpec chomboSolverSpec = solverTaskDescription.getChomboSolverSpec();
    printWriter.println(FVInputFileKeyword.CHOMBO_SPEC_BEGIN);
    printWriter.println(FVInputFileKeyword.DIMENSION + " " + geometrySpec.getDimension());
    Extent extent = geometrySpec.getExtent();
    Origin origin = geometrySpec.getOrigin();
    ISize isize = simulation.getMeshSpecification().getSamplingSize();
    switch(geometrySpec.getDimension()) {
        case 2:
            printWriter.println(FVInputFileKeyword.MESH_SIZE + " " + isize.getX() + " " + isize.getY());
            printWriter.println(FVInputFileKeyword.DOMAIN_SIZE + " " + extent.getX() + " " + extent.getY());
            printWriter.println(FVInputFileKeyword.DOMAIN_ORIGIN + " " + origin.getX() + " " + origin.getY());
            break;
        case 3:
            printWriter.println(FVInputFileKeyword.MESH_SIZE + " " + isize.getX() + " " + isize.getY() + " " + isize.getZ());
            printWriter.println(FVInputFileKeyword.DOMAIN_SIZE + " " + extent.getX() + " " + extent.getY() + " " + extent.getZ());
            printWriter.println(FVInputFileKeyword.DOMAIN_ORIGIN + " " + origin.getX() + " " + origin.getY() + " " + origin.getZ());
            break;
    }
    List<CompartmentSubDomain> featureList = new ArrayList<CompartmentSubDomain>();
    Enumeration<SubDomain> enum1 = simulation.getMathDescription().getSubDomains();
    while (enum1.hasMoreElements()) {
        SubDomain sd = enum1.nextElement();
        if (sd instanceof CompartmentSubDomain) {
            featureList.add((CompartmentSubDomain) sd);
        }
    }
    int numFeatures = featureList.size();
    CompartmentSubDomain[] features = featureList.toArray(new CompartmentSubDomain[0]);
    int[] phases = new int[numFeatures];
    Arrays.fill(phases, -1);
    phases[numFeatures - 1] = 0;
    int[] numAssigned = new int[] { 1 };
    assignPhases(features, numFeatures - 1, phases, numAssigned);
    Map<String, Integer> subDomainPhaseMap = new HashMap<String, Integer>();
    for (int i = 0; i < phases.length; ++i) {
        if (phases[i] == -1) {
            throw new SolverException("Failed to assign a phase to CompartmentSubdomain '" + features[i].getName() + "'. It might be caused by too coarsh a mesh.");
        }
        subDomainPhaseMap.put(features[i].getName(), phases[i]);
    }
    SubVolume[] subVolumes = geometrySpec.getSubVolumes();
    if (geometrySpec.hasImage()) {
        Geometry geometry = (Geometry) BeanUtils.cloneSerializable(simulation.getMathDescription().getGeometry());
        Geometry simGeometry = geometry;
        VCImage img = geometry.getGeometrySpec().getImage();
        int factor = Math.max(Math.max(img.getNumX(), img.getNumY()), img.getNumZ()) < 512 ? 2 : 1;
        ISize distanceMapMeshSize = new ISize(img.getNumX() * factor, img.getNumY() * factor, img.getNumZ() * factor);
        Vect3d deltaX = null;
        boolean bCellCentered = false;
        double dx = 0.5;
        double dy = 0.5;
        double dz = 0.5;
        int Nx = distanceMapMeshSize.getX();
        int Ny = distanceMapMeshSize.getY();
        int Nz = distanceMapMeshSize.getZ();
        if (dimension == 2) {
            // pad the 2D image with itself in order to obtain a 3D image used to compute the distance map
            // because the distance map algorithm is 3D only (using distance to triangles)
            byte[] oldPixels = img.getPixels();
            byte[] newPixels = new byte[oldPixels.length * 3];
            System.arraycopy(oldPixels, 0, newPixels, 0, oldPixels.length);
            System.arraycopy(oldPixels, 0, newPixels, oldPixels.length, oldPixels.length);
            System.arraycopy(oldPixels, 0, newPixels, oldPixels.length * 2, oldPixels.length);
            double distX = geometry.getExtent().getX() / img.getNumX();
            double distY = geometry.getExtent().getY() / img.getNumY();
            // we set the distance on the z axis to something that makes sense
            double distZ = Math.max(distX, distY);
            Extent newExtent = new Extent(geometry.getExtent().getX(), geometry.getExtent().getY(), distZ * 3);
            VCImage newImage = new VCImageUncompressed(null, newPixels, newExtent, img.getNumX(), img.getNumY(), 3);
            // copy the pixel classes too
            ArrayList<VCPixelClass> newPixelClasses = new ArrayList<VCPixelClass>();
            for (VCPixelClass origPixelClass : geometry.getGeometrySpec().getImage().getPixelClasses()) {
                SubVolume origSubvolume = geometry.getGeometrySpec().getImageSubVolumeFromPixelValue(origPixelClass.getPixel());
                newPixelClasses.add(new VCPixelClass(null, origSubvolume.getName(), origPixelClass.getPixel()));
            }
            newImage.setPixelClasses(newPixelClasses.toArray(new VCPixelClass[newPixelClasses.size()]));
            simGeometry = new Geometry(geometry, newImage);
            Nz = 3;
        }
        GeometrySpec simGeometrySpec = simGeometry.getGeometrySpec();
        Extent simExtent = simGeometrySpec.getExtent();
        dx = simExtent.getX() / (Nx - 1);
        dy = simExtent.getY() / (Ny - 1);
        dz = simExtent.getZ() / (Nz - 1);
        if (Math.abs(dx - dy) > 0.1 * Math.max(dx, dy)) {
            dx = Math.min(dx, dy);
            dy = dx;
            Nx = (int) (simExtent.getX() / dx + 1);
            Ny = (int) (simExtent.getY() / dx + 1);
            if (dimension == 3) {
                dz = dx;
                Nz = (int) (simExtent.getZ() / dx + 1);
            }
        }
        deltaX = new Vect3d(dx, dy, dz);
        // one more point in each direction
        distanceMapMeshSize = new ISize(Nx + 1, Ny + 1, Nz + 1);
        Extent distanceMapExtent = new Extent(simExtent.getX() + dx, simExtent.getY() + dy, simExtent.getZ() + dz);
        simGeometrySpec.setExtent(distanceMapExtent);
        GeometrySurfaceDescription geoSurfaceDesc = simGeometry.getGeometrySurfaceDescription();
        geoSurfaceDesc.setVolumeSampleSize(distanceMapMeshSize);
        geoSurfaceDesc.updateAll();
        VCImage vcImage = RayCaster.sampleGeometry(simGeometry, distanceMapMeshSize, bCellCentered);
        SubvolumeSignedDistanceMap[] distanceMaps = DistanceMapGenerator.computeDistanceMaps(simGeometry, vcImage, bCellCentered);
        if (dimension == 2) {
            distanceMaps = DistanceMapGenerator.extractMiddleSlice(distanceMaps);
        }
        printWriter.println(FVInputFileKeyword.SUBDOMAINS + " " + simGeometrySpec.getNumSubVolumes() + " " + FVInputFileKeyword.DISTANCE_MAP);
        for (int i = 0; i < subVolumes.length; i++) {
            File distanceMapFile = new File(workingDirectory, getSimulationTask().getSimulationJobID() + "_" + subVolumes[i].getName() + DISTANCE_MAP_FILE_EXTENSION);
            writeDistanceMapFile(deltaX, distanceMaps[i], distanceMapFile);
            int phase = subDomainPhaseMap.get(subVolumes[i].getName());
            printWriter.println(subVolumes[i].getName() + " " + phase + " " + distanceMapFile.getAbsolutePath());
        }
    } else {
        printWriter.println(FVInputFileKeyword.SUBDOMAINS + " " + geometrySpec.getNumSubVolumes());
        Expression[] rvachevExps = convertAnalyticGeometryToRvachevFunction(geometrySpec);
        for (int i = 0; i < subVolumes.length; i++) {
            if (subVolumes[i] instanceof AnalyticSubVolume) {
                String name = subVolumes[i].getName();
                int phase = subDomainPhaseMap.get(name);
                printWriter.println(name + " " + phase + " ");
                printWriter.println(FVInputFileKeyword.IF + " " + rvachevExps[i].infix() + ";");
                printWriter.println(FVInputFileKeyword.USER + " " + ((AnalyticSubVolume) subVolumes[i]).getExpression().infix() + ";");
            }
        }
    }
    printWriter.println(FVInputFileKeyword.MAX_BOX_SIZE + " " + chomboSolverSpec.getMaxBoxSize());
    printWriter.println(FVInputFileKeyword.FILL_RATIO + " " + chomboSolverSpec.getFillRatio());
    printWriter.println(FVInputFileKeyword.RELATIVE_TOLERANCE + " " + simulation.getSolverTaskDescription().getErrorTolerance().getRelativeErrorTolerance());
    printWriter.println(FVInputFileKeyword.SAVE_VCELL_OUTPUT + " " + chomboSolverSpec.isSaveVCellOutput());
    printWriter.println(FVInputFileKeyword.SAVE_CHOMBO_OUTPUT + " " + chomboSolverSpec.isSaveChomboOutput());
    printWriter.println(FVInputFileKeyword.ACTIVATE_FEATURE_UNDER_DEVELOPMENT + " " + chomboSolverSpec.isActivateFeatureUnderDevelopment());
    printWriter.println(FVInputFileKeyword.SMALL_VOLFRAC_THRESHOLD + " " + chomboSolverSpec.getSmallVolfracThreshold());
    printWriter.println(FVInputFileKeyword.BLOCK_FACTOR + " " + chomboSolverSpec.getBlockFactor());
    printWriter.println(FVInputFileKeyword.TAGS_GROW + " " + chomboSolverSpec.getTagsGrow());
    // Refinement
    int numLevels = chomboSolverSpec.getNumRefinementLevels();
    // Refinements #Levels ratio 1, ratio 2, etc
    printWriter.print(FVInputFileKeyword.REFINEMENTS + " " + (numLevels + 1));
    List<Integer> ratios = chomboSolverSpec.getRefineRatioList();
    for (int i : ratios) {
        printWriter.print(" " + i);
    }
    // write last refinement ratio, fake
    printWriter.println(" 2");
    // membrane rois
    List<RefinementRoi> memRios = chomboSolverSpec.getMembraneRefinementRois();
    printWriter.println(FVInputFileKeyword.REFINEMENT_ROIS + " " + RoiType.Membrane + " " + memRios.size());
    for (RefinementRoi roi : memRios) {
        if (roi.getRoiExpression() == null) {
            throw new SolverException("ROI expression cannot be null");
        }
        // level tagsGrow ROIexpression
        printWriter.println(roi.getLevel() + " " + roi.getRoiExpression().infix() + ";");
    }
    List<RefinementRoi> volRios = chomboSolverSpec.getVolumeRefinementRois();
    printWriter.println(FVInputFileKeyword.REFINEMENT_ROIS + " " + RoiType.Volume + " " + volRios.size());
    for (RefinementRoi roi : volRios) {
        if (roi.getRoiExpression() == null) {
            throw new SolverException("ROI expression cannot be null");
        }
        printWriter.println(roi.getLevel() + " " + roi.getRoiExpression().infix() + ";");
    }
    printWriter.println(FVInputFileKeyword.VIEW_LEVEL + " " + chomboSolverSpec.getViewLevel());
    printWriter.println(FVInputFileKeyword.CHOMBO_SPEC_END);
    printWriter.println();
}
Also used : Origin(org.vcell.util.Origin) VCPixelClass(cbit.image.VCPixelClass) GeometrySurfaceDescription(cbit.vcell.geometry.surface.GeometrySurfaceDescription) Extent(org.vcell.util.Extent) HashMap(java.util.HashMap) ISize(org.vcell.util.ISize) ArrayList(java.util.ArrayList) VCImage(cbit.image.VCImage) SubvolumeSignedDistanceMap(cbit.vcell.geometry.surface.SubvolumeSignedDistanceMap) GeometrySpec(cbit.vcell.geometry.GeometrySpec) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SubDomain(cbit.vcell.math.SubDomain) MembraneSubDomain(cbit.vcell.math.MembraneSubDomain) RefinementRoi(org.vcell.chombo.RefinementRoi) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) SolverTaskDescription(cbit.vcell.solver.SolverTaskDescription) VCImageUncompressed(cbit.image.VCImageUncompressed) ChomboSolverSpec(org.vcell.chombo.ChomboSolverSpec) Vect3d(cbit.vcell.render.Vect3d) Geometry(cbit.vcell.geometry.Geometry) Simulation(cbit.vcell.solver.Simulation) Expression(cbit.vcell.parser.Expression) CompartmentSubDomain(cbit.vcell.math.CompartmentSubDomain) SolverException(cbit.vcell.solver.SolverException) File(java.io.File) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume)

Example 14 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class ITextWriter method generateGeometryImage.

// pretty similar to its static counterpart
/*
	protected ByteArrayOutputStream generateDocStructureImage(Model model, String resolution) throws Exception {

		if (model == null || !isValidResolutionSetting(resolution)) {
	    	throw new IllegalArgumentException("Invalid parameters for generating structure image for model:" + model.getName());
        }
		ByteArrayOutputStream bos;

		// Create a new model and clone the structures only
		// Getting rid of species so that the image created will not have a problem being added to the document
		// when there are more than 15 species in the model.
		Model sparseModel = new Model(model.getName());
		Structure[] oldStructures = (Structure[])BeanUtils.cloneSerializable(model.getStructures());
		sparseModel.setStructures(oldStructures);
		 
		StructureCartoon scartoon = new StructureCartoon();
		scartoon.setModel(sparseModel);
		scartoon.refreshAll();
		//scartoon.setZoomPercent(scartoon.getZoomPercent()*3);
		BufferedImage dummyBufferedImage = new BufferedImage(DEF_IMAGE_WIDTH, DEF_IMAGE_HEIGHT, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D dummyGraphics = (Graphics2D)dummyBufferedImage.getGraphics();
		Dimension prefDim = scartoon.getPreferedCanvasSize(dummyGraphics);
		
		int width = (int)prefDim.getWidth()*110/100;
		int height = (int)prefDim.getHeight()*110/100;
		if (width < ITextWriter.DEF_IMAGE_WIDTH) {
			width = ITextWriter.DEF_IMAGE_WIDTH;
		}
		if (height < ITextWriter.DEF_IMAGE_HEIGHT) {
			height = ITextWriter.DEF_IMAGE_HEIGHT;
		}

		BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
		Graphics2D g = (Graphics2D)bufferedImage.getGraphics();
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
		while (true) {
			GraphContainerLayout containerLayout = new GraphContainerLayoutVCellClassical();
			containerLayout.layout(scartoon, g, new Dimension(width,height));
			break;
		}
		scartoon.paint(g, null);
		bos = encodeJPEG(bufferedImage);
		return bos;
	}
*/
protected ByteArrayOutputStream generateGeometryImage(Geometry geom) throws Exception {
    GeometrySpec geomSpec = geom.getGeometrySpec();
    IndexColorModel icm = DisplayAdapterService.getHandleColorMap();
    geom.precomputeAll(new GeometryThumbnailImageFactoryAWT());
    VCImage geomImage = geomSpec.getSampledImage().getCurrentValue();
    if (geomImage == null) {
        throw new Exception("generateGeometryImage error : No Image");
    }
    int x = geomImage.getNumX();
    int y = geomImage.getNumY();
    int z = geomImage.getNumZ();
    BufferedImage bufferedImage = null;
    WritableRaster pixelWR = null;
    Image adjImage = null;
    BufferedImage newBufferedImage = null;
    if (geom.getDimension() > 0 && geom.getDimension() < 3) {
        bufferedImage = new BufferedImage(x, y, BufferedImage.TYPE_BYTE_INDEXED, icm);
        pixelWR = bufferedImage.getRaster();
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                pixelWR.setSample(i, j, 0, geomImage.getPixel(i, j, 0));
            }
        }
        // Adjust the image width and height
        // retaining the aspect ratio. Start by adjusting the height, then adjust width to maintain aspect ratio.
        double scaleFactor = 1.0;
        if (x * scaleFactor > DEF_GEOM_WIDTH) {
            scaleFactor = ((double) DEF_GEOM_WIDTH) / x;
        }
        if (y * scaleFactor > DEF_GEOM_HEIGHT) {
            scaleFactor = ((double) DEF_GEOM_HEIGHT) / y;
        }
        int adjX = (int) Math.ceil(x * scaleFactor);
        int adjY = (int) Math.ceil(y * scaleFactor);
        adjImage = bufferedImage.getScaledInstance(adjX, adjY, BufferedImage.SCALE_REPLICATE);
        newBufferedImage = new BufferedImage(adjX, adjY, BufferedImage.TYPE_BYTE_INDEXED, icm);
        newBufferedImage.getGraphics().drawImage(adjImage, 0, 0, null);
    } else if (geom.getDimension() == 3) {
        WritableRaster smallPixelWR = null;
        int[] cmap = new int[256];
        final int DISPLAY_DIM_MAX = 256;
        try {
            // Reset colormap (grayscale)
            for (int i = 0; i < cmap.length; i += 1) {
                int iv = (int) (0x000000FF & i);
                cmap[i] = 0xFF << 24 | iv << 16 | iv << 8 | i;
            }
            // stretch cmap grays
            if (geomImage != null && geomImage.getPixelClasses().length < 32) {
                for (int i = 0; i < geomImage.getPixelClasses().length; i += 1) {
                    int stretchIndex = (int) (0xFF & geomImage.getPixelClasses()[i].getPixel());
                    int newI = 32 + (i * ((256 - 32) / geomImage.getPixelClasses().length));
                    cmap[stretchIndex] = 0xFF << 24 | newI << 16 | newI << 8 | newI;
                }
            }
            // Set grid color
            // white
            cmap[cmap.length - 1] = 0xFFFFFFFF;
            // Initialize image data
            int xSide = 0;
            int ySide = 0;
            if (pixelWR == null) {
                VCImage sampledImage = geomImage;
                double side = Math.sqrt(x * y * z);
                xSide = (int) Math.round(side / (double) x);
                if (xSide == 0) {
                    xSide = 1;
                }
                if (xSide > z) {
                    xSide = z;
                }
                ySide = (int) Math.ceil((double) z / (double) xSide);
                if (ySide == 0) {
                    ySide = 1;
                }
                if (ySide > z) {
                    ySide = z;
                }
                pixelWR = icm.createCompatibleWritableRaster(xSide * x, ySide * y);
                byte[] sib = sampledImage.getPixels();
                // write the image to buffer
                int ystride = x;
                int zstride = x * y;
                for (int row = 0; row < ySide; row += 1) {
                    for (int col = 0; col < xSide; col += 1) {
                        int xoffset = col * x;
                        int yoffset = (row * y);
                        int zoffset = (col + (row * xSide)) * zstride;
                        if (zoffset >= sib.length) {
                            for (int xi = 0; xi < x; xi += 1) {
                                for (int yi = 0; yi < y; yi += 1) {
                                    pixelWR.setSample(xi + xoffset, yi + yoffset, 0, cmap.length - 1);
                                }
                            }
                        } else {
                            for (int xi = 0; xi < x; xi += 1) {
                                for (int yi = 0; yi < y; yi += 1) {
                                    pixelWR.setSample(xi + xoffset, yi + yoffset, 0, (int) (0xFF & sib[xi + (ystride * yi) + zoffset]));
                                }
                            }
                        }
                    }
                }
                // scale if necessary
                double displayScale = 1.0;
                if (pixelWR.getWidth() < DISPLAY_DIM_MAX || pixelWR.getHeight() < DISPLAY_DIM_MAX) {
                    displayScale = (int) Math.min((DISPLAY_DIM_MAX / pixelWR.getWidth()), (DISPLAY_DIM_MAX / pixelWR.getHeight()));
                    if (displayScale == 0) {
                        displayScale = 1;
                    }
                }
                if ((displayScale == 1) && (pixelWR.getWidth() > DISPLAY_DIM_MAX || pixelWR.getHeight() > DISPLAY_DIM_MAX)) {
                    displayScale = Math.max((pixelWR.getWidth() / DISPLAY_DIM_MAX), (pixelWR.getHeight() / DISPLAY_DIM_MAX));
                    // displayScale = Math.min(((double)DISPLAY_DIM_MAX/(double)pixelWR.getWidth()),((double)DISPLAY_DIM_MAX/(double)pixelWR.getHeight()));
                    if (displayScale == 0) {
                        displayScale = 1;
                    }
                    displayScale = 1.0 / displayScale;
                }
                if (displayScale != 1) {
                    java.awt.geom.AffineTransform at = new java.awt.geom.AffineTransform();
                    at.setToScale(displayScale, displayScale);
                    java.awt.image.AffineTransformOp ato = new java.awt.image.AffineTransformOp(at, java.awt.image.AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
                    smallPixelWR = ato.createCompatibleDestRaster(pixelWR);
                    ato.filter(pixelWR, smallPixelWR);
                }
            }
            // draw labels and grid
            if (pixelWR != null) {
                bufferedImage = new java.awt.image.BufferedImage(icm, smallPixelWR, false, null);
                if (xSide > 0 || ySide > 0) {
                    float gridXBlockLen = ((float) (bufferedImage.getWidth()) / xSide);
                    float gridYBlockLen = ((float) (bufferedImage.getHeight()) / ySide);
                    java.awt.Graphics g = bufferedImage.getGraphics();
                    g.setColor(java.awt.Color.white);
                    // horiz lines
                    for (int row = 0; row < ySide; row += 1) {
                        if (row > 0) {
                            g.drawLine(0, (int) (row * gridYBlockLen), bufferedImage.getWidth(), (int) (row * gridYBlockLen));
                        }
                    }
                    // vert lines
                    for (int col = 0; col < xSide; col += 1) {
                        if (col > 0) {
                            g.drawLine((int) (col * gridXBlockLen), 0, (int) (col * gridXBlockLen), bufferedImage.getHeight());
                        }
                    }
                    // z markers
                    if (xSide > 1 || ySide > 1) {
                        for (int row = 0; row < xSide; row += 1) {
                            for (int col = 0; col < ySide; col += 1) {
                                g.drawString("" + (1 + row + (col * xSide)), (int) (row * gridXBlockLen) + 3, (int) (col * gridYBlockLen) + 12);
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            throw new Exception("CreateGeometryImageIcon error\n" + (e.getMessage() != null ? e.getMessage() : e.getClass().getName()));
        }
        // Adjust the image width and height
        adjImage = bufferedImage.getScaledInstance(smallPixelWR.getWidth(), smallPixelWR.getHeight(), BufferedImage.SCALE_REPLICATE);
        newBufferedImage = new BufferedImage(smallPixelWR.getWidth(), smallPixelWR.getHeight(), BufferedImage.TYPE_BYTE_INDEXED, icm);
        newBufferedImage.getGraphics().drawImage(adjImage, 0, 0, null);
    }
    ByteArrayOutputStream bos = null;
    bos = encodeJPEG(newBufferedImage);
    return bos;
}
Also used : VCImage(cbit.image.VCImage) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IIOImage(javax.imageio.IIOImage) VCImage(cbit.image.VCImage) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) DocumentException(com.lowagie.text.DocumentException) ExpressionException(cbit.vcell.parser.ExpressionException) BufferedImage(java.awt.image.BufferedImage) GeometrySpec(cbit.vcell.geometry.GeometrySpec) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) WritableRaster(java.awt.image.WritableRaster) IndexColorModel(java.awt.image.IndexColorModel)

Example 15 with VCImage

use of cbit.image.VCImage in project vcell by virtualcell.

the class XmlHelper method XMLToImage.

static VCImage XMLToImage(String xmlString, boolean printKeys) throws XmlParseException {
    Namespace ns = Namespace.getNamespace(XMLTags.VCML_NS);
    if (xmlString == null || xmlString.length() == 0) {
        throw new XmlParseException("Invalid xml for Image: " + xmlString);
    }
    // default parser and no validation
    Element root = (XmlUtil.stringToXML(xmlString, null)).getRootElement();
    Element extentElement = root.getChild(XMLTags.ExtentTag, ns);
    Element imageElement = root.getChild(XMLTags.ImageTag, ns);
    // Element extentElement = root.getChild(XMLTags.ExtentTag);
    // Element imageElement = root.getChild(XMLTags.ImageTag);
    XmlReader reader = new XmlReader(printKeys, ns);
    Extent extent = reader.getExtent(extentElement);
    VCImage vcImage = reader.getVCImage(imageElement, extent);
    vcImage.refreshDependencies();
    return vcImage;
}
Also used : Extent(org.vcell.util.Extent) Element(org.jdom.Element) VCImage(cbit.image.VCImage) Namespace(org.jdom.Namespace)

Aggregations

VCImage (cbit.image.VCImage)54 Geometry (cbit.vcell.geometry.Geometry)22 Extent (org.vcell.util.Extent)20 ISize (org.vcell.util.ISize)19 VCImageUncompressed (cbit.image.VCImageUncompressed)18 ImageException (cbit.image.ImageException)16 PropertyVetoException (java.beans.PropertyVetoException)15 DataAccessException (org.vcell.util.DataAccessException)15 KeyValue (org.vcell.util.document.KeyValue)15 SubVolume (cbit.vcell.geometry.SubVolume)14 Origin (org.vcell.util.Origin)13 RegionImage (cbit.vcell.geometry.RegionImage)11 SurfaceClass (cbit.vcell.geometry.SurfaceClass)11 ObjectNotFoundException (org.vcell.util.ObjectNotFoundException)11 UserCancelException (org.vcell.util.UserCancelException)11 ImageSubVolume (cbit.vcell.geometry.ImageSubVolume)10 Expression (cbit.vcell.parser.Expression)10 VCPixelClass (cbit.image.VCPixelClass)9 BioModel (cbit.vcell.biomodel.BioModel)8 FieldDataFileOperationSpec (cbit.vcell.field.io.FieldDataFileOperationSpec)8