use of org.vcell.util.ISize in project vcell by virtualcell.
the class RunRefSimulationOp method saveExternalData.
private static void saveExternalData(Image image, String varName, ExternalDataIdentifier newROIExtDataID, LocalWorkspace localWorkspace) throws ObjectNotFoundException, ImageException, IOException {
Extent extent = image.getExtent();
Origin origin = image.getOrigin();
ISize isize = image.getISize();
VCImage vcImage = new VCImageUncompressed(null, new byte[isize.getXYZ()], extent, isize.getX(), isize.getY(), isize.getZ());
RegionImage regionImage = new RegionImage(vcImage, 0, null, null, RegionImage.NO_SMOOTHING);
CartesianMesh simpleCartesianMesh = CartesianMesh.createSimpleCartesianMesh(origin, extent, isize, regionImage);
int NumTimePoints = 1;
int NumChannels = 1;
// dimensions: time points, channels, whole image ordered by z slices.
double[][][] pixData = new double[NumTimePoints][NumChannels][];
pixData[0][0] = image.getDoublePixels();
FieldDataFileOperationSpec fdos = new FieldDataFileOperationSpec();
fdos.opType = FieldDataFileOperationSpec.FDOS_ADD;
fdos.cartesianMesh = simpleCartesianMesh;
fdos.doubleSpecData = pixData;
fdos.specEDI = newROIExtDataID;
fdos.varNames = new String[] { varName };
fdos.owner = LocalWorkspace.getDefaultOwner();
fdos.times = new double[] { 0.0 };
fdos.variableTypes = new VariableType[] { VariableType.VOLUME };
fdos.origin = origin;
fdos.extent = extent;
fdos.isize = isize;
localWorkspace.getDataSetControllerImpl().fieldDataFileOperation(fdos);
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class BioformatsImageDatasetReader method getImageSizeInfo.
@Override
public ImageSizeInfo getImageSizeInfo(String fileName) throws Exception {
try (TTransport transport = new TSocket("localhost", port)) {
transport.open();
TProtocol protocol = new TBinaryProtocol(transport);
ImageDatasetService.Client client = new ImageDatasetService.Client(protocol);
org.vcell.imagedataset.ImageSizeInfo t_imageSizeInfo = client.getImageSizeInfo(fileName);
org.vcell.imagedataset.ISize t_size = t_imageSizeInfo.getISize();
double[] timePoints = new double[t_imageSizeInfo.getTimePoints().size()];
for (int i = 0; i < t_imageSizeInfo.getTimePointsSize(); i++) {
timePoints[i] = t_imageSizeInfo.getTimePoints().get(i);
}
ImageSizeInfo imageSizeInfo = new ImageSizeInfo(t_imageSizeInfo.imagePath, new ISize(t_size.getX(), t_size.getY(), t_size.getZ()), t_imageSizeInfo.numChannels, timePoints, t_imageSizeInfo.selectedTimeIndex);
return imageSizeInfo;
}
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class ClientRequestManager method getParseImageTask.
public static AsynchClientTask getParseImageTask(final Component requesterComp, final VCDocument.DocumentCreationInfo documentCreationInfo, final MDIManager mdiManager) {
AsynchClientTask parseImageTask = new AsynchClientTask("read and parse image file", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
@Override
public void run(final Hashtable<String, Object> hashTable) throws Exception {
final Component guiParent = (Component) hashTable.get(ClientRequestManager.GUI_PARENT);
try {
FieldDataFileOperationSpec fdfos = null;
// }
if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FILE) // || documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIJI_IMAGEJ ||
// documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_BLENDER
{
File imageFile = (File) hashTable.get(IMAGE_FILE);
if (imageFile == null) {
throw new Exception("No file selected");
}
if (ExtensionFilter.isMatchingExtension(imageFile, ".nrrd")) {
DataInputStream dis = null;
try {
dis = new DataInputStream(new BufferedInputStream(new FileInputStream(imageFile)));
int xsize = 1;
int ysize = 1;
int zsize = 1;
double xspace = 1.0;
double yspace = 1.0;
double zspace = 1.0;
NRRDTYPE type = null;
NRRDENCODING encoding = null;
int dimension = -1;
// read header lines
while (true) {
@SuppressWarnings("deprecation") String line = dis.readLine();
if (line == null || line.length() == 0) {
break;
}
StringTokenizer stringTokenizer = new StringTokenizer(line, ": ");
String headerParam = stringTokenizer.nextToken();
// System.out.println(headerParam);
if (headerParam.equals("sizes")) {
if (dimension != -1) {
xsize = Integer.parseInt(stringTokenizer.nextToken());
if (dimension >= 2) {
ysize = Integer.parseInt(stringTokenizer.nextToken());
}
if (dimension >= 3) {
zsize = Integer.parseInt(stringTokenizer.nextToken());
}
for (int i = 4; i < dimension; i++) {
if (Integer.parseInt(stringTokenizer.nextToken()) != 1) {
throw new Exception("Dimensions > 3 not supported");
}
}
} else {
throw new Exception("dimension expected to be set before reading sizes");
}
} else if (headerParam.equals("spacings")) {
if (dimension != -1) {
xspace = Double.parseDouble(stringTokenizer.nextToken());
if (dimension >= 2) {
yspace = Double.parseDouble(stringTokenizer.nextToken());
}
if (dimension >= 3) {
zspace = Double.parseDouble(stringTokenizer.nextToken());
}
// ignore other dimension spacings
} else {
throw new Exception("dimension expected to be set before reading spacings");
}
} else if (headerParam.equals("type")) {
String nextToken = stringTokenizer.nextToken();
if (nextToken.equalsIgnoreCase("double")) {
type = NRRDTYPE.DOUBLE;
} else if (nextToken.equalsIgnoreCase("float")) {
type = NRRDTYPE.FLOAT;
} else if (nextToken.equalsIgnoreCase("unsigned")) {
nextToken = stringTokenizer.nextToken();
if (nextToken.equalsIgnoreCase("char")) {
type = NRRDTYPE.UNSIGNEDCHAR;
} else {
throw new Exception("Unknown nrrd data type=" + nextToken);
}
} else {
throw new Exception("Unknown nrrd data type=" + nextToken);
}
} else if (headerParam.equals("dimension")) {
dimension = Integer.parseInt(stringTokenizer.nextToken());
if (dimension < 1) {
throw new Exception("unexpected dimension=" + dimension);
}
} else if (headerParam.equals("encoding")) {
encoding = NRRDENCODING.valueOf(stringTokenizer.nextToken().toUpperCase());
}
}
BufferedInputStream bis = null;
if (encoding == NRRDENCODING.GZIP) {
dis.close();
bis = new BufferedInputStream(new FileInputStream(imageFile));
boolean bnewLine = false;
while (true) {
int currentChar = bis.read();
if (currentChar == '\n') {
if (bnewLine) {
// 2 newlines end header
break;
}
bnewLine = true;
} else {
bnewLine = false;
}
}
GZIPInputStream gzipInputStream = new GZIPInputStream(bis);
dis = new DataInputStream(gzipInputStream);
}
double[] data = new double[xsize * ysize * zsize];
double minValue = Double.POSITIVE_INFINITY;
double maxValue = Double.NEGATIVE_INFINITY;
for (int i = 0; i < data.length; i++) {
if (i % 262144 == 0) {
if (getClientTaskStatusSupport() != null) {
getClientTaskStatusSupport().setMessage("Reading " + encoding + " " + type + " NRRD data " + (((long) i * (long) 100) / (long) data.length) + " % done.");
}
}
if (type == NRRDTYPE.DOUBLE) {
data[i] = dis.readDouble();
} else if (type == NRRDTYPE.FLOAT) {
data[i] = dis.readFloat();
} else if (type == NRRDTYPE.UNSIGNEDCHAR) {
data[i] = dis.readUnsignedByte();
} else {
throw new Exception("Unexpected data type=" + type.toString());
}
minValue = Math.min(minValue, data[i]);
maxValue = Math.max(maxValue, data[i]);
}
dis.close();
if (getClientTaskStatusSupport() != null) {
getClientTaskStatusSupport().setMessage("Scaling " + encoding + " " + type + " NRRD data.");
}
short[] dataToSegment = new short[data.length];
double scaleShort = Math.pow(2, Short.SIZE) - 1;
for (int i = 0; i < data.length; i++) {
dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
}
fdfos = new FieldDataFileOperationSpec();
fdfos.origin = new Origin(0, 0, 0);
fdfos.extent = new Extent((xsize == 1 ? .5 : (xsize) * xspace), (ysize == 1 ? .5 : (ysize) * yspace), (zsize == 1 ? .5 : (zsize) * zspace));
fdfos.isize = new ISize(xsize, ysize, zsize);
fdfos.shortSpecData = new short[][][] { { dataToSegment } };
} finally {
if (dis != null) {
try {
dis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
} else if ((fdfos = createFDOSFromSurfaceFile(imageFile)) != null) {
// try surface file formats
// work already done at this point
} else {
File[] dirFiles = null;
ImageSizeInfo origImageSizeInfo = null;
ImageDatasetReaderService imageDatasetReaderServiceInstance = ImageDatasetReaderService.getInstance();
ImageDatasetReader imageDatasetReader = imageDatasetReaderServiceInstance.getImageDatasetReader();
if (imageFile.isDirectory()) {
dirFiles = imageFile.listFiles(new java.io.FileFilter() {
public boolean accept(File pathname) {
// exclude windows Thumbs.db
return pathname.isFile() && !pathname.isHidden();
}
});
if (dirFiles.length == 0) {
throw new Exception("No valid files in selected directory");
}
String fileExt0 = null;
for (int i = 0; i < dirFiles.length; i++) {
int lastDot = dirFiles[i].getName().lastIndexOf('.');
String fileExt = (lastDot != -1 ? dirFiles[i].getName().substring(lastDot) : null);
if (dirFiles[i].isDirectory()) {
fileExt = "dir";
}
if (i == 0) {
fileExt0 = fileExt;
} else if (!Compare.isEqualOrNull(fileExt, fileExt0)) {
String result = DialogUtils.showWarningDialog(requesterComp, "Files in '" + imageFile.getAbsolutePath() + "' have different name extensions, continue?", new String[] { "OK", "Cancel" }, "Cancel");
if (!"OK".equals(result)) {
throw UserCancelException.CANCEL_FILE_SELECTION;
}
break;
}
}
hashTable.put(IMPORT_SOURCE_NAME, "Directory: " + imageFile.getAbsolutePath());
origImageSizeInfo = imageDatasetReader.getImageSizeInfoForceZ(dirFiles[0].getAbsolutePath(), dirFiles.length);
if (dirFiles.length > 1) {
final String importZ = "Import Z-Sections";
final String cancelOption = "Cancel";
String result = DialogUtils.showWarningDialog(guiParent, "Import all files in directory '" + imageFile.getAbsolutePath() + "' as Z-Sections", new String[] { importZ, cancelOption }, importZ);
if (result.equals(cancelOption)) {
throw UserCancelException.CANCEL_GENERIC;
}
}
hashTable.put(DIR_FILES, dirFiles);
} else {
origImageSizeInfo = imageDatasetReader.getImageSizeInfoForceZ(imageFile.getAbsolutePath(), null);
hashTable.put(IMPORT_SOURCE_NAME, "File: " + imageFile.getAbsolutePath());
}
hashTable.put(ORIG_IMAGE_SIZE_INFO, origImageSizeInfo);
return;
}
} else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FIELDDATA) {
getClientTaskStatusSupport().setMessage("Reading data from VCell server.");
VCDocument.GeomFromFieldDataCreationInfo docInfo = (VCDocument.GeomFromFieldDataCreationInfo) documentCreationInfo;
PDEDataContext pdeDataContext = mdiManager.getFieldDataWindowManager().getPDEDataContext(docInfo.getExternalDataID(), null);
ImageSizeInfo newImageSizeInfo = (ImageSizeInfo) hashTable.get(NEW_IMAGE_SIZE_INFO);
pdeDataContext.setVariableNameAndTime(docInfo.getVarName(), newImageSizeInfo.getTimePoints()[newImageSizeInfo.getSelectedTimeIndex()]);
double[] data = pdeDataContext.getDataValues();
hashTable.put(INITIAL_ANNOTATION, hashTable.get(IMPORT_SOURCE_NAME));
CartesianMesh mesh = (CartesianMesh) hashTable.get(FD_MESH);
ISize meshISize = (ISize) hashTable.get(FD_MESHISIZE);
double minValue = Double.POSITIVE_INFINITY;
double maxValue = Double.NEGATIVE_INFINITY;
for (int i = 0; i < data.length; i++) {
minValue = Math.min(minValue, data[i]);
maxValue = Math.max(maxValue, data[i]);
}
short[] dataToSegment = new short[data.length];
double scaleShort = Math.pow(2, Short.SIZE) - 1;
for (int i = 0; i < data.length; i++) {
dataToSegment[i] |= (int) ((data[i] - minValue) / (maxValue - minValue) * scaleShort);
}
fdfos = new FieldDataFileOperationSpec();
fdfos.origin = mesh.getOrigin();
fdfos.extent = mesh.getExtent();
fdfos.isize = meshISize;
fdfos.shortSpecData = new short[][][] { { dataToSegment } };
} else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_SCRATCH) {
ISize isize = getISizeFromUser(guiParent, new ISize(256, 256, 8), "Enter # of pixels for x,y,z (e.g. 3D{256,256,8}, 2D{256,256,1}, 1D{256,1,1})");
fdfos = new FieldDataFileOperationSpec();
fdfos.origin = new Origin(0, 0, 0);
fdfos.extent = new Extent(1, 1, 1);
fdfos.isize = isize;
hashTable.put(IMPORT_SOURCE_NAME, "Scratch: New Geometry");
// final int SCRATCH_SIZE_LIMIT = 512*512*20;
// if(isize.getXYZ() > (SCRATCH_SIZE_LIMIT)){
// throw new Exception("Total pixels (x*y*z) cannot be >"+SCRATCH_SIZE_LIMIT+".");
// }
} else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_ANALYTIC) {
if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
ISize defaultISize = workspaceGeom.getGeometrySpec().getDefaultSampledImageSize();
ISize isize = getISizeFromUser(guiParent, defaultISize, "Warning: converting analytic expression geometry into an image based geometry\nwill remove analytic expressions after new image is created.\n\n" + "Enter size (x,y,z) for new geometry image (e.g. " + defaultISize.getX() + "," + defaultISize.getY() + "," + defaultISize.getZ() + ")");
hashTable.put(IMPORT_SOURCE_NAME, "Workspace from Analytic Geometry");
VCImage img = workspaceGeom.getGeometrySpec().createSampledImage(isize);
Enumeration<SubVolume> enumSubvolume = workspaceGeom.getGeometrySpec().getAnalyticOrCSGSubVolumes();
ArrayList<VCPixelClass> vcPixelClassArrList = new ArrayList<VCPixelClass>();
while (enumSubvolume.hasMoreElements()) {
SubVolume subVolume = enumSubvolume.nextElement();
vcPixelClassArrList.add(new VCPixelClass(null, subVolume.getName(), subVolume.getHandle()));
}
if (vcPixelClassArrList.size() > img.getPixelClasses().length) {
String result = DialogUtils.showOKCancelWarningDialog(requesterComp, null, "Warning: sampling size is too small to include all subvolumes.");
if (result == null || !result.equals(SimpleUserMessage.OPTION_OK)) {
throw UserCancelException.CANCEL_GENERIC;
}
}
hashTable.put(VCPIXELCLASSES, vcPixelClassArrList.toArray(new VCPixelClass[0]));
fdfos = createFDOSFromVCImage(img);
} else {
throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE_ANALYTIC");
}
} else if (documentCreationInfo.getOption() == VCDocument.GEOM_OPTION_FROM_WORKSPACE_IMAGE) {
if (hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE) != null) {
Geometry workspaceGeom = (Geometry) hashTable.get(ClientRequestManager.GEOM_FROM_WORKSPACE);
hashTable.put(IMPORT_SOURCE_NAME, "Workspace Image");
fdfos = createFDOSFromVCImage(workspaceGeom.getGeometrySpec().getImage());
if (workspaceGeom.getGeometrySpec().getImage().getDescription() != null) {
hashTable.put(INITIAL_ANNOTATION, workspaceGeom.getGeometrySpec().getImage().getDescription());
}
GeometryClass[] myGeometryClasses = workspaceGeom.getGeometryClasses();
VCPixelClass[] myPixelClasses = workspaceGeom.getGeometrySpec().getImage().getPixelClasses();
VCPixelClass[] newPixelClasses = new VCPixelClass[myPixelClasses.length];
for (int i = 0; i < myPixelClasses.length; i++) {
for (int j = 0; j < myGeometryClasses.length; j++) {
if (myGeometryClasses[j] instanceof ImageSubVolume && myPixelClasses[i].getPixel() == ((ImageSubVolume) myGeometryClasses[j]).getPixelValue()) {
newPixelClasses[i] = new VCPixelClass(null, myGeometryClasses[j].getName(), myPixelClasses[i].getPixel());
break;
}
}
}
hashTable.put(VCPIXELCLASSES, newPixelClasses);
} else {
throw new Exception("Expecting image source for GEOM_OPTION_FROM_WORKSPACE");
}
}
hashTable.put(FDFOS, fdfos);
} catch (DataFormatException ex) {
throw new Exception("Cannot read image file.\n" + ex.getMessage());
}
}
};
return parseImageTask;
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class ClientRequestManager method resizeImage.
private static void resizeImage(FieldDataFileOperationSpec fdfos, ISize newImagesISize, int imageType) throws Exception {
final int ORIG_XYSIZE = fdfos.isize.getX() * fdfos.isize.getY();
try {
int xsize = newImagesISize.getX();
int ysize = newImagesISize.getY();
double scaleFactor = (double) newImagesISize.getX() / (double) fdfos.isize.getX();
if (xsize != fdfos.isize.getX() || ysize != fdfos.isize.getY()) {
// this normally contains different variables but is
int numChannels = fdfos.shortSpecData[0].length;
// used for channels here
// resize each z section to xsize,ysize
AffineTransform scaleAffineTransform = AffineTransform.getScaleInstance(scaleFactor, scaleFactor);
AffineTransformOp scaleAffineTransformOp = new AffineTransformOp(scaleAffineTransform, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
short[][][] resizeData = new short[1][numChannels][fdfos.isize.getZ() * xsize * ysize];
for (int c = 0; c < numChannels; c++) {
BufferedImage originalImage = new BufferedImage(fdfos.isize.getX(), fdfos.isize.getY(), BufferedImage.TYPE_USHORT_GRAY);
BufferedImage scaledImage = new BufferedImage(xsize, ysize, BufferedImage.TYPE_USHORT_GRAY);
for (int z = 0; z < fdfos.isize.getZ(); z++) {
short[] originalImageBuffer = ((DataBufferUShort) (originalImage.getRaster().getDataBuffer())).getData();
System.arraycopy(fdfos.shortSpecData[0][c], z * ORIG_XYSIZE, originalImageBuffer, 0, ORIG_XYSIZE);
scaleAffineTransformOp.filter(originalImage, scaledImage);
short[] scaledImageBuffer = ((DataBufferUShort) (scaledImage.getRaster().getDataBuffer())).getData();
System.arraycopy(scaledImageBuffer, 0, resizeData[0][c], z * xsize * ysize, xsize * ysize);
}
}
fdfos.isize = new ISize(xsize, ysize, fdfos.isize.getZ());
fdfos.shortSpecData = resizeData;
}
} catch (Exception e) {
throw new Exception("Error scaling imported image:\n" + e.getMessage());
}
}
use of org.vcell.util.ISize in project vcell by virtualcell.
the class VFrapXmlHelper method SaveVFrapSpecialImagesAsFieldData.
//
// save the special images in the database as field data
//
public static ExternalDataIdentifier SaveVFrapSpecialImagesAsFieldData(Hashtable<String, Object> hashTable, DocumentManager documentManager) throws DataAccessException {
CartesianMesh mesh = (CartesianMesh) hashTable.get("mesh");
double[][][] pixData = (double[][][]) hashTable.get("pixData");
String[] channelNames = (String[]) hashTable.get("channelNames");
VariableType[] channelTypes = (VariableType[]) hashTable.get("channelTypes");
// DataSymbolType[] channelVFrapImageType = (DataSymbolType[])hashTable.get("channelVFrapImageType");
String mixedFieldDataName = (String) hashTable.get("mixedFieldDataName");
FieldDataFileOperationSpec vfrapMiscFieldDataOpSpec = new FieldDataFileOperationSpec();
vfrapMiscFieldDataOpSpec.opType = FieldDataFileOperationSpec.FDOS_ADD;
vfrapMiscFieldDataOpSpec.cartesianMesh = mesh;
vfrapMiscFieldDataOpSpec.doubleSpecData = pixData;
vfrapMiscFieldDataOpSpec.specEDI = null;
// item name as it comes from vFrap
vfrapMiscFieldDataOpSpec.varNames = channelNames;
vfrapMiscFieldDataOpSpec.owner = documentManager.getUser();
vfrapMiscFieldDataOpSpec.times = new double[] { 0.0 };
vfrapMiscFieldDataOpSpec.variableTypes = channelTypes;
vfrapMiscFieldDataOpSpec.origin = new Origin(0, 0, 0);
vfrapMiscFieldDataOpSpec.extent = mesh.getExtent();
vfrapMiscFieldDataOpSpec.isize = new ISize(mesh.getSizeX(), mesh.getSizeY(), mesh.getSizeZ());
ExternalDataIdentifier vfrapMisc = documentManager.saveFieldData(vfrapMiscFieldDataOpSpec, mixedFieldDataName);
return vfrapMisc;
}
Aggregations