Search in sources :

Example 6 with GeometrySpec

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

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

the class MovingBoundaryFileWriter method getLevelFunction.

private Element getLevelFunction() throws ExpressionException {
    Element e = new Element(MBTags.levelFunction);
    // geometry shape encode in "LevelFunction".
    GeometrySpec geometrySpec = geometry.getGeometrySpec();
    if (geometry.getGeometrySpec().hasImage()) {
        throw new RuntimeException("image-based geometry not yet supported");
    } else {
        Expression[] rvachevExps = FiniteVolumeFileWriter.convertAnalyticGeometryToRvachevFunction(geometrySpec);
        if (rvachevExps.length == 2) {
            Expression levelFunction = rvachevExps[0];
            String content = levelFunction.infix();
            e.setText(content);
        } else {
            throw new IllegalArgumentException("Can't get level function, expected 2 RvachevFunction expressions, got " + rvachevExps.length);
        }
    }
    return e;
}
Also used : GeometrySpec(cbit.vcell.geometry.GeometrySpec) Expression(cbit.vcell.parser.Expression) Element(org.jdom.Element)

Example 8 with GeometrySpec

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

the class GeometrySubVolumeTableModel method setValueAt.

public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
    if (rowIndex < 0 || rowIndex >= getRowCount()) {
        throw new RuntimeException("GeometrySubVolumeTableModel.setValueAt(), row = " + rowIndex + " out of range [" + 0 + "," + (getRowCount() - 1) + "]");
    }
    if (columnIndex < 0 || columnIndex >= getColumnCount()) {
        throw new RuntimeException("GeometrySubVolumeTableModel.setValueAt(), column = " + columnIndex + " out of range [" + 0 + "," + (getColumnCount() - 1) + "]");
    }
    final SubVolume subVolume = getValueAt(rowIndex);
    try {
        switch(columnIndex) {
            case COLUMN_NAME:
                {
                    final String newName = (String) aValue;
                    final String oldName = subVolume.getName();
                    subVolume.setName(newName);
                    AsynchClientTask task1 = new AsynchClientTask("changing the name", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

                        @Override
                        public void run(Hashtable<String, Object> hashTable) throws Exception {
                            getGeometry().precomputeAll(new GeometryThumbnailImageFactoryAWT());
                            GeometrySpec gs = getGeometry().getGeometrySpec();
                            if (gs != null) {
                                gs.geometryNameChanged(oldName, newName);
                            } else {
                                if (lg.isEnabledFor(Level.WARN)) {
                                    lg.warn(getGeometry().getDescription() + " has no GeometrySpec?");
                                }
                            }
                        }
                    };
                    ClientTaskDispatcher.dispatch(ownerTable, new Hashtable<String, Object>(), new AsynchClientTask[] { task1 }, false);
                    break;
                }
            case COLUMN_VALUE:
                {
                    if (subVolume instanceof AnalyticSubVolume) {
                        final AnalyticSubVolume analyticSubVolume = (AnalyticSubVolume) subVolume;
                        if (aValue instanceof ScopedExpression) {
                            throw new RuntimeException("unexpected value type ScopedExpression");
                        } else if (aValue instanceof String) {
                            final String newExpressionString = (String) aValue;
                            analyticSubVolume.setExpression(new Expression(newExpressionString));
                            AsynchClientTask task1 = new AsynchClientTask("changing the expression", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

                                @Override
                                public void run(Hashtable<String, Object> hashTable) throws Exception {
                                    getGeometry().precomputeAll(new GeometryThumbnailImageFactoryAWT());
                                }
                            };
                            ClientTaskDispatcher.dispatch(ownerTable, new Hashtable<String, Object>(), new AsynchClientTask[] { task1 }, false);
                        }
                    }
                    break;
                }
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        DialogUtils.showErrorDialog(ownerTable, e.getMessage(), e);
    }
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) GeometrySpec(cbit.vcell.geometry.GeometrySpec) GeometryThumbnailImageFactoryAWT(cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT) ScopedExpression(cbit.gui.ScopedExpression) ScopedExpression(cbit.gui.ScopedExpression) Expression(cbit.vcell.parser.Expression) SubVolume(cbit.vcell.geometry.SubVolume) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume) CSGObject(cbit.vcell.geometry.CSGObject) AnalyticSubVolume(cbit.vcell.geometry.AnalyticSubVolume)

Example 9 with GeometrySpec

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

the class GeometryViewer method refreshSourceDataInfo.

/**
 * connEtoM2:  (Geometry.this --> ImagePlaneManagerPanel1.sourceDataInfo)
 * @param value cbit.vcell.geometry.Geometry
 */
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void refreshSourceDataInfo() {
    if (getGeometry() == null) {
        return;
    }
    GeometrySpec geometrySpec = getGeometry().getGeometrySpec();
    if (geometrySpec.getSampledImage().isDirty()) {
        return;
    }
    VCImage sampledImage = geometrySpec.getSampledImage().getCurrentValue();
    try {
        SourceDataInfo sdi = new SourceDataInfo(SourceDataInfo.INDEX_TYPE, sampledImage.getPixels(), geometrySpec.getExtent(), geometrySpec.getOrigin(), null, 0, sampledImage.getNumX(), 1, sampledImage.getNumY(), sampledImage.getNumX(), sampledImage.getNumZ(), sampledImage.getNumX() * sampledImage.getNumY());
        getImagePlaneManagerPanel1().setSourceDataInfo(sdi);
    } catch (ImageException e) {
        e.printStackTrace();
        DialogUtils.showErrorDialog(this, e.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        DialogUtils.showErrorDialog(this, e.getMessage(), e);
    }
}
Also used : GeometrySpec(cbit.vcell.geometry.GeometrySpec) ImageException(cbit.image.ImageException) VCImage(cbit.image.VCImage) SourceDataInfo(cbit.image.SourceDataInfo) ImageException(cbit.image.ImageException)

Example 10 with GeometrySpec

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

the class GeomDbDriver method insertGeometry.

/**
 * This method was created in VisualAge.
 */
private void insertGeometry(InsertHashtable hash, QueryHashtable dbc, Connection con, User user, Geometry geom, KeyValue updatedImageKey, Version newVersion, boolean bVersionChildren) throws ImageException, SQLException, DataAccessException, RecordChangedException {
    // log.print("GeomDbDriver.insertGeometry(" + geom + ")");
    // everybody needs to be in synch 'cause children may be manipulated...
    geom.refreshDependencies();
    KeyValue extentKey = null;
    GeometrySpec geometrySpec = geom.getGeometrySpec();
    if (geometrySpec.getImage() != null) {
        // //try {
        // imageVersionKey = hash.getDatabaseKey(geometrySpec.getImage());
        // if (imageVersionKey==null){
        // if(geometrySpec.getImage().getVersion()!=null && geometrySpec.getImage().getVersion().getVersionKey() != null){
        // imageVersionKey = updateVersionable(hash, con, user, geometrySpec.getImage(), bVersionChildren);
        // }else{
        // String imageName = geometrySpec.getImage().getName(); // + "_image";
        // while (isNameUsed(con,VersionableType.VCImage,user,imageName)){
        // imageName = cbit.util.TokenMangler.getNextRandomToken(imageName);
        // }
        // imageVersionKey = insertVersionable(hash, con, user, geometrySpec.getImage(),imageName ,bVersionChildren);
        // }
        // try{
        // geometrySpec.setImage(getVCImage(con,user,imageVersionKey));
        // }catch(PropertyVetoException e){
        // e.printStackTrace();
        // throw new DataAccessException(e.getMessage());
        // }
        // }
        // //} catch (RecordChangedException rce) {
        // //	throw rce;
        // //}
        extentKey = getExtentRefKeyFromImage(con, updatedImageKey);
    }
    // 
    if (extentKey == null) {
        extentKey = keyFactory.getNewKey(con);
        insertExtentSQL(con, extentKey, geometrySpec.getExtent().getX(), geometrySpec.getExtent().getY(), geometrySpec.getExtent().getZ());
    }
    // 
    insertGeometrySQL(con, geom, updatedImageKey, extentKey, newVersion, user);
    hash.put(geom, newVersion.getVersionKey());
    if (updatedImageKey != null && !updatedImageKey.equals(geom.getGeometrySpec().getImage().getKey())) {
        VCImage resavedImage = getVCImage(dbc, con, user, updatedImageKey, true);
        try {
            geom.getGeometrySpec().setImage(resavedImage);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
            throw new DataAccessException(e.getMessage());
        }
    }
    insertSubVolumesSQL(hash, con, geom, newVersion.getVersionKey());
    insertSurfaceClassesSQL(hash, con, geom, newVersion.getVersionKey());
    if (geom.getDimension() > 0) {
        insertGeometrySurfaceDescriptionSQL(hash, con, geom, newVersion.getVersionKey());
        insertFilamentsSQL(con, geom, newVersion.getVersionKey());
    }
}
Also used : GeometrySpec(cbit.vcell.geometry.GeometrySpec) PropertyVetoException(java.beans.PropertyVetoException) KeyValue(org.vcell.util.document.KeyValue) VCImage(cbit.image.VCImage) DataAccessException(org.vcell.util.DataAccessException)

Aggregations

GeometrySpec (cbit.vcell.geometry.GeometrySpec)23 SubVolume (cbit.vcell.geometry.SubVolume)12 VCImage (cbit.image.VCImage)7 SurfaceClass (cbit.vcell.geometry.SurfaceClass)6 GeometrySurfaceDescription (cbit.vcell.geometry.surface.GeometrySurfaceDescription)6 Expression (cbit.vcell.parser.Expression)6 ArrayList (java.util.ArrayList)6 AnalyticSubVolume (cbit.vcell.geometry.AnalyticSubVolume)5 Geometry (cbit.vcell.geometry.Geometry)5 GeometryThumbnailImageFactoryAWT (cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT)5 GeometricRegion (cbit.vcell.geometry.surface.GeometricRegion)5 SurfaceGeometricRegion (cbit.vcell.geometry.surface.SurfaceGeometricRegion)5 VolumeGeometricRegion (cbit.vcell.geometry.surface.VolumeGeometricRegion)5 CompartmentSubDomain (cbit.vcell.math.CompartmentSubDomain)5 MembraneSubDomain (cbit.vcell.math.MembraneSubDomain)5 Extent (org.vcell.util.Extent)5 Origin (org.vcell.util.Origin)5 CSGObject (cbit.vcell.geometry.CSGObject)4 ISize (org.vcell.util.ISize)4 VCImageUncompressed (cbit.image.VCImageUncompressed)3