Search in sources :

Example 1 with DoubleArray

use of net.imglib2.img.basictypeaccess.array.DoubleArray in project vcell by virtualcell.

the class VCellPlugin method run.

// private Hashtable<String,Thread> threadHash = new Hashtable<String,Thread>();
// private void startJProgressThread0(String lastName,String newName) {
// if(lastName != null && threadHash.get(lastName) != null) {
// threadHash.get(lastName).interrupt();
// while(threadHash.get(lastName) != null) {
// try {
// Thread.sleep(50);
// } catch (InterruptedException e) {
// e.printStackTrace();
// break;
// }
// }
// }
// if(newName == null) {
// return;
// }
// final Thread progressThread = new Thread(new Runnable(){
// @Override
// public void run() {
// final int[] progress = new int[] {1};
// while(progressDialog.isVisible()) {
// if(Thread.currentThread().isInterrupted()) {
// break;
// }
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// jProgressBar.setValue(progress[0]);
// }});
// progress[0]++;
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// break;
// }
// }
// threadHash.remove(Thread.currentThread().getName());
// }});
// threadHash.put(newName, progressThread);
// progressThread.setName(newName);
// progressThread.setDaemon(true);//So not block JVM exit
// progressThread.start();
// }
// public void showAndZoom(String displayName,Object thingToDisplay,double zoomFactor) throws Exception{
// final ImageDisplayService ids = getContext().getService(ImageDisplayService.class);
// final DisplayService ds = getContext().getService(DisplayService.class);
// new Thread(new Runnable() {
// 
// @Override
// public void run() {
// // TODO Auto-generated method stub
// uiService.show(displayName,thingToDisplay);
// //Find display and set zoom, resize window
// List<ImageDisplay> knownImageDisplays = ids.getImageDisplays();
// boolean bvisible = false;
// while (!bvisible) {
// for (ImageDisplay imageDisplay : knownImageDisplays) {
// if (imageDisplay.getName().equals(displayName)) {
// if (imageDisplay.isVisible(imageDisplay.getActiveView())) {
// bvisible = true;
// break;
// }
// }
// }
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// //		    	int vw = ij.imageDisplay().getActiveImageDisplay().getCanvas().getViewportWidth();
// //		    	int vh = ij.imageDisplay().getActiveImageDisplay().getCanvas().getViewportHeight();
// //		    	System.out.println(" -----byname="+ij.display().getDisplay(displayName));
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// try {
// ids.getActiveImageDisplay().getCanvas().setZoom(zoomFactor);
// if(ds.getDisplay(displayName) != null && uiService.getDisplayViewer(ds.getDisplay(displayName)) instanceof JFrame) {
// double vw = ids.getActiveImageDisplay().dimension(ids.getActiveImageDisplay().dimensionIndex(Axes.X))*zoomFactor;
// double vh = ids.getActiveImageDisplay().dimension(ids.getActiveImageDisplay().dimensionIndex(Axes.Y))*zoomFactor;
// ((JFrame)uiService.getDisplayViewer(ds.getDisplay(displayName)).getWindow()).setSize(new Dimension((int)vw+50, (int)vh+150));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// 
// //		    	ij.ui().getDisplayViewer(ij.display().getDisplay(displayName)).getPanel().redoLayout();
// //		    	List<Display<?>> displays = ij.display().getDisplays();
// //		    	for (Display<?> display : displays) {
// //					System.out.println(display+" -----byname="+ij.display().getDisplay(displayName));
// //				}
// 
// }
// }).start();
// 
// }
@Override
public void run() {
    try {
        if (vcellSelection != null && vcellSelection.exception != null) {
            if (!vcellSelection.exception.getMessage().equals(MyPreProcessor.CANCELLED)) {
                uiService.showDialog("Model search failed\n" + vcellSelection.exception.getClass().getName() + "\n" + vcellSelection.exception.getMessage(), MessageType.ERROR_MESSAGE);
            }
            return;
        }
        if (vcellSelection == null || vcellSelection.theCacheKey == null) {
            return;
        }
        // Create ImageJ datasets and display separate hyperstack for each variable
        for (int varIndex = 0; varIndex < vcellSelection.varName.length; varIndex++) {
            int[] time = vcellSelection.timePointIndexes;
            displayProgressBar(true, "loading Image...", "VCell Model Loader", (varIndex + 1) * 100 / vcellSelection.varName.length, uiService);
            final IJDataList tpd = vcellHelper.getTimePointData(vcellSelection.theCacheKey, vcellSelection.varName[varIndex], VCellHelper.VARTYPE_POSTPROC.NotPostProcess, time, 0);
            BasicStackDimensions bsd = tpd.ijData[0].stackInfo;
            double[] data = new double[bsd.getTotalSize() * tpd.ijData.length];
            double min = Double.MAX_VALUE;
            double max = Double.MIN_VALUE;
            ArrayImg<DoubleType, DoubleArray> testimg = ArrayImgs.doubles(data, bsd.xsize, bsd.ysize, bsd.zsize, tpd.ijData.length);
            for (int i = 0; i < tpd.ijData.length; i++) {
                System.arraycopy(tpd.ijData[i].getDoubleData(), 0, data, i * bsd.getTotalSize(), bsd.getTotalSize());
                // calc minmax only for pixel values that are in domain of this variable
                for (int j = 0; j < tpd.ijData[i].getDoubleData().length; j++) {
                    if (tpd.ijData[i].getDoubleData()[j] != tpd.ijData[i].notInDomainValue) {
                        min = Math.min(min, tpd.ijData[i].getDoubleData()[j]);
                        max = Math.max(max, tpd.ijData[i].getDoubleData()[j]);
                    }
                }
            }
            ImgPlus<DoubleType> imgPlus = new ImgPlus<DoubleType>(testimg);
            imgPlus.setChannelMinimum(0, min);
            imgPlus.setChannelMaximum(0, max);
            imgPlus.setAxis(new DefaultLinearAxis(Axes.Z), 2);
            imgPlus.setAxis(new DefaultLinearAxis(Axes.TIME), 3);
            uiService.show(vcellSelection.varName[varIndex], imgPlus);
            DefaultImageDisplay createDisplayQuietly = (DefaultImageDisplay) displayService.getDisplay(vcellSelection.varName[varIndex]);
            while (displayService.getActiveDisplay() == null) {
                Thread.sleep(100);
            }
            WindowManager.getActiveWindow().setSize(400, 400);
            IJ.run("Scale to Fit", "");
            // refresh the sliders
            WindowManager.getActiveWindow().setSize(400, 400);
            // final ZoomService zoomService = getContext().getService(ZoomService.class);
            // zoomService.zoomSet(createDisplayQuietly, 300, 0, 0);
            // eventService.publish(new PanZoomEvent(createDisplayQuietly.getCanvas()));
            // IJ.run("Set... ", "zoom=300 x="+(bsd.xsize/2)+" y="+(bsd.ysize/2));
            // IJ.run("Set... ", "zoom=300");
            // IJ.run("In");
            // IJ.run("In");
            // IJ.run("In");
            // RunService runService = getContext().getService(RunService.class);
            // runService.run("In", (Map)null);
            // final Iterator<PluginInfo<Op>> iterator = opService.getPlugins().iterator();
            // while(iterator.hasNext()) {
            // System.out.println(iterator.next());
            // }
            // opService.run("In", "");
            // final ZoomService zoomService = getContext().getService(ZoomService.class);
            // zoomService.zoomSet(createDisplayQuietly, 300, 0, 0);
            // createDisplayQuietly.update();
            // final Display<?> createDisplayQuietly = getContext().getService(DisplayService.class).createDisplayQuietly(testimg);
            final DefaultDatasetView defaultDatasetView = (DefaultDatasetView) ((DefaultImageDisplay) createDisplayQuietly).getActiveView();
            // defaultDatasetView.getData().setAxis(createDisplayQuietly.axis(2), 2);
            // defaultDatasetView.getData().setAxis(createDisplayQuietly.axis(3), 3);
            // defaultDatasetView.update();
            System.out.println(min + " " + max);
        // displayService.setActiveDisplay(createDisplayQuietly);
        // IJ.setMinAndMax(min, max);
        // defaultDatasetView.getData().setChannelMinimum(0, min);
        // defaultDatasetView.getData().setChannelMaximum(0, max);
        // defaultDatasetView.setChannelRanges(min,max);
        // IJ.getImage().updateAndDraw();
        // while(displayService.getActiveDisplay() == null) {
        // Thread.sleep(100);
        // }
        // IJ.setMinAndMax(min, max);
        // WindowManager.getCurrentImage().setDisplayRange(min, max)
        // WindowManager.getCurrentImage().setDisplayRange(min,max);
        // ImageStack.create(varIndex, varIndex, varIndex, varIndex)
        // ImagePlus ip = new ImagePlus();
        // uiService.showUI();
        // EventService es = null;
        // getContext().getService(EventService.class).publish(new DisplayUpdatedEvent(createDisplayQuietly,DisplayUpdatedEvent.DisplayUpdateLevel.UPDATE));
        // uiService.get
        // uiService.show(createDisplayQuietly);
        // getContext().getService(DisplayService.class).
        // showAndZoom(vcellSelection.varName[varIndex],createDisplayQuietly, 3);
        }
    } catch (Exception e) {
        displayProgressBar(false, "Error", "VCell Model Loader", 100, uiService);
        uiService.showDialog("theCacheKey,var,VCellHelper.VARTYPE_POSTPROC.NotPostProcess,time,0\n" + e.getMessage(), "getTimePoint(...) failed", MessageType.ERROR_MESSAGE);
    } finally {
        displayProgressBar(false, "displaying Image...", "VCell Model Loader", 100, uiService);
    }
}
Also used : ImgPlus(net.imagej.ImgPlus) DefaultLinearAxis(net.imagej.axis.DefaultLinearAxis) DoubleType(net.imglib2.type.numeric.real.DoubleType) IJDataList(org.vcell.imagej.helper.VCellHelper.IJDataList) BasicStackDimensions(org.vcell.imagej.helper.VCellHelper.BasicStackDimensions) DefaultImageDisplay(net.imagej.display.DefaultImageDisplay) DoubleArray(net.imglib2.img.basictypeaccess.array.DoubleArray) DefaultDatasetView(net.imagej.display.DefaultDatasetView)

Example 2 with DoubleArray

use of net.imglib2.img.basictypeaccess.array.DoubleArray in project vcell by virtualcell.

the class VCellPlugin_Minimal method run.

// private Hashtable<String,Thread> threadHash = new Hashtable<String,Thread>();
// private void startJProgressThread0(String lastName,String newName) {
// if(lastName != null && threadHash.get(lastName) != null) {
// threadHash.get(lastName).interrupt();
// while(threadHash.get(lastName) != null) {
// try {
// Thread.sleep(50);
// } catch (InterruptedException e) {
// e.printStackTrace();
// break;
// }
// }
// }
// if(newName == null) {
// return;
// }
// final Thread progressThread = new Thread(new Runnable(){
// @Override
// public void run() {
// final int[] progress = new int[] {1};
// while(progressDialog.isVisible()) {
// if(Thread.currentThread().isInterrupted()) {
// break;
// }
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// jProgressBar.setValue(progress[0]);
// }});
// progress[0]++;
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// break;
// }
// }
// threadHash.remove(Thread.currentThread().getName());
// }});
// threadHash.put(newName, progressThread);
// progressThread.setName(newName);
// progressThread.setDaemon(true);//So not block JVM exit
// progressThread.start();
// }
// public void showAndZoom(String displayName,Object thingToDisplay,double zoomFactor) throws Exception{
// final ImageDisplayService ids = getContext().getService(ImageDisplayService.class);
// final DisplayService ds = getContext().getService(DisplayService.class);
// new Thread(new Runnable() {
// 
// @Override
// public void run() {
// // TODO Auto-generated method stub
// uiService.show(displayName,thingToDisplay);
// //Find display and set zoom, resize window
// List<ImageDisplay> knownImageDisplays = ids.getImageDisplays();
// boolean bvisible = false;
// while (!bvisible) {
// for (ImageDisplay imageDisplay : knownImageDisplays) {
// if (imageDisplay.getName().equals(displayName)) {
// if (imageDisplay.isVisible(imageDisplay.getActiveView())) {
// bvisible = true;
// break;
// }
// }
// }
// try {
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// //		    	int vw = ij.imageDisplay().getActiveImageDisplay().getCanvas().getViewportWidth();
// //		    	int vh = ij.imageDisplay().getActiveImageDisplay().getCanvas().getViewportHeight();
// //		    	System.out.println(" -----byname="+ij.display().getDisplay(displayName));
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// try {
// ids.getActiveImageDisplay().getCanvas().setZoom(zoomFactor);
// if(ds.getDisplay(displayName) != null && uiService.getDisplayViewer(ds.getDisplay(displayName)) instanceof JFrame) {
// double vw = ids.getActiveImageDisplay().dimension(ids.getActiveImageDisplay().dimensionIndex(Axes.X))*zoomFactor;
// double vh = ids.getActiveImageDisplay().dimension(ids.getActiveImageDisplay().dimensionIndex(Axes.Y))*zoomFactor;
// ((JFrame)uiService.getDisplayViewer(ds.getDisplay(displayName)).getWindow()).setSize(new Dimension((int)vw+50, (int)vh+150));
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
// });
// 
// //		    	ij.ui().getDisplayViewer(ij.display().getDisplay(displayName)).getPanel().redoLayout();
// //		    	List<Display<?>> displays = ij.display().getDisplays();
// //		    	for (Display<?> display : displays) {
// //					System.out.println(display+" -----byname="+ij.display().getDisplay(displayName));
// //				}
// 
// }
// }).start();
// 
// }
@Override
public void run() {
    try {
        if (vcellSelection != null && vcellSelection.exception != null) {
            if (!vcellSelection.exception.getMessage().equals(MyPreProcessor.CANCELLED)) {
                uiService.showDialog("Model search failed\n" + vcellSelection.exception.getClass().getName() + "\n" + vcellSelection.exception.getMessage(), MessageType.ERROR_MESSAGE);
            }
            return;
        }
        if (vcellSelection == null || vcellSelection.theCacheKey == null) {
            return;
        }
        // Create ImageJ datasets and display separate hyperstack for each variable
        for (int varIndex = 0; varIndex < vcellSelection.varName.length; varIndex++) {
            int[] time = vcellSelection.timePointIndexes;
            displayProgressBar(true, "loading Image...", "VCell Model Loader", (varIndex + 1) * 100 / vcellSelection.varName.length, uiService);
            final IJDataList tpd = vcellHelper.getTimePointData(vcellSelection.theCacheKey, vcellSelection.varName[varIndex], VCellHelper.VARTYPE_POSTPROC.NotPostProcess, time, 0);
            BasicStackDimensions bsd = tpd.ijData[0].stackInfo;
            double[] data = new double[bsd.getTotalSize() * tpd.ijData.length];
            double min = Double.MAX_VALUE;
            double max = Double.MIN_VALUE;
            ArrayImg<DoubleType, DoubleArray> testimg = ArrayImgs.doubles(data, bsd.xsize, bsd.ysize, bsd.zsize, tpd.ijData.length);
            for (int i = 0; i < tpd.ijData.length; i++) {
                System.arraycopy(tpd.ijData[i].getDoubleData(), 0, data, i * bsd.getTotalSize(), bsd.getTotalSize());
                // calc minmax only for pixel values that are in domain of this variable
                for (int j = 0; j < tpd.ijData[i].getDoubleData().length; j++) {
                    if (tpd.ijData[i].getDoubleData()[j] != tpd.ijData[i].notInDomainValue) {
                        min = Math.min(min, tpd.ijData[i].getDoubleData()[j]);
                        max = Math.max(max, tpd.ijData[i].getDoubleData()[j]);
                    }
                }
            }
            ImgPlus<DoubleType> imgPlus = new ImgPlus<DoubleType>(testimg);
            imgPlus.setChannelMinimum(0, min);
            imgPlus.setChannelMaximum(0, max);
            imgPlus.setAxis(new DefaultLinearAxis(Axes.Z), 2);
            imgPlus.setAxis(new DefaultLinearAxis(Axes.TIME), 3);
            uiService.show(vcellSelection.varName[varIndex], imgPlus);
            DefaultImageDisplay createDisplayQuietly = (DefaultImageDisplay) displayService.getDisplay(vcellSelection.varName[varIndex]);
            while (displayService.getActiveDisplay() == null) {
                Thread.sleep(100);
            }
            WindowManager.getActiveWindow().setSize(400, 400);
            IJ.run("Scale to Fit", "");
            // refresh the sliders
            WindowManager.getActiveWindow().setSize(400, 400);
            // final ZoomService zoomService = getContext().getService(ZoomService.class);
            // zoomService.zoomSet(createDisplayQuietly, 300, 0, 0);
            // eventService.publish(new PanZoomEvent(createDisplayQuietly.getCanvas()));
            // IJ.run("Set... ", "zoom=300 x="+(bsd.xsize/2)+" y="+(bsd.ysize/2));
            // IJ.run("Set... ", "zoom=300");
            // IJ.run("In");
            // IJ.run("In");
            // IJ.run("In");
            // RunService runService = getContext().getService(RunService.class);
            // runService.run("In", (Map)null);
            // final Iterator<PluginInfo<Op>> iterator = opService.getPlugins().iterator();
            // while(iterator.hasNext()) {
            // System.out.println(iterator.next());
            // }
            // opService.run("In", "");
            // final ZoomService zoomService = getContext().getService(ZoomService.class);
            // zoomService.zoomSet(createDisplayQuietly, 300, 0, 0);
            // createDisplayQuietly.update();
            // final Display<?> createDisplayQuietly = getContext().getService(DisplayService.class).createDisplayQuietly(testimg);
            final DefaultDatasetView defaultDatasetView = (DefaultDatasetView) ((DefaultImageDisplay) createDisplayQuietly).getActiveView();
            // defaultDatasetView.getData().setAxis(createDisplayQuietly.axis(2), 2);
            // defaultDatasetView.getData().setAxis(createDisplayQuietly.axis(3), 3);
            // defaultDatasetView.update();
            System.out.println(min + " " + max);
        // displayService.setActiveDisplay(createDisplayQuietly);
        // IJ.setMinAndMax(min, max);
        // defaultDatasetView.getData().setChannelMinimum(0, min);
        // defaultDatasetView.getData().setChannelMaximum(0, max);
        // defaultDatasetView.setChannelRanges(min,max);
        // IJ.getImage().updateAndDraw();
        // while(displayService.getActiveDisplay() == null) {
        // Thread.sleep(100);
        // }
        // IJ.setMinAndMax(min, max);
        // WindowManager.getCurrentImage().setDisplayRange(min, max)
        // WindowManager.getCurrentImage().setDisplayRange(min,max);
        // ImageStack.create(varIndex, varIndex, varIndex, varIndex)
        // ImagePlus ip = new ImagePlus();
        // uiService.showUI();
        // EventService es = null;
        // getContext().getService(EventService.class).publish(new DisplayUpdatedEvent(createDisplayQuietly,DisplayUpdatedEvent.DisplayUpdateLevel.UPDATE));
        // uiService.get
        // uiService.show(createDisplayQuietly);
        // getContext().getService(DisplayService.class).
        // showAndZoom(vcellSelection.varName[varIndex],createDisplayQuietly, 3);
        }
    } catch (Exception e) {
        displayProgressBar(false, "Error", "VCell Model Loader", 100, uiService);
        uiService.showDialog("theCacheKey,var,VCellHelper.VARTYPE_POSTPROC.NotPostProcess,time,0\n" + e.getMessage(), "getTimePoint(...) failed", MessageType.ERROR_MESSAGE);
    } finally {
        displayProgressBar(false, "displaying Image...", "VCell Model Loader", 100, uiService);
    }
}
Also used : ImgPlus(net.imagej.ImgPlus) DefaultLinearAxis(net.imagej.axis.DefaultLinearAxis) DoubleType(net.imglib2.type.numeric.real.DoubleType) IJDataList(org.vcell.imagej.helper.VCellHelper.IJDataList) BasicStackDimensions(org.vcell.imagej.helper.VCellHelper.BasicStackDimensions) DefaultImageDisplay(net.imagej.display.DefaultImageDisplay) DoubleArray(net.imglib2.img.basictypeaccess.array.DoubleArray) DefaultDatasetView(net.imagej.display.DefaultDatasetView)

Example 3 with DoubleArray

use of net.imglib2.img.basictypeaccess.array.DoubleArray 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();
}
Also used : UnsignedByteType(net.imglib2.type.numeric.integer.UnsignedByteType) BigDecimal(java.math.BigDecimal) DoubleType(net.imglib2.type.numeric.real.DoubleType)

Example 4 with DoubleArray

use of net.imglib2.img.basictypeaccess.array.DoubleArray in project vcell by virtualcell.

the class ModelSearch method run.

// private Hashtable<String,Thread> threadHash = new Hashtable<String,Thread>();
// private void startJProgressThread0(String lastName,String newName) {
// if(lastName != null && threadHash.get(lastName) != null) {
// threadHash.get(lastName).interrupt();
// while(threadHash.get(lastName) != null) {
// try {
// Thread.sleep(50);
// } catch (InterruptedException e) {
// e.printStackTrace();
// break;
// }
// }
// }
// if(newName == null) {
// return;
// }
// final Thread progressThread = new Thread(new Runnable(){
// @Override
// public void run() {
// final int[] progress = new int[] {1};
// while(progressDialog.isVisible()) {
// if(Thread.currentThread().isInterrupted()) {
// break;
// }
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
// jProgressBar.setValue(progress[0]);
// }});
// progress[0]++;
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// break;
// }
// }
// threadHash.remove(Thread.currentThread().getName());
// }});
// threadHash.put(newName, progressThread);
// progressThread.setName(newName);
// progressThread.setDaemon(true);//So not block JVM exit
// progressThread.start();
// }
@Override
public void run() {
    try {
        if (vcellSelection != null && vcellSelection.exception != null) {
            if (!vcellSelection.exception.getMessage().equals(MyPreProcessor.CANCELLED)) {
                uiService.showDialog("Model search failed\n" + vcellSelection.exception.getClass().getName() + "\n" + vcellSelection.exception.getMessage(), MessageType.ERROR_MESSAGE);
            }
            return;
        }
        if (vcellSelection == null || vcellSelection.theCacheKey == null) {
            return;
        }
        String var = vcellSelection.varName;
        int[] time = new int[] { vcellSelection.timePointIndex };
        displayProgressBar(true, "loading Image...", "VCell Model Loader", 50, uiService);
        IJDataList tpd = vcellHelper.getTimePointData(vcellSelection.theCacheKey, var, VCellHelper.VARTYPE_POSTPROC.NotPostProcess, time, 0);
        displayProgressBar(true, "displaying Image...", "VCell Model Loader", 100, uiService);
        double[] data = tpd.ijData[0].getDoubleData();
        BasicStackDimensions bsd = tpd.ijData[0].stackInfo;
        System.out.println(bsd.xsize + " " + bsd.ysize);
        ArrayImg<DoubleType, DoubleArray> testimg = ArrayImgs.doubles(data, bsd.xsize, bsd.ysize, bsd.zsize);
        uiService.show(testimg);
    } catch (Exception e) {
        displayProgressBar(false, "displaying Image...", "VCell Model Loader", 100, uiService);
        uiService.showDialog("theCacheKey,var,VCellHelper.VARTYPE_POSTPROC.NotPostProcess,time,0\n" + e.getMessage(), "getTimePoint(...) failed", MessageType.ERROR_MESSAGE);
    } finally {
        displayProgressBar(false, "displaying Image...", "VCell Model Loader", 100, uiService);
    }
}
Also used : DoubleType(net.imglib2.type.numeric.real.DoubleType) IJDataList(org.vcell.imagej.helper.VCellHelper.IJDataList) BasicStackDimensions(org.vcell.imagej.helper.VCellHelper.BasicStackDimensions) DoubleArray(net.imglib2.img.basictypeaccess.array.DoubleArray)

Example 5 with DoubleArray

use of net.imglib2.img.basictypeaccess.array.DoubleArray in project vcell by virtualcell.

the class ModelLoad method run.

@Override
public void run() {
    displayProgressBar(true, "Checking listening ports...", "Checking for VCell Client");
    startJProgressThread0(null, "Check");
    try {
        // Find the port that a separately running VCell client is listening on
        // 
        System.out.println("vcell service port=" + vcellHelper.findVCellApiServerPort());
        // uiService.getDisplayViewer(textDisplay).dispose();
        displayProgressBar(false, null, null);
    } catch (Exception e) {
        // e.printStackTrace();
        displayProgressBar(false, null, null);
        // uiService.getDisplayViewer(textDisplay).dispose();
        uiService.showDialog("Activate VCell client ImageJ service\nTools->'Start Fiji (ImageJ) service'\n" + e.getMessage(), "Couldn't contact VCell client", MessageType.ERROR_MESSAGE);
        return;
    }
    displayProgressBar(true, "Searching...", "Searching VCell Models");
    startJProgressThread0("Check", "Search");
    String theCacheKey = null;
    VCellHelper.VCellModelSearch vcms = new VCellHelper.VCellModelSearch(VCellHelper.ModelType.bm, vCellUser, vCellModel, application, simulation, null, null);
    try {
        ArrayList<VCellModelSearchResults> vcmsr = vcellHelper.getSearchedModelSimCacheKey(false, vcms, null);
        if (vcmsr.size() == 0) {
            throw new Exception("No Results for search found");
        }
        theCacheKey = vcmsr.get(0).getCacheKey();
        System.out.println("theCacheKey=" + theCacheKey);
        displayProgressBar(false, null, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
        uiService.showDialog("VCellHelper.ModelType.bm,vCellUser,vCellModel,application,simulation,null,null\n" + e.getMessage(), "Search failed", MessageType.ERROR_MESSAGE);
        displayProgressBar(false, null, null);
    }
    displayProgressBar(true, "Loading Data...", "Loading Data");
    startJProgressThread0("Search", "getTimePointData");
    try {
        String var = variable;
        int[] time = new int[] { timePoint };
        IJDataList tpd = vcellHelper.getTimePointData(theCacheKey, var, VCellHelper.VARTYPE_POSTPROC.NotPostProcess, time, 0);
        double[] data = tpd.ijData[0].getDoubleData();
        BasicStackDimensions bsd = tpd.ijData[0].stackInfo;
        System.out.println(bsd.xsize + " " + bsd.ysize);
        ArrayImg<DoubleType, DoubleArray> testimg = ArrayImgs.doubles(data, bsd.xsize, bsd.ysize);
        uiService.show(testimg);
        displayProgressBar(false, null, null);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        // e.printStackTrace();
        uiService.showDialog("theCacheKey,var,VCellHelper.VARTYPE_POSTPROC.NotPostProcess,time,0\n" + e.getMessage(), "getTimePoint(...) failed", MessageType.ERROR_MESSAGE);
        displayProgressBar(false, null, null);
    }
    startJProgressThread0("getTimePointData", null);
}
Also used : VCellModelSearchResults(org.vcell.imagej.helper.VCellHelper.VCellModelSearchResults) VCellHelper(org.vcell.imagej.helper.VCellHelper) DoubleType(net.imglib2.type.numeric.real.DoubleType) IJDataList(org.vcell.imagej.helper.VCellHelper.IJDataList) BasicStackDimensions(org.vcell.imagej.helper.VCellHelper.BasicStackDimensions) DoubleArray(net.imglib2.img.basictypeaccess.array.DoubleArray)

Aggregations

DoubleType (net.imglib2.type.numeric.real.DoubleType)6 DoubleArray (net.imglib2.img.basictypeaccess.array.DoubleArray)5 BasicStackDimensions (org.vcell.imagej.helper.VCellHelper.BasicStackDimensions)5 IJDataList (org.vcell.imagej.helper.VCellHelper.IJDataList)4 ImgPlus (net.imagej.ImgPlus)2 DefaultLinearAxis (net.imagej.axis.DefaultLinearAxis)2 DefaultDatasetView (net.imagej.display.DefaultDatasetView)2 DefaultImageDisplay (net.imagej.display.DefaultImageDisplay)2 IOException (java.io.IOException)1 BigDecimal (java.math.BigDecimal)1 URL (java.net.URL)1 ArrayList (java.util.ArrayList)1 StringTokenizer (java.util.StringTokenizer)1 UnsignedByteType (net.imglib2.type.numeric.integer.UnsignedByteType)1 VCellHelper (org.vcell.imagej.helper.VCellHelper)1 VCellModelSearchResults (org.vcell.imagej.helper.VCellHelper.VCellModelSearchResults)1 Document (org.w3c.dom.Document)1 Node (org.w3c.dom.Node)1 NodeList (org.w3c.dom.NodeList)1