use of net.imglib2.FinalInterval in project vcell by virtualcell.
the class VCellResultService method importCsv.
public Dataset importCsv(File directory) throws FileNotFoundException {
File[] files = directory.listFiles();
// TODO: Better handling
if (files == null)
return null;
ArrayList<ArrayList<Float>> timeSeries = new ArrayList<>(files.length);
Scanner scanner;
int dataSize = 0;
for (File file : files) {
scanner = new Scanner(file);
scanner.useDelimiter("[,\n]");
while (scanner.hasNext() && !scanner.hasNextDouble()) {
scanner.next();
}
if (!scanner.hasNextDouble()) {
scanner.close();
return null;
}
ArrayList<Float> data = new ArrayList<>();
while (scanner.hasNextDouble()) {
data.add(scanner.nextFloat());
}
scanner.close();
timeSeries.add(data);
dataSize = data.size();
}
int[] dimensions = { dataSize, timeSeries.size() };
Img<FloatType> img = new ArrayImgFactory<FloatType>().create(dimensions, new FloatType());
Cursor<FloatType> cursor = img.localizingCursor();
while (cursor.hasNext()) {
cursor.next();
int xPos = cursor.getIntPosition(0);
int tPos = cursor.getIntPosition(1);
Float val = timeSeries.get(tPos).get(xPos);
cursor.get().set(val);
}
Dataset dataset = datasetService.create(img);
// Drop single dimensions
@SuppressWarnings("unchecked") ImgPlus<FloatType> imgPlus = (ImgPlus<FloatType>) dataset.getImgPlus();
FinalInterval interval = Intervals.createMinMax(0, 0, imgPlus.dimension(0) - 1, imgPlus.dimension(1) - 1);
ImgPlus<FloatType> cropped = ops.transform().crop(imgPlus, interval, true);
dataset.setImgPlus(cropped);
System.out.println(dataset.numDimensions());
dataset.setName(directory.getName());
return dataset;
}
use of net.imglib2.FinalInterval in project vcell by virtualcell.
the class DeconstructGeometryCommand method run.
@Override
public void run() {
// Crop to get a z-stack over time (remove channel dimension)
long maxX = fluorData.max(fluorData.dimensionIndex(Axes.X));
long maxY = fluorData.max(fluorData.dimensionIndex(Axes.Y));
long maxZ = fluorData.max(fluorData.dimensionIndex(Axes.Z));
long maxTime = fluorData.max(fluorData.dimensionIndex(Axes.TIME));
Img fluorImg = fluorData.getImgPlus().getImg();
FinalInterval intervals = Intervals.createMinMax(0, 0, 0, 0, 0, maxX, maxY, maxZ, 0, maxTime);
RandomAccessibleInterval fluorImgCropped = ops.transform().crop(fluorImg, intervals, true);
// Calculate scale factors
double[] scaleFactors = { 1, 1, 1, 1 };
for (int i = 0; i < geomData.numDimensions(); i++) {
scaleFactors[i] = geomData.dimension(i) / (double) fluorImgCropped.dimension(i);
}
// Scale the fluorescence dataset to match the geometry
NLinearInterpolatorFactory interpolatorFactory = new NLinearInterpolatorFactory();
RandomAccessibleInterval fluorScaled = ops.transform().scale(fluorImgCropped, scaleFactors, interpolatorFactory);
// Crop out the first slice of each z-stack in time series
intervals = Intervals.createMinMax(0, 0, 0, 0, fluorScaled.dimension(0) - 1, fluorScaled.dimension(1) - 1, 0, fluorScaled.dimension(3) - 1);
IntervalView fluorXYT = (IntervalView) ops.transform().crop(fluorScaled, intervals, true);
// Create a blank image of the same X-Y-Time dimensions
long[] dimensions = { fluorXYT.dimension(0), fluorXYT.dimension(1), fluorXYT.dimension(2) };
Img<DoubleType> result = ops.create().img(dimensions);
// Calculate constant d in TIRF exponential decay function
theta = theta * 2 * Math.PI / 360;
double n1 = 1.52;
double n2 = 1.38;
double d = lambda * Math.pow((Math.pow(n1, 2) * Math.pow(Math.sin(theta), 2) - Math.pow(n2, 2)), -0.5) / (4 * Math.PI);
// Iterate through each time point, using 3D geometry to generate 2D intensities
Cursor<DoubleType> cursor = fluorXYT.localizingCursor();
RandomAccess fluorRA = fluorScaled.randomAccess();
RandomAccess<RealType<?>> geomRA = geomData.randomAccess();
RandomAccess<DoubleType> resultRA = result.randomAccess();
maxZ = geomData.dimension(2) - 1;
while (cursor.hasNext()) {
cursor.fwd();
int[] positionXYZ = { cursor.getIntPosition(0), cursor.getIntPosition(1), (int) maxZ - 1 };
int[] positionXYZT = { cursor.getIntPosition(0), cursor.getIntPosition(1), (int) maxZ - 1, cursor.getIntPosition(2) };
resultRA.setPosition(cursor);
geomRA.setPosition(positionXYZ);
double sum = 0.0;
while (positionXYZ[2] >= 0 && geomRA.get().getRealDouble() != 0.0) {
fluorRA.setPosition(positionXYZT);
geomRA.setPosition(positionXYZ);
sum += geomRA.get().getRealDouble() * Math.exp(-zSpacing * positionXYZ[2] / d);
positionXYZ[2]--;
}
resultRA.get().set(sum);
}
System.out.println("done");
displayService.createDisplay(result);
}
use of net.imglib2.FinalInterval in project vcell by virtualcell.
the class SmallCR method calcMSE.
// public static IJSolverStatus runFrapSolver(VCellHelper vh,double diffusionRate,String cacheKey,VCellHelper.IJGeom overrideGeom) throws Exception{
// //Override Model/Simulation parameter values (user must have knowledge of chosen model to know what parameter names to override)
// HashMap<String,String> simulationParameterOverrides = new HashMap<>();
// simulationParameterOverrides.put("rf_diffusionRate", ""+diffusionRate);
// HashMap<String, String> speciesContextInitialConditionsOverrides = new HashMap<>();
// String laserArea = "((x >= "+43+") && (x <= "+47+") && (y >= "+22+") && (y <= "+26+"))";
// speciesContextInitialConditionsOverrides.put("Laser", laserArea);
// double newEndTime = 10.0;
// //Start Frap simulation
// IJSolverStatus ijSolverStatus = vh.startVCellSolver(Long.parseLong(cacheKey), overrideGeom, simulationParameterOverrides, speciesContextInitialConditionsOverrides,newEndTime);
// return ijSolverStatus;
// }
// public static String waitForSolverGetCacheForData(VCellHelper vh,IJSolverStatus ijSolverStatus) throws Exception{
// //Wait for solver to finish
// System.out.println(ijSolverStatus.toString());
// String simulationJobId = ijSolverStatus.simJobId;
// while(true) {
// Thread.sleep(5000);
// ijSolverStatus = vh.getSolverStatus(simulationJobId);
// System.out.println(ijSolverStatus.toString());
// String statusName = ijSolverStatus.statusName.toLowerCase();
// if(statusName.equals("finished") || statusName.equals("stopped") || statusName.equals("aborted")) {
// break;
// }
// }
// return vh.getSimulationDataCacheKey(ijSolverStatus.simJobId);
// }
// public static SCIFIOImgPlus<DoubleType> zProjectNormalizeSimData(VCellHelper vh,
// String newImgPlusName,String simulationDataCachekey,String varToAnalyze,int preBleachTimeIndex,int solverStatus_jobIndex,int ANALYZE_BEGIN_TIMEINDEX,int ANALYZE_END_TIMEINDEX) throws Exception{
//
// int ANALYZE_COUNT = ANALYZE_END_TIMEINDEX - ANALYZE_BEGIN_TIMEINDEX+1;
// // Get the SIMULATION pre-bleach timepoint data for normalizing
// VCellHelper.TimePointData timePointData = vh.getTimePointData(simulationDataCachekey, varToAnalyze, new int[] {preBleachTimeIndex}, solverStatus_jobIndex);
// int xysize = timePointData.getBasicStackDimensions().xsize*timePointData.getBasicStackDimensions().ysize;
// double[] bleachedTimeStack = new double[ANALYZE_COUNT*xysize];
// // checkSizes(timePointData.getBasicStackDimensions(), xsize, xysize, zsize);
// // URL dataUrl = new URL("http://localhost:"+vh.findVCellApiServerPort()+"/"+"getdata"+"?"+"cachekey"+"="+cachekey+"&"+"varname"+"="+varToAnalyze+"&"+"timeindex"+"="+(int)(0)+"&"+"jobid="+ijSolverStatus.getJobIndex());
// double[] zProjectedSimNormalizer = getNormalizedZProjected(timePointData,null);
// //showAndZoom(ij, "Sim Data PreBleach", ArrayImgs.doubles(simNormalizer, xsize,ysize), 4);
//
// // Get the SIMULATION post-bleach data to analyze
// for(int timeIndex = ANALYZE_BEGIN_TIMEINDEX;timeIndex<=ANALYZE_END_TIMEINDEX;timeIndex++){
// timePointData = vh.getTimePointData(simulationDataCachekey, varToAnalyze, new int[] {timeIndex}, solverStatus_jobIndex);
// // checkSizes(timePointData.getBasicStackDimensions(), xsize, xysize, zsize);
// // dataUrl = new URL("http://localhost:"+vh.findVCellApiServerPort()+"/"+"getdata"+"?"+"cachekey"+"="+cachekey+"&"+"varname"+"="+varToAnalyze+"&"+"timeindex"+"="+(int)timeIndex+"&"+"jobid="+ijSolverStatus.getJobIndex());
// double[] data = getNormalizedZProjected(timePointData,zProjectedSimNormalizer);
// System.arraycopy(data, 0, bleachedTimeStack, (timeIndex-ANALYZE_BEGIN_TIMEINDEX)*xysize, data.length);
// }
//
// //Turn VCell data into iterableinterval
// // FinalInterval zProjectedSimDataSize = FinalInterval.createMinSize(new long[] {0,0,0, xsize,ysize,ANALYZE_COUNT});//xyzt:origin and xyzt:size
// ArrayImg<DoubleType, DoubleArray> simImgs = ArrayImgs.doubles(bleachedTimeStack, new long[] {timePointData.getBasicStackDimensions().xsize,timePointData.getBasicStackDimensions().ysize,ANALYZE_COUNT});
// SCIFIOImgPlus<DoubleType> annotatedZProjectedSimPostBleachData = new SCIFIOImgPlus<>(simImgs,newImgPlusName /*"Sim Data "+diffusionRate*/,new AxisType[] {Axes.X,Axes.Y,Axes.TIME});
// // RandomAccessibleInterval<DoubleType> simExtracted = ij.op().transform().crop(annotatedSimData, simExtractInterval);
// //showAndZoom(ij, "Sim Data "+diffusionRate, annotatedZProjectedSimPostBleachData, 4);
// return annotatedZProjectedSimPostBleachData;
// }
// public static double[] getNormalizedZProjected(VCellHelper.TimePointData timePointData,double[] normalizer) throws Exception{
// BasicStackDimensions basicStackDimensions = timePointData.getBasicStackDimensions();//VCellHelper.getDimensions(nodes.item(0));
// //Sum pixel values in Z direction to match experimental data (open pinhole confocal, essentially brightfield)
// int xysize = basicStackDimensions.xsize*basicStackDimensions.ysize;
// double[] normalizedData = new double[xysize];
// for (int i = 0; i < timePointData.getTimePointData().length; i++) {
// normalizedData[(i%xysize)]+= timePointData.getTimePointData()[i];
// }
// if(normalizer != null) {
// for (int i = 0; i < normalizedData.length; i++) {
// if(normalizedData[i] != 0) {
// normalizedData[i] = (normalizedData[i]+Double.MIN_VALUE)/(normalizer[i]+Double.MIN_VALUE);
// }
// }
// }
// return normalizedData;
// }
// public static void checkSizes(BasicStackDimensions basicStackDimensions,int xsize,int ysize,int zsize) throws Exception{
// if(basicStackDimensions.xsize != xsize || basicStackDimensions.ysize != ysize || basicStackDimensions.zsize != zsize) {
// throw new Exception("One or more sim data xyz dimensions="+basicStackDimensions.xsize+","+basicStackDimensions.ysize+","+basicStackDimensions.zsize+" does not match expected xyz sizes="+xsize+","+ysize+","+zsize);
// }
// }
public static double calcMSE(ImageJ ij, SCIFIOImgPlus<DoubleType> annotatedZProjectedSimPostBleachData, ExampleDatasets exampleDatasets, FinalInterval analyzeOrigInterval) throws Exception {
// Calculate mean-squared-error as example, normalize experimental data by dividing by a prebleach image
RandomAccessibleInterval<? extends RealType<?>> zProjectedExperimentalPostBleach = ij.op().transform().crop(exampleDatasets.experimentalData, analyzeOrigInterval);
Cursor<DoubleType> zProjectedSimPostBleachDataCursor = IterableRandomAccessibleInterval.create(annotatedZProjectedSimPostBleachData).localizingCursor();
Cursor<? extends RealType<?>> zProjectedExpPostBleachDataCursor = IterableRandomAccessibleInterval.create(zProjectedExperimentalPostBleach).localizingCursor();
IterableRandomAccessibleInterval<? extends RealType<?>> zProjectedPreBleachInterval = IterableRandomAccessibleInterval.create(exampleDatasets.preBleachImage);
BigDecimal sumSquaredDiff = new BigDecimal(0);
int[] analysisPosition = new int[exampleDatasets.analysisROI.numDimensions()];
int[] preBleachPosition = new int[zProjectedPreBleachInterval.numDimensions()];
int[] experimentalPosition = new int[zProjectedExperimentalPostBleach.numDimensions()];
int[] simulationPosition = new int[annotatedZProjectedSimPostBleachData.numDimensions()];
int numValsInMask = 0;
while (zProjectedSimPostBleachDataCursor.hasNext()) {
Cursor<UnsignedByteType> analysisCursor = exampleDatasets.analysisROI.localizingCursor();
Cursor<? extends RealType<?>> preBleachNormalizingCursor = zProjectedPreBleachInterval.localizingCursor();
while (analysisCursor.hasNext()) {
boolean maskBit = !(analysisCursor.next().get() == 0);
DoubleType simPostBleachVal = zProjectedSimPostBleachDataCursor.next();
RealType<?> expPostBleachVal = zProjectedExpPostBleachDataCursor.next();
RealType<?> preBleachNormalizingVal = preBleachNormalizingCursor.next();
if (!maskBit) {
// skip areas where analysis mask is 0
continue;
}
// Get the position of all the cursors and check they are in sync
analysisCursor.localize(analysisPosition);
preBleachNormalizingCursor.localize(preBleachPosition);
zProjectedExpPostBleachDataCursor.localize(experimentalPosition);
zProjectedSimPostBleachDataCursor.localize(simulationPosition);
// System.out.println("analysis="+Arrays.toString(analysisPosition)+" prebleach="+Arrays.toString(preBleachPosition)+" exp="+Arrays.toString(experimentalPosition)+" sim="+Arrays.toString(simulationPosition));
if (!Arrays.equals(analysisPosition, preBleachPosition) || !Arrays.equals(experimentalPosition, simulationPosition)) {
throw new Exception("Cursor positions not equal");
}
if (analysisPosition[0] != experimentalPosition[0] || analysisPosition[1] != experimentalPosition[1]) {
// check xy are same
throw new Exception("XY Cursor position not equal for analysisROI mask and experimental data");
}
double normalizedExpDataVal = 0;
if (expPostBleachVal.getRealDouble() != 0) {
normalizedExpDataVal = (expPostBleachVal.getRealDouble()) / (preBleachNormalizingVal.getRealDouble() + Double.MIN_VALUE);
}
double diff = simPostBleachVal.get() - (normalizedExpDataVal);
sumSquaredDiff = sumSquaredDiff.add(new BigDecimal(Math.pow(diff, 2.0)));
numValsInMask++;
}
}
return sumSquaredDiff.divide(new BigDecimal(numValsInMask), 8, RoundingMode.HALF_UP).doubleValue();
}
use of net.imglib2.FinalInterval in project vcell by virtualcell.
the class PlotROIStats method crop.
private RandomAccessibleInterval<T> crop(RandomAccessibleInterval<T> data, Overlay overlay) {
int numDimensions = data.numDimensions();
long[] minDimensions = new long[numDimensions];
long[] maxDimensions = new long[numDimensions];
if (numDimensions > 0) {
minDimensions[0] = (long) overlay.realMin(0);
maxDimensions[0] = (long) overlay.realMax(0);
}
if (numDimensions > 1) {
minDimensions[1] = (long) overlay.realMin(0);
maxDimensions[1] = (long) overlay.realMax(0);
}
for (int i = 2; i < numDimensions; i++) {
minDimensions[i] = 0;
maxDimensions[i] = data.dimension(i) - 1;
}
FinalInterval interval = new FinalInterval(minDimensions, maxDimensions);
RandomAccessibleInterval<T> cropped = ops.transform().crop(data, interval);
return cropped;
}
use of net.imglib2.FinalInterval in project vcell by virtualcell.
the class ProjectService method load.
public Task<Project, String> load(File root) {
final Task<Project, String> task = new Task<Project, String>() {
@Override
protected Project doInBackground() throws Exception {
Project project = new Project(root.getName());
String rootPath = root.getAbsolutePath();
File[] dataFiles = Paths.get(rootPath, "data").toFile().listFiles();
File[] geometryFiles = Paths.get(rootPath, "geometry").toFile().listFiles();
File[] modelDirectories = Paths.get(rootPath, "models").toFile().listFiles();
File[] resultsFiles = Paths.get(rootPath, "results").toFile().listFiles();
int numFiles = dataFiles.length + geometryFiles.length + modelDirectories.length + resultsFiles.length;
int numLoaded = 0;
if (dataFiles != null) {
for (File dataFile : dataFiles) {
try {
setSubtask(dataFile.getName());
Dataset data = datasetIOService.open(dataFile.getAbsolutePath());
project.getData().add(data);
numLoaded++;
setProgress(numLoaded * 100 / numFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (geometryFiles != null) {
for (File geometryFile : geometryFiles) {
try {
setSubtask(geometryFile.getName());
Dataset geometry = datasetIOService.open(geometryFile.getAbsolutePath());
// Geometry datasets are saved as 8-bit images so we must convert back to 1-bit
if (geometry.firstElement() instanceof UnsignedByteType) {
@SuppressWarnings("unchecked") Img<UnsignedByteType> img = (Img<UnsignedByteType>) geometry.getImgPlus().getImg();
Img<BitType> converted = opService.convert().bit(img);
ImgPlus<BitType> convertedImgPlus = new ImgPlus<>(converted, geometry.getName());
geometry.setImgPlus(convertedImgPlus);
}
project.getGeometry().add(geometry);
numLoaded++;
setProgress(numLoaded * 100 / numFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (modelDirectories != null) {
for (File modelDirectory : modelDirectories) {
setSubtask(modelDirectory.getName());
SBMLDocument sbmlDocument = null;
BufferedImage image = null;
File[] modelFiles = modelDirectory.listFiles();
System.out.println(modelFiles.length);
// Invalid model directory
if (modelFiles.length > 2)
continue;
for (File modelFile : modelFiles) {
System.out.println(modelFile.getName());
if (FilenameUtils.getExtension(modelFile.getName()).equals("xml")) {
sbmlDocument = new SBMLReader().readSBML(modelFile);
System.out.println("Loaded sbml");
} else if (FilenameUtils.getExtension(modelFile.getName()).equals("png")) {
image = ImageIO.read(modelFile);
System.out.println("Loaded image");
}
}
if (sbmlDocument != null) {
VCellModel vCellModel = new VCellModel(modelDirectory.getName(), null, sbmlDocument);
vCellModel.setImage(image);
project.getModels().add(vCellModel);
System.out.println("Added model");
}
numLoaded++;
setProgress(numLoaded * 100 / numFiles);
}
}
if (resultsFiles != null) {
for (File resultsFile : resultsFiles) {
try {
setSubtask(resultsFile.getName());
Dataset results = datasetIOService.open(resultsFile.getAbsolutePath());
// Loading 1-dimensional tif images adds a dimension
// so must crop out empty dimensions
@SuppressWarnings("unchecked") ImgPlus<T> imgPlus = (ImgPlus<T>) results.getImgPlus();
int numDimensions = imgPlus.numDimensions();
long[] dimensions = new long[2 * imgPlus.numDimensions()];
for (int i = 0; i < numDimensions; i++) {
dimensions[i] = 0;
dimensions[i + numDimensions] = imgPlus.dimension(i) - 1;
}
FinalInterval interval = Intervals.createMinMax(dimensions);
ImgPlus<T> cropped = opService.transform().crop(imgPlus, interval, true);
results.setImgPlus(cropped);
project.getResults().add(results);
numLoaded++;
setProgress(numLoaded * 100 / numFiles);
} catch (IOException e) {
e.printStackTrace();
}
}
}
currentProjectRoot = root;
return project;
}
};
return task;
}
Aggregations