Search in sources :

Example 6 with AsynchClientTask

use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.

the class PDEDataViewer method makeSurfaceMovie.

private void makeSurfaceMovie(final SurfaceCanvas surfaceCanvas, final int varTotalNumIndices, final String movieDataVarName, final DisplayAdapterService movieDAS, final VCDataIdentifier movieVCDataIdentifier) {
    final SurfaceMovieSettingsPanel smsp = new SurfaceMovieSettingsPanel();
    final double[] timePoints = getPdeDataContext().getTimePoints();
    final int surfaceWidth = surfaceCanvas.getWidth();
    final int surfaceHeight = surfaceCanvas.getHeight();
    smsp.init(surfaceWidth, surfaceHeight, timePoints);
    while (true) {
        if (PopupGenerator.showComponentOKCancelDialog(this, smsp, "Movie Settings for var " + movieDataVarName) != JOptionPane.OK_OPTION) {
            return;
        }
        long movieSize = (smsp.getTotalFrames() * surfaceWidth * surfaceHeight * 3);
        // raw data size;
        long rawDataSize = (smsp.getTotalFrames() * varTotalNumIndices * 8);
        if (movieSize + rawDataSize > 50000000) {
            final String YES_RESULT = "Yes";
            String result = PopupGenerator.showWarningDialog(this, "Movie processing will require at least " + (movieSize + rawDataSize) / 1000000 + " mega-bytes of memory.\nMovie size will be " + (movieSize >= 1000000 ? movieSize / 1000000 + " mega-bytes." : movieSize / 1000.0 + " kilo-bytes.") + " Continue?", new String[] { YES_RESULT, "No" }, YES_RESULT);
            if (result != null && result.equals(YES_RESULT)) {
                break;
            }
        } else {
            break;
        }
    }
    final int beginTimeIndex = smsp.getBeginTimeIndex();
    final int endTimeIndex = smsp.getEndTimeIndex();
    final int step = smsp.getSkipParameter() + 1;
    final String[] varNames = new String[] { movieDataVarName };
    int[] allIndices = new int[varTotalNumIndices];
    for (int i = 0; i < allIndices.length; i++) {
        allIndices[i] = i;
    }
    final TimeSeriesJobSpec timeSeriesJobSpec = new TimeSeriesJobSpec(varNames, new int[][] { allIndices }, null, timePoints[beginTimeIndex], step, timePoints[endTimeIndex], VCDataJobID.createVCDataJobID(getDataViewerManager().getUser(), true));
    Hashtable<String, Object> hash = new Hashtable<String, Object>();
    hash.put(StringKey_timeSeriesJobSpec, timeSeriesJobSpec);
    AsynchClientTask task1 = new TimeSeriesDataRetrievalTask("Retrieving data for variable '" + movieDataVarName + "'", PDEDataViewer.this, getPdeDataContext());
    AsynchClientTask task2 = new AsynchClientTask("select a file", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            VCFileChooser fileChooser = new VCFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.setMultiSelectionEnabled(false);
            fileChooser.addChoosableFileFilter(FileFilters.FILE_FILTER_MOV);
            // Set the default file filter...
            fileChooser.setFileFilter(FileFilters.FILE_FILTER_MOV);
            // remove all selector
            fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
            fileChooser.setDialogTitle("Saving surface movie");
            File selectedFile = null;
            while (true) {
                if (fileChooser.showSaveDialog(PDEDataViewer.this) != JFileChooser.APPROVE_OPTION) {
                    return;
                }
                selectedFile = fileChooser.getSelectedFile();
                if (!selectedFile.getName().endsWith(".mov")) {
                    selectedFile = new File(selectedFile.getAbsolutePath() + ".mov");
                }
                if (selectedFile.exists()) {
                    final String YES_RESULT = "Yes";
                    String result = PopupGenerator.showWarningDialog(PDEDataViewer.this, "Overwrite exisitng file:\n" + selectedFile.getAbsolutePath() + "?", new String[] { YES_RESULT, "No" }, YES_RESULT);
                    if (result != null && result.equals(YES_RESULT)) {
                        break;
                    }
                } else {
                    break;
                }
            }
            hashTable.put("selectedFile", selectedFile);
        }
    };
    AsynchClientTask task3 = new AsynchClientTask("create movie", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            File selectedFile = (File) hashTable.get("selectedFile");
            if (selectedFile == null) {
                return;
            }
            TSJobResultsNoStats tsJobResultsNoStats = (TSJobResultsNoStats) hashTable.get(StringKey_timeSeriesJobResults);
            double[][] timeSeries = tsJobResultsNoStats.getTimesAndValuesForVariable(movieDataVarName);
            int[] singleFrame = new int[surfaceWidth * surfaceHeight];
            BufferedImage bufferedImage = new BufferedImage(surfaceWidth, surfaceHeight, BufferedImage.TYPE_3BYTE_BGR);
            Graphics2D g2D = bufferedImage.createGraphics();
            VideoMediaChunk[] chunks = new VideoMediaChunk[tsJobResultsNoStats.getTimes().length];
            VideoMediaSample sample;
            int sampleDuration = 0;
            int timeScale = smsp.getFramesPerSecond();
            int bitsPerPixel = 32;
            DisplayAdapterService das = new DisplayAdapterService(movieDAS);
            int[][] origSurfacesColors = surfaceCanvas.getSurfacesColors();
            DataInfoProvider dataInfoProvider = getPDEDataContextPanel1().getDataInfoProvider();
            FileDataContainerManager fileDataContainerManager = new FileDataContainerManager();
            try {
                try {
                    for (int t = 0; t < tsJobResultsNoStats.getTimes().length; t++) {
                        getClientTaskStatusSupport().setMessage("Creating Movie... Progress " + NumberUtils.formatNumber(100.0 * ((double) t / (double) tsJobResultsNoStats.getTimes().length), 3) + "%");
                        double min = Double.POSITIVE_INFINITY;
                        double max = Double.NEGATIVE_INFINITY;
                        for (int index = 1; index < timeSeries.length; index++) {
                            double v = timeSeries[index][t];
                            if ((dataInfoProvider == null || dataInfoProvider.isDefined(index - 1)) && !Double.isNaN(v) && !Double.isInfinite(v)) {
                                min = Math.min(min, v);
                                max = Math.max(max, v);
                            }
                        }
                        das.setValueDomain(new Range(min, max));
                        if (das.getAutoScale()) {
                            das.setActiveScaleRange(new Range(min, max));
                        }
                        int[][] surfacesColors = new int[surfaceCanvas.getSurfaceCollection().getSurfaceCount()][];
                        for (int i = 0; i < surfaceCanvas.getSurfaceCollection().getSurfaceCount(); i += 1) {
                            Surface surface = surfaceCanvas.getSurfaceCollection().getSurfaces(i);
                            surfacesColors[i] = new int[surface.getPolygonCount()];
                            for (int j = 0; j < surface.getPolygonCount(); j += 1) {
                                int membIndex = meshRegionSurfaces.getMembraneIndexForPolygon(i, j);
                                surfacesColors[i][j] = das.getColorFromValue(timeSeries[membIndex + 1][t]);
                            }
                        }
                        surfaceCanvas.setSurfacesColors(surfacesColors);
                        surfaceCanvas.paintImmediately(0, 0, surfaceWidth, surfaceHeight);
                        surfaceCanvas.paint(g2D);
                        bufferedImage.getRGB(0, 0, surfaceWidth, surfaceHeight, singleFrame, 0, surfaceWidth);
                        sampleDuration = 1;
                        sample = FormatSpecificSpecs.getVideoMediaSample(surfaceWidth, surfaceHeight * varNames.length, sampleDuration, false, FormatSpecificSpecs.CODEC_JPEG, 1.0f, singleFrame);
                        chunks[t] = new VideoMediaChunk(sample, fileDataContainerManager);
                    }
                } finally {
                    surfaceCanvas.setSurfacesColors(origSurfacesColors);
                    surfaceCanvas.paintImmediately(0, 0, surfaceWidth, surfaceHeight);
                }
                MediaTrack videoTrack = new MediaTrack(chunks);
                MediaMovie newMovie = new MediaMovie(videoTrack, videoTrack.getDuration(), timeScale);
                newMovie.addUserDataEntry(new UserDataEntry("cpy", "\u00A9" + (new GregorianCalendar()).get(Calendar.YEAR) + ", UCHC"));
                newMovie.addUserDataEntry(new UserDataEntry("des", "Dataset name: " + movieVCDataIdentifier.getID()));
                newMovie.addUserDataEntry(new UserDataEntry("cmt", "Time range: " + timePoints[beginTimeIndex] + " - " + timePoints[endTimeIndex]));
                for (int k = 0; k < varNames.length; k++) {
                    // pad with 0 if k < 10
                    String entryType = "v" + (k < 10 ? "0" : "") + k;
                    UserDataEntry entry = new UserDataEntry(entryType, "Variable name: " + varNames[k] + " min: " + das.getValueDomain().getMin() + " max: " + das.getValueDomain().getMax());
                    newMovie.addUserDataEntry(entry);
                }
                getClientTaskStatusSupport().setMessage("Writing Movie to disk...");
                FileOutputStream fos = new FileOutputStream(selectedFile);
                DataOutputStream movieOutput = new DataOutputStream(new BufferedOutputStream(fos));
                MediaMethods.writeMovie(movieOutput, newMovie);
                movieOutput.close();
                fos.close();
            } finally {
                fileDataContainerManager.closeAllAndDelete();
            }
        }
    };
    ClientTaskDispatcher.dispatch(this, hash, new AsynchClientTask[] { task1, task2, task3 }, true, true, null);
}
Also used : DisplayAdapterService(cbit.image.DisplayAdapterService) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) TimeSeriesJobSpec(org.vcell.util.document.TimeSeriesJobSpec) DataOutputStream(java.io.DataOutputStream) DataInfoProvider(cbit.vcell.simdata.DataInfoProvider) FileDataContainerManager(cbit.vcell.export.server.FileDataContainerManager) BufferedImage(java.awt.image.BufferedImage) VideoMediaSample(cbit.vcell.export.gloworm.quicktime.VideoMediaSample) Surface(cbit.vcell.geometry.surface.Surface) VCFileChooser(org.vcell.util.gui.VCFileChooser) VideoMediaChunk(cbit.vcell.export.gloworm.quicktime.VideoMediaChunk) BufferedOutputStream(java.io.BufferedOutputStream) Hashtable(java.util.Hashtable) UserDataEntry(cbit.vcell.export.gloworm.atoms.UserDataEntry) GregorianCalendar(java.util.GregorianCalendar) Range(org.vcell.util.Range) Point(java.awt.Point) SinglePoint(cbit.vcell.geometry.SinglePoint) Graphics2D(java.awt.Graphics2D) MediaTrack(cbit.vcell.export.gloworm.quicktime.MediaTrack) FileOutputStream(java.io.FileOutputStream) SurfaceMovieSettingsPanel(cbit.vcell.geometry.gui.SurfaceMovieSettingsPanel) File(java.io.File) TSJobResultsNoStats(org.vcell.util.document.TSJobResultsNoStats) MediaMovie(cbit.vcell.export.gloworm.quicktime.MediaMovie)

Example 7 with AsynchClientTask

use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.

the class PDEDataViewer method roiAction.

private void roiAction() {
    BeanUtils.setCursorThroughout(this, Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    try {
        final String[] ROI_COLUMN_NAMES = new String[] { "ROI source", "ROI source name", "ROI Description" };
        final Vector<Object> auxInfoV = new Vector<Object>();
        final DataIdentifier dataIdentifier = getPdeDataContext().getDataIdentifier();
        VariableType variableType = dataIdentifier.getVariableType();
        final boolean isVolume = variableType.equals(VariableType.VOLUME) || variableType.equals(VariableType.VOLUME_REGION);
        DefaultTableModel tableModel = new DefaultTableModel() {

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        for (int i = 0; i < ROI_COLUMN_NAMES.length; i++) {
            tableModel.addColumn(ROI_COLUMN_NAMES[i]);
        }
        // Add Snapshot ROI
        if ((isVolume ? volumeSnapshotROI : membraneSnapshotROI) != null) {
            tableModel.addRow(new Object[] { (isVolume ? "Volume" : "Membrane") + " Variables and Functions", "Snapshot", (isVolume ? volumeSnapshotROIDescription : membraneSnapshotROIDescription) + ", (values = 1.0)" });
            auxInfoV.add((isVolume ? volumeSnapshotROI : membraneSnapshotROI));
        }
        // Add user ROIs
        SpatialSelection[] userROIArr = getPDEDataContextPanel1().fetchSpatialSelections(true, false);
        for (int i = 0; userROIArr != null && i < userROIArr.length; i += 1) {
            String descr = null;
            boolean bPoint = false;
            if (isVolume) {
                if (userROIArr[i] instanceof SpatialSelectionVolume) {
                    Curve curve = ((SpatialSelectionVolume) userROIArr[i]).getCurveSelectionInfo().getCurve();
                    descr = curve.getDescription();
                    if (curve instanceof SinglePoint) {
                        bPoint = true;
                    }
                }
            } else {
                if (userROIArr[i] instanceof SpatialSelectionMembrane) {
                    SampledCurve selectionSource = ((SpatialSelectionMembrane) userROIArr[i]).getSelectionSource();
                    descr = selectionSource.getDescription();
                    if (selectionSource instanceof SinglePoint) {
                        bPoint = true;
                    }
                }
            }
            // Add Area User ROI
            BitSet fillBitSet = null;
            if (userROIArr[i] instanceof SpatialSelectionVolume) {
                fillBitSet = getFillROI((SpatialSelectionVolume) userROIArr[i]);
                if (fillBitSet != null) {
                    tableModel.addRow(new Object[] { "User Defined", descr, "Area Enclosed Volume ROI" });
                    auxInfoV.add(fillBitSet);
                }
            }
            // Add Point and Line User ROI
            if (fillBitSet == null) {
                tableModel.addRow(new Object[] { "User Defined", descr, (bPoint ? "Point" : "Line") + (isVolume ? " Volume" : " Membrane") + " ROI " });
                auxInfoV.add(userROIArr[i]);
            }
        }
        // Add sorted Geometry ROI
        final CartesianMesh cartesianMesh = getPdeDataContext().getCartesianMesh();
        HashMap<Integer, ?> regionMapSubvolumesHashMap = (isVolume ? cartesianMesh.getVolumeRegionMapSubvolume() : cartesianMesh.getMembraneRegionMapSubvolumesInOut());
        Set<?> regionMapSubvolumesEntrySet = regionMapSubvolumesHashMap.entrySet();
        Iterator<?> regionMapSubvolumesEntryIter = regionMapSubvolumesEntrySet.iterator();
        TreeSet<Object[]> sortedGeomROITreeSet = new TreeSet<Object[]>(new Comparator<Object[]>() {

            public int compare(Object[] o1, Object[] o2) {
                int result = ((String) ((Object[]) o1[0])[1]).compareToIgnoreCase((String) ((Object[]) o2[0])[1]);
                if (result == 0) {
                    result = (((Entry<Integer, ?>) o1[1]).getKey()).compareTo(((Entry<Integer, ?>) o2[1]).getKey());
                }
                return result;
            }
        });
        while (regionMapSubvolumesEntryIter.hasNext()) {
            Entry<Integer, ?> regionMapSubvolumesEntry = (Entry<Integer, ?>) regionMapSubvolumesEntryIter.next();
            sortedGeomROITreeSet.add(new Object[] { new Object[] { "Geometry", (isVolume ? getSimulationModelInfo().getVolumeNamePhysiology(((Integer) regionMapSubvolumesEntry.getValue())) : getSimulationModelInfo().getMembraneName(((int[]) regionMapSubvolumesEntry.getValue())[0], ((int[]) regionMapSubvolumesEntry.getValue())[1], false)), (isVolume ? "(svID=" + regionMapSubvolumesEntry.getValue() + " " : "(") + "vrID=" + regionMapSubvolumesEntry.getKey() + ") Predefined " + (isVolume ? "volume" : "membrane") + " region" }, regionMapSubvolumesEntry });
        }
        Iterator<Object[]> sortedGeomROIIter = sortedGeomROITreeSet.iterator();
        while (sortedGeomROIIter.hasNext()) {
            Object[] sortedGeomROIObjArr = (Object[]) sortedGeomROIIter.next();
            tableModel.addRow((Object[]) sortedGeomROIObjArr[0]);
            auxInfoV.add(sortedGeomROIObjArr[1]);
        }
        final ScrollTable roiTable = new ScrollTable();
        roiTable.setModel(tableModel);
        roiTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        roiTable.setPreferredScrollableViewportSize(new Dimension(500, 200));
        final JPanel mainJPanel = new JPanel();
        BoxLayout mainBL = new BoxLayout(mainJPanel, BoxLayout.Y_AXIS);
        mainJPanel.setLayout(mainBL);
        MiniTimePanel timeJPanel = new MiniTimePanel();
        ActionListener okAction = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (((Double) timeJPanel.jcb_time_begin.getSelectedItem()).compareTo((Double) timeJPanel.jcb_time_end.getSelectedItem()) > 0) {
                    PopupGenerator.showErrorDialog(PDEDataViewer.this, "Selected 'Begin Time' must be less than or equal to 'End Time'");
                    return;
                }
                int[] selectedRows = roiTable.getSelectedRows();
                if (selectedRows != null) {
                    try {
                        BitSet dataBitSet = new BitSet(getPdeDataContext().getDataValues().length);
                        for (int i = 0; i < selectedRows.length; i++) {
                            Object auxInfo = auxInfoV.elementAt(selectedRows[i]);
                            if (auxInfo instanceof BitSet) {
                                dataBitSet.or((BitSet) auxInfo);
                            } else if (auxInfo instanceof SpatialSelectionMembrane) {
                                int[] roiIndexes = ((SpatialSelectionMembrane) auxInfo).getIndexSamples().getSampledIndexes();
                                for (int j = 0; j < roiIndexes.length; j += 1) {
                                    dataBitSet.set(roiIndexes[j], true);
                                }
                            } else if (auxInfo instanceof SpatialSelectionVolume) {
                                int[] roiIndexes = ((SpatialSelectionVolume) auxInfo).getIndexSamples(0, 1).getSampledIndexes();
                                for (int j = 0; j < roiIndexes.length; j += 1) {
                                    dataBitSet.set(roiIndexes[j], true);
                                }
                            } else if (auxInfo instanceof Entry) {
                                Entry<Integer, Integer> entry = (Entry<Integer, Integer>) auxInfo;
                                if (isVolume) {
                                    int volumeRegionID = entry.getKey();
                                    dataBitSet.or(cartesianMesh.getVolumeROIFromVolumeRegionID(volumeRegionID));
                                } else {
                                    int membraneRegionID = entry.getKey();
                                    dataBitSet.or(cartesianMesh.getMembraneROIFromMembraneRegionID(membraneRegionID));
                                }
                            } else if (auxInfo instanceof BitSet) {
                                dataBitSet.or((BitSet) auxInfo);
                            } else {
                                throw new Exception("ROI table, Unknown data type: " + auxInfo.getClass().getName());
                            }
                        }
                        TimeSeriesJobSpec timeSeriesJobSpec = new TimeSeriesJobSpec(new String[] { dataIdentifier.getName() }, new BitSet[] { dataBitSet }, ((Double) timeJPanel.jcb_time_begin.getSelectedItem()).doubleValue(), 1, ((Double) timeJPanel.jcb_time_end.getSelectedItem()).doubleValue(), true, false, VCDataJobID.createVCDataJobID(getDataViewerManager().getUser(), true));
                        Hashtable<String, Object> hash = new Hashtable<String, Object>();
                        hash.put(StringKey_timeSeriesJobSpec, timeSeriesJobSpec);
                        AsynchClientTask task1 = new TimeSeriesDataRetrievalTask("Retrieve data for '" + dataIdentifier + "'", PDEDataViewer.this, getPdeDataContext());
                        AsynchClientTask task2 = new AsynchClientTask("Showing stat for '" + dataIdentifier + "'", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

                            @Override
                            public void run(Hashtable<String, Object> hashTable) throws Exception {
                                TSJobResultsSpaceStats tsJobResultsSpaceStats = (TSJobResultsSpaceStats) hashTable.get(StringKey_timeSeriesJobResults);
                                plotSpaceStats(tsJobResultsSpaceStats);
                            }
                        };
                        ClientTaskDispatcher.dispatch(PDEDataViewer.this, hash, new AsynchClientTask[] { task1, task2 }, true, true, null);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        PopupGenerator.showErrorDialog(PDEDataViewer.this, "ROI Error.\n" + e1.getMessage(), e1);
                    }
                }
                BeanUtils.disposeParentWindow(mainJPanel);
            }
        };
        ActionListener cancelAction = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                BeanUtils.disposeParentWindow(mainJPanel);
            }
        };
        OkCancelSubPanel okCancelJPanel = new OkCancelSubPanel(okAction, cancelAction);
        roiTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (roiTable.getSelectedRows() != null && roiTable.getSelectedRows().length > 0) {
                    okCancelJPanel.okButton.setEnabled(true);
                } else {
                    okCancelJPanel.okButton.setEnabled(false);
                }
            }
        });
        mainJPanel.add(timeJPanel);
        mainJPanel.add(roiTable.getEnclosingScrollPane());
        mainJPanel.add(okCancelJPanel);
        // showComponentInFrame(mainJPanel,
        // "Calculate "+(isVolume?"volume":"membrane")+" statistics for '"+getPdeDataContext().getVariableName()+"'."+
        // "  Choose times and 1 or more ROI(s).");
        Frame dialogOwner = JOptionPane.getFrameForComponent(this);
        JOptionPane inputDialog = new JOptionPane(mainJPanel, JOptionPane.PLAIN_MESSAGE, 0, null, new Object[0]);
        final JDialog d = inputDialog.createDialog(dialogOwner, "Calculate " + (isVolume ? "volume" : "membrane") + " statistics for '" + getPdeDataContext().getVariableName() + "'." + "  Choose times and 1 or more ROI(s).");
        d.setResizable(true);
        try {
            DialogUtils.showModalJDialogOnTop(d, PDEDataViewer.this);
        } finally {
            d.dispose();
        }
    } finally {
        BeanUtils.setCursorThroughout(this, Cursor.getDefaultCursor());
    }
}
Also used : JPanel(javax.swing.JPanel) VCSimulationDataIdentifier(cbit.vcell.solver.VCSimulationDataIdentifier) LocalVCSimulationDataIdentifier(cbit.vcell.client.ClientSimManager.LocalVCSimulationDataIdentifier) ExternalDataIdentifier(org.vcell.util.document.ExternalDataIdentifier) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier) DataIdentifier(cbit.vcell.simdata.DataIdentifier) ScrollTable(org.vcell.util.gui.ScrollTable) TimeSeriesJobSpec(org.vcell.util.document.TimeSeriesJobSpec) ActionEvent(java.awt.event.ActionEvent) TreeSet(java.util.TreeSet) Vector(java.util.Vector) SampledCurve(cbit.vcell.geometry.SampledCurve) Curve(cbit.vcell.geometry.Curve) BitSet(java.util.BitSet) TSJobResultsSpaceStats(org.vcell.util.document.TSJobResultsSpaceStats) JOptionPane(javax.swing.JOptionPane) ListSelectionListener(javax.swing.event.ListSelectionListener) CartesianMesh(cbit.vcell.solvers.CartesianMesh) ActionListener(java.awt.event.ActionListener) SpatialSelectionVolume(cbit.vcell.simdata.SpatialSelectionVolume) JDialog(javax.swing.JDialog) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Frame(java.awt.Frame) SpatialSelectionMembrane(cbit.vcell.simdata.SpatialSelectionMembrane) DefaultTableModel(javax.swing.table.DefaultTableModel) BoxLayout(javax.swing.BoxLayout) ListSelectionEvent(javax.swing.event.ListSelectionEvent) SymbolTableEntry(cbit.vcell.parser.SymbolTableEntry) Entry(java.util.Map.Entry) UserDataEntry(cbit.vcell.export.gloworm.atoms.UserDataEntry) SinglePoint(cbit.vcell.geometry.SinglePoint) SpatialSelection(cbit.vcell.simdata.SpatialSelection) SampledCurve(cbit.vcell.geometry.SampledCurve) VariableType(cbit.vcell.math.VariableType) Hashtable(java.util.Hashtable) Dimension(java.awt.Dimension) Point(java.awt.Point) SinglePoint(cbit.vcell.geometry.SinglePoint) DataAccessException(org.vcell.util.DataAccessException) PropertyVetoException(java.beans.PropertyVetoException) ImageException(cbit.image.ImageException) UserCancelException(org.vcell.util.UserCancelException)

Example 8 with AsynchClientTask

use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.

the class PDEDataViewer method updateDataValueSurfaceViewer0.

// private AsynchClientTask[] getDataVlaueSurfaceViewerTasks(){
// AsynchClientTask createDataValueSurfaceViewerTask = new AsynchClientTask("Create surface viewer...",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
// @Override
// public void run(Hashtable<String, Object> hashTable) throws Exception {
// if(getDataValueSurfaceViewer().getSurfaceCollectionDataInfoProvider() == null){
// createDataValueSurfaceViewer(getClientTaskStatusSupport());
// }
// }
// };
// 
// AsynchClientTask updateDataValueSurfaceViewerTask = new AsynchClientTask("Update surface viewer...",AsynchClientTask.TASKTYPE_SWING_BLOCKING) {
// @Override
// public void run(Hashtable<String, Object> hashTable) throws Exception {
// updateDataValueSurfaceViewer0();
// }
// };
// 
// AsynchClientTask resetDataValueSurfaceViewerTask = new AsynchClientTask("Reset tab...",AsynchClientTask.TASKTYPE_SWING_NONBLOCKING,false,false) {
// @Override
// public void run(Hashtable<String, Object> hashTable) throws Exception {
// if(getDataValueSurfaceViewer().getSurfaceCollectionDataInfoProvider() == null){
// viewDataTabbedPane.setSelectedIndex(0);
// }
// }
// };
// return new AsynchClientTask[] {createDataValueSurfaceViewerTask,updateDataValueSurfaceViewerTask,resetDataValueSurfaceViewerTask};
// }
// private Timer dataValueSurfaceTimer;
// //private boolean bPdeIsParamScan=false;
// private void updateDataValueSurfaceViewer(){
// //	if((dataValueSurfaceTimer = ClientTaskDispatcher.getBlockingTimer(this,getPdeDataContext(),null,dataValueSurfaceTimer,new ActionListener() {@Override public void actionPerformed(ActionEvent e2) {updateDataValueSurfaceViewer();}}))!=null){
// //		return;
// //	}
// if(bSkipSurfaceCalc){
// return;
// }
// if(getDataValueSurfaceViewer().getSurfaceCollectionDataInfoProvider() == null){
// if((dataValueSurfaceTimer = ClientTaskDispatcher.getBlockingTimer(this,getPdeDataContext(),null,dataValueSurfaceTimer,new ActionListener() {@Override public void actionPerformed(ActionEvent e2) {updateDataValueSurfaceViewer();}}))!=null){
// return;
// }
// ClientTaskDispatcher.dispatch(this, new Hashtable<String, Object>(), getDataVlaueSurfaceViewerTasks(),true,true,null);
// }else{
// try{
// updateDataValueSurfaceViewer0();
// }catch(Exception e){
// e.printStackTrace();
// DialogUtils.showErrorDialog(this, e.getMessage());
// }
// }
// }
/**
 * Insert the method's description here.
 * Creation date: (9/25/2005 2:00:05 PM)
 */
private void updateDataValueSurfaceViewer0() {
    // viewDataTabbedPane.addTab(CurrentView.SURFACE_VIEW.title, getDataValueSurfaceViewer());
    if (viewDataTabbedPane.getSelectedIndex() != CurrentView.SURFACE_VIEW.ordinal()) {
        return;
    }
    // SurfaceColors and DataValues
    if (getDataValueSurfaceViewer().getSurfaceCollectionDataInfo() == null) {
        // happens with PostProcessingImageData version of PDEDataViewer
        return;
    }
    SurfaceCollection surfaceCollection = getDataValueSurfaceViewer().getSurfaceCollectionDataInfo().getSurfaceCollection();
    DisplayAdapterService das = getPDEDataContextPanel1().getdisplayAdapterService1();
    final int[][] surfaceColors = new int[surfaceCollection.getSurfaceCount()][];
    final double[][] surfaceDataValues = new double[surfaceCollection.getSurfaceCount()][];
    boolean bMembraneVariable = getPdeDataContext().getDataIdentifier().getVariableType().equals(VariableType.MEMBRANE);
    RecodeDataForDomainInfo recodeDataForDomainInfo = getPDEDataContextPanel1().getRecodeDataForDomainInfo();
    double[] membraneValues = (recodeDataForDomainInfo.isRecoded() ? recodeDataForDomainInfo.getRecodedDataForDomain() : getPdeDataContext().getDataValues());
    for (int i = 0; i < surfaceCollection.getSurfaceCount(); i += 1) {
        Surface surface = surfaceCollection.getSurfaces(i);
        surfaceColors[i] = new int[surface.getPolygonCount()];
        surfaceDataValues[i] = new double[surface.getPolygonCount()];
        for (int j = 0; j < surface.getPolygonCount(); j += 1) {
            int membraneIndexForPolygon = meshRegionSurfaces.getMembraneIndexForPolygon(i, j);
            if (bMembraneVariable) {
                surfaceDataValues[i][j] = membraneValues[membraneIndexForPolygon];
            } else {
                // get membrane region index from membrane index
                surfaceDataValues[i][j] = membraneValues[getPdeDataContext().getCartesianMesh().getMembraneRegionIndex(membraneIndexForPolygon)];
            }
            surfaceColors[i][j] = das.getColorFromValue(surfaceDataValues[i][j]);
        }
    }
    DataValueSurfaceViewer.SurfaceCollectionDataInfoProvider svdp = new DataValueSurfaceViewer.SurfaceCollectionDataInfoProvider() {

        private DisplayAdapterService updatedDAS = new DisplayAdapterService(getPDEDataContextPanel1().getdisplayAdapterService1());

        private String updatedVariableName = getPdeDataContext().getVariableName();

        private double updatedTimePoint = getPdeDataContext().getTimePoint();

        private double[] updatedVariableValues = getPdeDataContext().getDataValues();

        private VCDataIdentifier updatedVCDataIdentifier = getPdeDataContext().getVCDataIdentifier();

        public void makeMovie(SurfaceCanvas surfaceCanvas) {
            makeSurfaceMovie(surfaceCanvas, updatedVariableValues.length, updatedVariableName, updatedDAS, updatedVCDataIdentifier);
        }

        public double getValue(int surfaceIndex, int polygonIndex) {
            return updatedVariableValues[meshRegionSurfaces.getMembraneIndexForPolygon(surfaceIndex, polygonIndex)];
        }

        public String getValueDescription(int surfaceIndex, int polygonIndex) {
            return updatedVariableName;
        }

        public int[][] getSurfacePolygonColors() {
            return surfaceColors;
        }

        public Coordinate getCentroid(int surfaceIndex, int polygonIndex) {
            return getPdeDataContext().getCartesianMesh().getMembraneElements()[meshRegionSurfaces.getMembraneIndexForPolygon(surfaceIndex, polygonIndex)].getCentroid();
        }

        public float getArea(int surfaceIndex, int polygonIndex) {
            return getPdeDataContext().getCartesianMesh().getMembraneElements()[meshRegionSurfaces.getMembraneIndexForPolygon(surfaceIndex, polygonIndex)].getArea();
        }

        public Vect3d getNormal(int surfaceIndex, int polygonIndex) {
            return getPdeDataContext().getCartesianMesh().getMembraneElements()[meshRegionSurfaces.getMembraneIndexForPolygon(surfaceIndex, polygonIndex)].getNormal();
        }

        public int getMembraneIndex(int surfaceIndex, int polygonIndex) {
            return meshRegionSurfaces.getMembraneIndexForPolygon(surfaceIndex, polygonIndex);
        }

        public Color getROIHighlightColor() {
            return new Color(getPDEDataContextPanel1().getdisplayAdapterService1().getSpecialColors()[cbit.image.DisplayAdapterService.FOREGROUND_HIGHLIGHT_COLOR_OFFSET]);
        }

        @Override
        public boolean isMembrIndexInVarDomain(int membrIndex) {
            return (getPDEDataContextPanel1().getRecodeDataForDomainInfo() != null ? getPDEDataContextPanel1().getRecodeDataForDomainInfo().isIndexInDomain(membrIndex) : true);
        }

        // public void showComponentInFrame(Component comp,String title){
        // PDEDataViewer.this.showComponentInFrame(comp,title);
        // }
        public void plotTimeSeriesData(int[][] indices, boolean bAllTimes, boolean bTimeStats, boolean bSpaceStats) throws DataAccessException {
            double[] timePoints = getPdeDataContext().getTimePoints();
            double beginTime = (bAllTimes ? timePoints[0] : updatedTimePoint);
            double endTime = (bAllTimes ? timePoints[timePoints.length - 1] : beginTime);
            String[] varNames = new String[indices.length];
            for (int i = 0; i < varNames.length; i += 1) {
                varNames[i] = updatedVariableName;
            }
            TimeSeriesJobSpec timeSeriesJobSpec = new TimeSeriesJobSpec(varNames, indices, beginTime, 1, endTime, bSpaceStats, bTimeStats, VCDataJobID.createVCDataJobID(getDataViewerManager().getUser(), true));
            Hashtable<String, Object> hash = new Hashtable<String, Object>();
            hash.put(StringKey_timeSeriesJobSpec, timeSeriesJobSpec);
            AsynchClientTask task1 = new TimeSeriesDataRetrievalTask("Retrieve data", PDEDataViewer.this, getPdeDataContext());
            AsynchClientTask task2 = new AsynchClientTask("Showing surface", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

                @Override
                public void run(Hashtable<String, Object> hashTable) throws Exception {
                    TSJobResultsSpaceStats tsJobResultsSpaceStats = (TSJobResultsSpaceStats) hashTable.get(StringKey_timeSeriesJobResults);
                    plotSpaceStats(tsJobResultsSpaceStats);
                }
            };
            ClientTaskDispatcher.dispatch(PDEDataViewer.this, hash, new AsynchClientTask[] { task1, task2 }, true, true, null);
        }
    };
    getDataValueSurfaceViewer().setSurfaceCollectionDataInfoProvider(svdp);
}
Also used : DisplayAdapterService(cbit.image.DisplayAdapterService) AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) TimeSeriesJobSpec(org.vcell.util.document.TimeSeriesJobSpec) Surface(cbit.vcell.geometry.surface.Surface) RecodeDataForDomainInfo(cbit.vcell.simdata.gui.PDEDataContextPanel.RecodeDataForDomainInfo) SurfaceCollection(cbit.vcell.geometry.surface.SurfaceCollection) Hashtable(java.util.Hashtable) Color(java.awt.Color) TSJobResultsSpaceStats(org.vcell.util.document.TSJobResultsSpaceStats) Point(java.awt.Point) SinglePoint(cbit.vcell.geometry.SinglePoint) SurfaceCanvas(cbit.vcell.geometry.gui.SurfaceCanvas) DataValueSurfaceViewer(cbit.vcell.geometry.gui.DataValueSurfaceViewer) VCDataIdentifier(org.vcell.util.document.VCDataIdentifier)

Example 9 with AsynchClientTask

use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.

the class PDEDataViewerPostProcess method getUpdateTasks.

public AsynchClientTask[] getUpdateTasks() {
    final String POST_PROCESS_PDEDC_KEY = "POST_PROCESS_PDEDC_KEY";
    AsynchClientTask createPostProcessPDETask = new AsynchClientTask("create postprocess pdedc", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            hashTable.put(POST_PROCESS_PDEDC_KEY, createPostProcessPDEDataContext((ClientPDEDataContext) getParentPdeDataContext()));
        }
    };
    AsynchClientTask setPostProcessPDETask = new AsynchClientTask("set postproces pdedc", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            postProcessPDEDataViewer.setPdeDataContext((ClientPDEDataContext) hashTable.get(POST_PROCESS_PDEDC_KEY));
        }
    };
    return new AsynchClientTask[] { /*listenersTask,*/
    createPostProcessPDETask, setPostProcessPDETask };
// ClientTaskDispatcher.dispatch(myPDEDataViewer, new Hashtable<>(), new AsynchClientTask[] {listenersTask,createPostProcessPDETask,setPostProcessPDETask},false,false,null);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) ClientPDEDataContext(cbit.vcell.simdata.ClientPDEDataContext)

Example 10 with AsynchClientTask

use of cbit.vcell.client.task.AsynchClientTask in project vcell by virtualcell.

the class PDEDataViewerPostProcess method dispatchPostProcessUpdate.

private void dispatchPostProcessUpdate(ClientPDEDataContext newClientPDEDataContext) {
    ArrayList<AsynchClientTask> allTasks = new ArrayList<>();
    final String SPATIAL_ERROR_KEY = "SPATIAL_ERROR_KEY";
    AsynchClientTask postProcessInfoTask = new AsynchClientTask("", AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (postProcessPDEDataViewer != null) {
                // already initialized
                return;
            }
            if (getClientTaskStatusSupport() != null) {
                getClientTaskStatusSupport().setMessage("Getting Simulation status...");
            }
            SimulationStatus simStatus = PDEDataViewerPostProcess.this.getDataViewerManager().getRequestManager().getServerSimulationStatus(PDEDataViewerPostProcess.this.getSimulation().getSimulationInfo());
            if (simStatus == null) {
                hashTable.put(SPATIAL_ERROR_KEY, "PostProcessing Image, no simulation status");
                return;
            } else if (!simStatus.isCompleted()) {
                // sim still busy, no postprocessing data
                hashTable.put(SPATIAL_ERROR_KEY, "PostProcessing Image, waiting for completed simulation: " + simStatus.toString());
                return;
            }
            if (getClientTaskStatusSupport() != null) {
                getClientTaskStatusSupport().setMessage("Getting Post Process Info...");
            }
            // Get PostProcess Image state variables info
            DataProcessingOutputInfoOP dataProcessingOutputInfoOP = new DataProcessingOutputInfoOP(PDEDataViewerPostProcess.this.getParentPdeDataContext().getVCDataIdentifier(), false, null);
            DataProcessingOutputInfo dataProcessingOutputInfo = (DataProcessingOutputInfo) PDEDataViewerPostProcess.this.getParentPdeDataContext().doDataOperation(dataProcessingOutputInfoOP);
            boolean bFoundImageStateVariables = false;
            if (dataProcessingOutputInfo != null && dataProcessingOutputInfo.getVariableNames() != null) {
                for (int i = 0; i < dataProcessingOutputInfo.getVariableNames().length; i++) {
                    if (dataProcessingOutputInfo.getPostProcessDataType(dataProcessingOutputInfo.getVariableNames()[i]).equals(DataProcessingOutputInfo.PostProcessDataType.image)) {
                        bFoundImageStateVariables = true;
                        break;
                    }
                }
            }
            if (!bFoundImageStateVariables) {
                hashTable.put(SPATIAL_ERROR_KEY, "No spatial PostProcessing variables found. (see Application->Protocols->Microscope Measurement)");
            }
        }
    };
    AsynchClientTask addPanelTask = new AsynchClientTask("", AsynchClientTask.TASKTYPE_SWING_BLOCKING) {

        @Override
        public void run(Hashtable<String, Object> hashTable) throws Exception {
            if (postProcessPDEDataViewer != null) {
                return;
            }
            if (hashTable.get(SPATIAL_ERROR_KEY) != null) {
                if (PDEDataViewerPostProcess.this.getComponentCount() == 0) {
                    PDEDataViewerPostProcess.this.add(new JLabel((String) hashTable.get(SPATIAL_ERROR_KEY)), BorderLayout.CENTER);
                } else {
                    ((JLabel) PDEDataViewerPostProcess.this.getComponent(0)).setText((String) hashTable.get(SPATIAL_ERROR_KEY));
                }
                throw UserCancelException.CANCEL_GENERIC;
            }
            postProcessPDEDataViewer = new PDEDataViewer();
            parentDataJobListenerHolder.addDataJobListener(postProcessPDEDataViewer);
            PDEDataViewerPostProcess.this.postProcessPDEDataViewer.setPostProcessingPanelVisible(false);
            PDEDataViewerPostProcess.this.add(PDEDataViewerPostProcess.this.postProcessPDEDataViewer, BorderLayout.CENTER);
            postProcessPDEDataViewer.setDataViewerManager(getDataViewerManager());
            postProcessPDEDataViewer.setSimulationModelInfo(getSimulationModelInfo());
            postProcessPDEDataViewer.setSimulation(getSimulation());
        }
    };
    allTasks.addAll(Arrays.asList(PDEDataViewerPostProcess.this.getUpdateTasks()));
    // AsynchClientTask refreshTask = new AsynchClientTask("refreshPostProcess",AsynchClientTask.TASKTYPE_NONSWING_BLOCKING) {
    // @Override
    // public void run(Hashtable<String, Object> hashTable) throws Exception {
    // ((ArrayList<AsynchClientTask>)hashTable.get(ClientTaskDispatcher.INTERMEDIATE_TASKS)).addAll(Arrays.asList(PDEDataViewerPostProcess.this.postProcessPDEDataViewer.getRefreshTasks()));
    // }
    // };
    // allTasks.add(refreshTask);
    allTasks.add(0, addPanelTask);
    allTasks.add(0, postProcessInfoTask);
    ClientTaskDispatcher.dispatch(this, new Hashtable<>(), allTasks.toArray(new AsynchClientTask[0]), false, false, false, null, true);
}
Also used : AsynchClientTask(cbit.vcell.client.task.AsynchClientTask) Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) JLabel(javax.swing.JLabel) DataProcessingOutputInfoOP(cbit.vcell.simdata.DataOperation.DataProcessingOutputInfoOP) SimulationStatus(cbit.vcell.server.SimulationStatus) DataProcessingOutputInfo(cbit.vcell.simdata.DataOperationResults.DataProcessingOutputInfo)

Aggregations

AsynchClientTask (cbit.vcell.client.task.AsynchClientTask)229 Hashtable (java.util.Hashtable)219 ArrayList (java.util.ArrayList)68 UserCancelException (org.vcell.util.UserCancelException)52 File (java.io.File)35 CSGObject (cbit.vcell.geometry.CSGObject)30 Point (java.awt.Point)23 DataAccessException (org.vcell.util.DataAccessException)22 SimulationContext (cbit.vcell.mapping.SimulationContext)21 FRAPStudy (cbit.vcell.microscopy.FRAPStudy)18 PropertyVetoException (java.beans.PropertyVetoException)18 ImageException (cbit.image.ImageException)17 IOException (java.io.IOException)17 GeometryThumbnailImageFactoryAWT (cbit.vcell.geometry.GeometryThumbnailImageFactoryAWT)14 Vector (java.util.Vector)14 DataFormatException (java.util.zip.DataFormatException)14 UtilCancelException (org.vcell.util.UtilCancelException)14 Geometry (cbit.vcell.geometry.Geometry)12 ActionEvent (java.awt.event.ActionEvent)12 BioModel (cbit.vcell.biomodel.BioModel)11