def enter_thread(self):
     J.attach()
     if not cpprefs.get_awt_headless():
         J.activate_awt()
     self.notify_socket = the_zmq_context.socket(zmq.SUB)
     self.notify_socket.setsockopt(zmq.SUBSCRIBE, "")
     self.notify_socket.connect(NOTIFY_ADDR)
示例#2
0
 def enter_thread(self):
     J.attach()
     if not cpprefs.get_awt_headless():
         J.activate_awt()
     self.notify_socket = the_zmq_context.socket(zmq.SUB)
     self.notify_socket.setsockopt(zmq.SUBSCRIBE, "")
     self.notify_socket.connect(NOTIFY_ADDR)
    def OnInit(self):
        # The wx.StandardPaths aren't available until this is set.
        from cellprofiler.utilities.version import dotted_version
        self.SetAppName('CellProfiler%s' % dotted_version)
        
        wx.InitAllImageHandlers()

        if self.show_splashbox:
            # If the splash image has alpha, it shows up transparently on
            # windows, so we blend it into a white background.
            splashbitmap = wx.EmptyBitmapRGBA(
                CellProfilerSplash.GetWidth(), 
                CellProfilerSplash.GetHeight(), 255, 255, 255, 255)
            dc = wx.MemoryDC()
            dc.SelectObject(splashbitmap)
            dc.DrawBitmap(wx.BitmapFromImage(CellProfilerSplash), 0, 0)
            dc.SelectObject(wx.NullBitmap)
            dc.Destroy() # necessary to avoid a crash in splashscreen
            self.splash = wx.SplashScreen(
                splashbitmap, 
                wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT, 
                2000, None, -1)
            self.splash_timer = wx.Timer()
            self.splash_timer.Bind(wx.EVT_TIMER, self.destroy_splash_screen)
            self.splash_timer.Start(milliseconds = 2000, oneShot=True)
        else:
            self.splash = None

        if self.check_for_new_version:
            self.new_version_check()

        from javabridge import activate_awt
        activate_awt()
        from cellprofiler.gui.cpframe import CPFrame
        self.frame = CPFrame(None, -1, "Cell Profiler")
        self.destroy_splash_screen()
        try:
            self.frame.start(self.workspace_path, self.pipeline_path)
        except:
            return 0
        if self.abort_initialization:
            return 0

        # set up error dialog for uncaught exceptions
        def show_errordialog(type, exc, tb):
            def doit():
                cpp.cancel_progress()
                display_error_dialog(self.frame, exc, None, tb=tb, continue_only=True,
                                     message="Exception in CellProfiler core processing")
                # continue is really the only choice
            wx.CallAfter(doit)
        # replace default hook with error dialog
        self.orig_excepthook = sys.excepthook
        sys.excepthook = show_errordialog
        self.SetTopWindow(self.frame)
        self.frame.Show()
        if self.frame.startup_blurb_frame.IsShownOnScreen():
            self.frame.startup_blurb_frame.Raise()
        return 1
    def OnInit(self):
        """Initialize CPA
        """

        """List of tables created by the user during this session"""
        self.user_tables = []

        # splashscreen
        splashimage = cpa.icons.cpa_splash.ConvertToBitmap()
        # If the splash image has alpha, it shows up transparently on
        # windows, so we blend it into a white background.
        splashbitmap = wx.EmptyBitmapRGBA(splashimage.GetWidth(), splashimage.GetHeight(), 255, 255, 255, 255)
        dc = wx.MemoryDC()
        dc.SelectObject(splashbitmap)
        dc.DrawBitmap(splashimage, 0, 0)
        dc.Destroy()  # necessary to avoid a crash in splashscreen
        splash = wx.SplashScreen(splashbitmap, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 2000, None, -1)
        self.splash = splash

        p = Properties.getInstance()
        if not p.is_initialized():
            from cpa.guiutils import show_load_dialog

            splash.Destroy()
            if not show_load_dialog():
                logging.error("CellProfiler Analyst requires a properties file. Exiting.")
                return False
        self.frame = MainGUI(p, None, size=(860, -1))
        self.frame.Show(True)
        db = cpa.dbconnect.DBConnect.getInstance()
        # Black magic: Bus errors occur on Mac OS X if we wait until
        # the JVM or the wx event look has started to connect. But it
        # has to be done after we have read the properties file. So we
        # do it here.
        db.connect()
        db.register_gui_parent(self.frame)

        # The JVM has to be started after db.connect(), otherwise bus errors
        # occur on Mac OS X.
        javabridge.start_vm(class_path=bioformats.JARS, run_headless=False)
        javabridge.attach()
        javabridge.activate_awt()

        try:
            if __version__ != -1:
                import cellprofiler.utilities.check_for_updates as cfu

                cfu.check_for_updates(
                    "http://cellprofiler.org/CPAupdate.html",
                    max(__version__, cpaprefs.get_skip_version()),
                    new_version_cb,
                    user_agent="CPAnalyst/2.0.%d" % (__version__),
                )
        except ImportError:
            logging.warn(
                "CPA was unable to check for updates. Could not import cellprofiler.utilities.check_for_updates."
            )

        return True
示例#5
0
    def begin(self):
        import javabridge

        javabridge.start_vm(self.extra_jvm_args,
                            class_path=self.class_path.split(os.pathsep),
                            run_headless=self.headless,
                            max_heap_size=self.max_heap_size)
        if not self.headless:
            javabridge.activate_awt()
示例#6
0
    def begin(self):
        import javabridge

        javabridge.start_vm(self.extra_jvm_args,
                            class_path=self.class_path.split(os.pathsep),
                            run_headless=self.headless,
                            max_heap_size=self.max_heap_size)
        if not self.headless:
            javabridge.activate_awt()
    def get(self):
        total = dm.get_total_object_count()
        objKeys = dm.GetRandomObjects(total)

        # Start the virtual machine
        javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
        javabridge.attach()
        javabridge.activate_awt()

        return calculateAllJSON(objKeys, base64=True)
    def get(self):
        if cached_json["base64"] == False:
            # Start the virtual machine
            javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
            javabridge.attach()
            javabridge.activate_awt()

            # Calculate the Training DataSet and store it
            cached_json["json"] = calculateTrainingSetJSON(base64=True)
            cached_json["base64"] = True

        return cached_json["json"]
    def OnInit(self):
        '''Initialize CPA
        '''
        '''List of tables created by the user during this session'''
        self.user_tables = []

        # splashscreen
        splashimage = cpa.icons.cpa_splash.ConvertToBitmap()
        # If the splash image has alpha, it shows up transparently on
        # windows, so we blend it into a white background.
        splashbitmap = wx.EmptyBitmapRGBA(splashimage.GetWidth(),
                                          splashimage.GetHeight(), 255, 255,
                                          255, 255)
        dc = wx.MemoryDC()
        dc.SelectObject(splashbitmap)
        dc.DrawBitmap(splashimage, 0, 0)
        dc.Destroy()  # necessary to avoid a crash in splashscreen
        splash = wx.SplashScreen(
            splashbitmap, wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT, 2000,
            None, -1)
        self.splash = splash

        p = Properties.getInstance()
        if not p.is_initialized():
            from cpa.guiutils import show_load_dialog
            splash.Destroy()
            if not show_load_dialog():
                logging.error(
                    'CellProfiler Analyst requires a properties file. Exiting.'
                )
                return False
        self.frame = MainGUI(p, None, size=(860, -1))
        self.frame.Show(True)
        db = cpa.dbconnect.DBConnect.getInstance()
        # Black magic: Bus errors occur on Mac OS X if we wait until
        # the JVM or the wx event look has started to connect. But it
        # has to be done after we have read the properties file. So we
        # do it here.
        db.connect()
        db.register_gui_parent(self.frame)

        # The JVM has to be started after db.connect(), otherwise bus errors
        # occur on Mac OS X.
        javabridge.start_vm(class_path=bioformats.JARS, run_headless=False)
        javabridge.attach()
        javabridge.activate_awt()

        try:
            if __version__ != -1:
                import cellprofiler.utilities.check_for_updates as cfu
                cfu.check_for_updates('http://cellprofiler.org/CPAupdate.html',
                                      max(__version__,
                                          cpaprefs.get_skip_version()),
                                      new_version_cb,
                                      user_agent='CPAnalyst/2.0.%d' %
                                      (__version__))
        except ImportError:
            logging.warn(
                "CPA was unable to check for updates. Could not import cellprofiler.utilities.check_for_updates."
            )

        return True
示例#10
0
def run_pipeline_headless(options, args):
    '''Run a CellProfiler pipeline in headless mode'''
    
    if sys.platform == 'darwin':
        if options.start_awt:
            import bioformats
            from javabridge import activate_awt
            activate_awt()
        
    if not options.first_image_set is None:
        if not options.first_image_set.isdigit():
            raise ValueError("The --first-image-set option takes a numeric argument")
        else:
            image_set_start = int(options.first_image_set)
    else:
        image_set_start = None
    
    image_set_numbers = None
    if not options.last_image_set is None:
        if not options.last_image_set.isdigit():
            raise ValueError("The --last-image-set option takes a numeric argument")
        else:
            image_set_end = int(options.last_image_set)
            if image_set_start is None:
                image_set_numbers = np.arange(1, image_set_end+1)
            else:
                image_set_numbers = np.arange(image_set_start, image_set_end+1)
    else:
        image_set_end = None
    
    if ((options.pipeline_filename is not None) and 
        (not options.pipeline_filename.lower().startswith('http'))):
        options.pipeline_filename = os.path.expanduser(options.pipeline_filename)
    from cellprofiler.pipeline import Pipeline, EXIT_STATUS, M_PIPELINE
    import cellprofiler.measurements as cpmeas
    pipeline = Pipeline()
    initial_measurements = None
    try:
        if h5py.is_hdf5(options.pipeline_filename):
            initial_measurements = cpmeas.load_measurements(
                options.pipeline_filename,
                image_numbers=image_set_numbers)
    except:
        logging.root.info("Failed to load measurements from pipeline")
    if initial_measurements is not None:
        pipeline_text = \
            initial_measurements.get_experiment_measurement(
                M_PIPELINE)
        pipeline_text = pipeline_text.encode('us-ascii')
        pipeline.load(StringIO(pipeline_text))
        if not pipeline.in_batch_mode():
            #
            # Need file list in order to call prepare_run
            #
            from cellprofiler.utilities.hdf5_dict import HDF5FileList
            with h5py.File(options.pipeline_filename, "r") as src:
                if HDF5FileList.has_file_list(src):
                    HDF5FileList.copy(
                        src, initial_measurements.hdf5_dict.hdf5_file)
    else:
        pipeline.load(options.pipeline_filename)
    if options.groups is not None:
        kvs = [x.split('=') for x in options.groups.split(',')]
        groups = dict(kvs)
    else:
        groups = None
    use_hdf5 = len(args) > 0 and not args[0].lower().endswith(".mat")
    measurements = pipeline.run(
        image_set_start=image_set_start, 
        image_set_end=image_set_end,
        grouping=groups,
        measurements_filename = None if not use_hdf5 else args[0],
        initial_measurements = initial_measurements)
    if len(args) > 0 and not use_hdf5:
        pipeline.save_measurements(args[0], measurements)
    if options.done_file is not None:
        if (measurements is not None and 
            measurements.has_feature(cpmeas.EXPERIMENT, EXIT_STATUS)):
            done_text = measurements.get_experiment_measurement(EXIT_STATUS)
        else:
            done_text = "Failure"
        fd = open(options.done_file, "wt")
        fd.write("%s\n"%done_text)
        fd.close()
    if measurements is not None:
        measurements.close()
示例#11
0
def main(args):
    javabridge.activate_awt()
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            importClass(java.util.concurrent.SynchronousQueue);
            
            d = new Hashtable();
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //------------------------------------------------
            //
            // qUp sends messages from Java to Python
            // qDown sends messages from Python to Java
            //
            // The communications protocol is that qUp sends
            // a command. For Exec and Eval commands, qUp sends
            // text and qDown must send a reply to continue.
            // For the Exit command, qUp sends the command and
            // Python must dispose of Java
            //
            //-------------------------------------------------
            
            qUp = new SynchronousQueue();
            qDown = new SynchronousQueue();
            d.put("qUp", qUp);
            d.put("qDown", qDown);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Exec");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Eval");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    qUp.put("Exit");
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script)
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f)
    d = javabridge.get_map_wrapper(d)
    qUp = d["qUp"]
    qDown = d["qDown"]
    frame = d["frame"]
    while True:
        cmd = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Exit":
            break
        text = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Eval":
            try:
                result = eval(text, globals(), locals())
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
        else:
            try:
                exec(text, globals(), locals())
                result = "Operation succeeded"
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"

        javabridge.run_script("qDown.put(result);",
                              dict(qDown=qDown, result=str(result)))
    javabridge.run_script("frame.dispose();", dict(frame=frame))
示例#12
0
def run_ui():
    figure = plt.figure()
    ax = figure.add_axes([.05, .05, .9, .9])
    x = np.linspace(0, np.pi * 8)
    ax.plot(x, np.sin(x))
    canvas = figure.canvas
    frame = canvas.component.getTopLevelAncestor()
    toolbar = plt.get_current_fig_manager().frame.toolbar
    toolbar.add_button(lambda event: popup_script_dlg(canvas), "hand")
    plt.show()
    return frame, canvas, toolbar


javabridge.start_vm()
javabridge.activate_awt()
event = threading.Event()
event_ref_id, event_ref = javabridge.create_jref(event)
cpython = javabridge.JClassWrapper('org.cellprofiler.javabridge.CPython')()
set_event_script = ('import javabridge\n'
                    'event = javabridge.redeem_jref("%s")\n'
                    'event.set()') % event_ref_id
adapter = javabridge.run_script(
    """
new java.awt.event.WindowAdapter() {
    windowClosed: function(e) {
        cpython.exec(script);
    }
}
""", dict(cpython=cpython, script=set_event_script))
frame, canvas, toolbar = run_ui()
def main(args):
    javabridge.activate_awt()
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            importClass(java.util.concurrent.SynchronousQueue);
            
            d = new Hashtable();
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //------------------------------------------------
            //
            // qUp sends messages from Java to Python
            // qDown sends messages from Python to Java
            //
            // The communications protocol is that qUp sends
            // a command. For Exec and Eval commands, qUp sends
            // text and qDown must send a reply to continue.
            // For the Exit command, qUp sends the command and
            // Python must dispose of Java
            //
            //-------------------------------------------------
            
            qUp = new SynchronousQueue();
            qDown = new SynchronousQueue();
            d.put("qUp", qUp);
            d.put("qDown", qDown);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Exec");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    qUp.put("Eval");
                    qUp.put(textField.getText());
                    result.setText(qDown.take());
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    qUp.put("Exit");
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script);
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f);
    d = javabridge.get_map_wrapper(d)
    qUp = d["qUp"]
    qDown = d["qDown"]
    frame = d["frame"]
    while True:
        cmd = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Exit":
            break
        text = javabridge.run_script("qUp.take();", dict(qUp=qUp))
        if cmd == "Eval":
            try:
                result = eval(text, globals(), locals())
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
        else:
            try:
                exec(text, globals(), locals())
                result = "Operation succeeded"
            except Exception as e:
                result = "%s\n%s" % (str(e), traceback.format_exc())
            except:
                result = "What happened?"
            
        javabridge.run_script("qDown.put(result);", 
                              dict(qDown=qDown, result = str(result)))
    javabridge.run_script("frame.dispose();", dict(frame=frame))
    def OnInit(self):
        javabridge.activate_awt()

        return True
示例#15
0
def main(args):
    javabridge.activate_awt()
    cpython = javabridge.make_instance(
        "org/cellprofiler/javabridge/CPython", "()V")
    script = """
    //--------------------------------------
    //
    // The anonymous callable runs on the thread
    // that started Java - that's the rule with AWT.
    //
    // The callable returns a Java Map whose keys
    // have the labels of objects like "qUp" for
    // the upward queue. Python can then fetch
    // whichever ones it wants and do Java stuff
    // with them.
    //
    //--------------------------------------
    new java.util.concurrent.Callable() {
        call: function() {
            importClass(javax.swing.SpringLayout);
            importClass(javax.swing.JFrame);
            importClass(javax.swing.JTextField);
            importClass(javax.swing.JButton);
            importClass(javax.swing.JScrollPane);
            importClass(javax.swing.JTextArea);
            importClass(java.util.Hashtable);
            importClass(java.util.ArrayList);
            importClass(java.util.concurrent.CountDownLatch);
            importClass(java.awt.event.ActionListener);
            importClass(java.awt.event.WindowAdapter);
            
            d = new Hashtable();
            signal = new CountDownLatch(1);
            d.put("signal", signal);
            frame = new JFrame("Callbacks in Java");
            d.put("frame", frame);
            contentPane = frame.getContentPane();
            layout = new SpringLayout();
            contentPane.setLayout(layout);
            
            textField = new JTextField("'Hello, world.'", 60);
            d.put("textField", textField);
            contentPane.add(textField);
            
            execButton = new JButton("Exec");
            contentPane.add(execButton);
            
            evalButton = new JButton("Eval");
            contentPane.add(evalButton);
            
            result = new JTextArea("None");
            scrollPane = new JScrollPane(result)
            contentPane.add(scrollPane);
            d.put("result", result);
            
            //-----------------------------------------------------
            //
            // The layout is:
            //
            // [ textField] [execButton] [evalButton]
            // [    scrollPane                      ]
            //
            //-----------------------------------------------------

            layout.putConstraint(SpringLayout.WEST, textField,
                                 5, SpringLayout.WEST, contentPane);
            layout.putConstraint(SpringLayout.NORTH, textField,
                                 5, SpringLayout.NORTH, contentPane);

            layout.putConstraint(SpringLayout.WEST, execButton,
                                 5, SpringLayout.EAST, textField);
            layout.putConstraint(SpringLayout.NORTH, execButton,
                                 0, SpringLayout.NORTH, textField);
                                 
            layout.putConstraint(SpringLayout.WEST, evalButton,
                                 5, SpringLayout.EAST, execButton);
            layout.putConstraint(SpringLayout.NORTH, evalButton,
                                 0, SpringLayout.NORTH, textField);

            layout.putConstraint(SpringLayout.NORTH, scrollPane,
                                 5, SpringLayout.SOUTH, textField);
            layout.putConstraint(SpringLayout.WEST, scrollPane,
                                 0, SpringLayout.WEST, textField);
            layout.putConstraint(SpringLayout.EAST, scrollPane,
                                 0, SpringLayout.EAST, evalButton);
                                 
            layout.putConstraint(SpringLayout.EAST, contentPane,
                                 5, SpringLayout.EAST, evalButton);
            layout.putConstraint(SpringLayout.SOUTH, contentPane,
                                 20, SpringLayout.SOUTH, scrollPane);
            
            //-----------------------------------------------
            //
            // Create an action listener that binds the execButton
            // action to a function that instructs Python to
            // execute the contents of the text field.
            //
            //-----------------------------------------------
            alExec = new ActionListener() {
                actionPerformed: function(e) {
                    try {
                        cpython.exec(textField.getText());
                        result.setText("OK");
                    } catch(err) {
                        result.setText(err.message);
                    }
                }
            };
            execButton.addActionListener(alExec);

            //-----------------------------------------------
            //
            // Create an action listener that binds the evalButton
            // action to a function that instructs Python to
            // evaluate the contents of the text field.
            //
            //-----------------------------------------------
            alEval = new ActionListener() {
                actionPerformed: function(e) {
                    try {
                        locals = new Hashtable();
                        jresult = new ArrayList();
                        locals.put("script", textField.getText());
                        locals.put("jresult", jresult);
                        script = "import javabridge\\n" +
                                 "result=eval(javabridge.to_string(script))\\n" +
                                 "jwresult=javabridge.JWrapper(jresult)\\n" +
                                 "jwresult.add(str(result))"
                        cpython.exec(script, locals, null);
                        result.setText(jresult.get(0));
                    } catch(err) {
                        result.setText(err.message);
                    }
                }
            };
            evalButton.addActionListener(alEval);
            
            //-----------------------------------------------
            //
            // Create a window listener that binds the frame's
            // windowClosing action to a function that instructs 
            // Python to exit.
            //
            //-----------------------------------------------
            wl = new WindowAdapter() {
                windowClosing: function(e) {
                    signal.countDown();
                }
            };
            
            frame.addWindowListener(wl);

            frame.pack();
            frame.setVisible(true);
            return d;
        }
    };"""
    c = javabridge.run_script(script, dict(cpython=cpython));
    f = javabridge.make_future_task(c)
    d = javabridge.execute_future_in_main_thread(f);
    d = javabridge.get_map_wrapper(d)
    frame = javabridge.JWrapper(d["frame"])
    signal = javabridge.JWrapper(d["signal"]);
    signal.await();
    frame.dispose();
示例#16
0
    def OnInit(self):
        # The wx.StandardPaths aren't available until this is set.
        from cellprofiler.utilities.version import dotted_version
        self.SetAppName('CellProfiler%s' % dotted_version)

        wx.InitAllImageHandlers()

        if self.show_splashbox:
            # If the splash image has alpha, it shows up transparently on
            # windows, so we blend it into a white background.
            splashbitmap = wx.EmptyBitmapRGBA(CellProfilerSplash.GetWidth(),
                                              CellProfilerSplash.GetHeight(),
                                              255, 255, 255, 255)
            dc = wx.MemoryDC()
            dc.SelectObject(splashbitmap)
            dc.DrawBitmap(wx.BitmapFromImage(CellProfilerSplash), 0, 0)
            dc.SelectObject(wx.NullBitmap)
            dc.Destroy()  # necessary to avoid a crash in splashscreen
            self.splash = wx.SplashScreen(
                splashbitmap,
                wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_NO_TIMEOUT, 2000, None,
                -1)
            self.splash_timer = wx.Timer()
            self.splash_timer.Bind(wx.EVT_TIMER, self.destroy_splash_screen)
            self.splash_timer.Start(milliseconds=2000, oneShot=True)
        else:
            self.splash = None

        if self.check_for_new_version:
            self.new_version_check()

        from javabridge import activate_awt
        activate_awt()
        from cellprofiler.gui.cpframe import CPFrame
        self.frame = CPFrame(None, -1, "Cell Profiler")
        self.destroy_splash_screen()
        try:
            self.frame.start(self.workspace_path, self.pipeline_path)
        except:
            return 0
        if self.abort_initialization:
            return 0

        # set up error dialog for uncaught exceptions
        def show_errordialog(type, exc, tb):
            def doit():
                cpp.cancel_progress()
                display_error_dialog(
                    self.frame,
                    exc,
                    None,
                    tb=tb,
                    continue_only=True,
                    message="Exception in CellProfiler core processing")
                # continue is really the only choice

            wx.CallAfter(doit)

        # replace default hook with error dialog
        self.orig_excepthook = sys.excepthook
        sys.excepthook = show_errordialog
        self.SetTopWindow(self.frame)
        self.frame.Show()
        if self.frame.startup_blurb_frame.IsShownOnScreen():
            self.frame.startup_blurb_frame.Raise()
        return 1
示例#17
0
def run_pipeline_headless(options, args):
    '''Run a CellProfiler pipeline in headless mode'''
    #
    # Start Ilastik's workers
    #
    try:
        from ilastik.core.jobMachine import GLOBAL_WM
        GLOBAL_WM.set_thread_count(1)
    except:
        logging.root.warn("Failed to stop Ilastik")
    
    if sys.platform == 'darwin':
        if options.start_awt:
            import bioformats
            from javabridge import activate_awt
            activate_awt()
        
    if not options.first_image_set is None:
        if not options.first_image_set.isdigit():
            raise ValueError("The --first-image-set option takes a numeric argument")
        else:
            image_set_start = int(options.first_image_set)
    else:
        image_set_start = None
    
    image_set_numbers = None
    if not options.last_image_set is None:
        if not options.last_image_set.isdigit():
            raise ValueError("The --last-image-set option takes a numeric argument")
        else:
            image_set_end = int(options.last_image_set)
            if image_set_start is None:
                image_set_numbers = np.arange(1, image_set_end+1)
            else:
                image_set_numbers = np.arange(image_set_start, image_set_end+1)
    else:
        image_set_end = None
    
    if ((options.pipeline_filename is not None) and 
        (not options.pipeline_filename.lower().startswith('http'))):
        options.pipeline_filename = os.path.expanduser(options.pipeline_filename)
    from cellprofiler.pipeline import Pipeline, EXIT_STATUS, M_PIPELINE
    import cellprofiler.measurements as cpmeas
    import cellprofiler.preferences as cpprefs
    pipeline = Pipeline()
    initial_measurements = None
    try:
        if h5py.is_hdf5(options.pipeline_filename):
            initial_measurements = cpmeas.load_measurements(
                options.pipeline_filename,
                image_numbers=image_set_numbers)
    except:
        logging.root.info("Failed to load measurements from pipeline")
    if initial_measurements is not None:
        pipeline_text = \
            initial_measurements.get_experiment_measurement(
                M_PIPELINE)
        pipeline_text = pipeline_text.encode('us-ascii')
        pipeline.load(StringIO(pipeline_text))
        if not pipeline.in_batch_mode():
            #
            # Need file list in order to call prepare_run
            #
            from cellprofiler.utilities.hdf5_dict import HDF5FileList
            with h5py.File(options.pipeline_filename, "r") as src:
                if HDF5FileList.has_file_list(src):
                    HDF5FileList.copy(
                        src, initial_measurements.hdf5_dict.hdf5_file)
    else:
        pipeline.load(options.pipeline_filename)
    if options.groups is not None:
        kvs = [x.split('=') for x in options.groups.split(',')]
        groups = dict(kvs)
    else:
        groups = None
    file_list = cpprefs.get_image_set_file()
    if file_list is not None:
        pipeline.read_file_list(file_list)
    #
    # Fixup CreateBatchFiles with any command-line input or output directories
    #
    if pipeline.in_batch_mode():
        create_batch_files = [
            m for m in pipeline.modules()
            if m.is_create_batch_module()]
        if len(create_batch_files) > 0:
            create_batch_files = create_batch_files[0]
            if options.output_directory is not None:
                create_batch_files.custom_output_directory.value = \
                    options.output_directory
            if options.image_directory is not None:
                create_batch_files.default_image_directory.value = \
                    options.image_directory
        
    use_hdf5 = len(args) > 0 and not args[0].lower().endswith(".mat")
    measurements = pipeline.run(
        image_set_start=image_set_start, 
        image_set_end=image_set_end,
        grouping=groups,
        measurements_filename = None if not use_hdf5 else args[0],
        initial_measurements = initial_measurements)
    if len(args) > 0 and not use_hdf5:
        pipeline.save_measurements(args[0], measurements)
    if options.done_file is not None:
        if (measurements is not None and 
            measurements.has_feature(cpmeas.EXPERIMENT, EXIT_STATUS)):
            done_text = measurements.get_experiment_measurement(EXIT_STATUS)
        else:
            done_text = "Failure"
        fd = open(options.done_file, "wt")
        fd.write("%s\n"%done_text)
        fd.close()
    if measurements is not None:
        measurements.close()
@app.route("/start", methods=["GET"])
def init():
    start()
    return "starting CPA"


##
## Actually setup the Api resource routing here
##
api.add_resource(helloworld, "/")
# api.add_resource(TrainingSet, '/')
api.add_resource(getImagePaths, "/images")
api.add_resource(getBase64, "/base64")
api.add_resource(getAll, "/all")


# Server Main Function
if __name__ == "__main__":

    # app.debug = True
    # app.run(host='0.0.0.0', port=5000) #Public IP

    start()
    # Start the virtual machine
    javabridge.start_vm(class_path=bioformats.JARS, run_headless=True)
    javabridge.attach()
    javabridge.activate_awt()

    # Calculate the Training DataSet and store it
    calculateTrainingSetJSON(base64=True)
示例#19
0
def run_pipeline_headless(options, args):
    '''Run a CellProfiler pipeline in headless mode'''

    if sys.platform == 'darwin':
        if options.start_awt:
            from javabridge import activate_awt
            activate_awt()

    if not options.first_image_set is None:
        if not options.first_image_set.isdigit():
            raise ValueError(
                "The --first-image-set option takes a numeric argument")
        else:
            image_set_start = int(options.first_image_set)
    else:
        image_set_start = None

    image_set_numbers = None
    if not options.last_image_set is None:
        if not options.last_image_set.isdigit():
            raise ValueError(
                "The --last-image-set option takes a numeric argument")
        else:
            image_set_end = int(options.last_image_set)
            if image_set_start is None:
                image_set_numbers = np.arange(1, image_set_end + 1)
            else:
                image_set_numbers = np.arange(image_set_start,
                                              image_set_end + 1)
    else:
        image_set_end = None

    if ((options.pipeline_filename is not None)
            and (not options.pipeline_filename.lower().startswith('http'))):
        options.pipeline_filename = os.path.expanduser(
            options.pipeline_filename)
    from cellprofiler.pipeline import Pipeline, EXIT_STATUS, M_PIPELINE
    import cellprofiler.measurement as cpmeas
    import cellprofiler.preferences as cpprefs
    pipeline = Pipeline()
    initial_measurements = None
    try:
        if h5py.is_hdf5(options.pipeline_filename):
            initial_measurements = cpmeas.load_measurements(
                options.pipeline_filename, image_numbers=image_set_numbers)
    except:
        logging.root.info("Failed to load measurements from pipeline")
    if initial_measurements is not None:
        pipeline_text = \
            initial_measurements.get_experiment_measurement(
                    M_PIPELINE)
        pipeline_text = pipeline_text.encode('us-ascii')
        pipeline.load(StringIO(pipeline_text))
        if not pipeline.in_batch_mode():
            #
            # Need file list in order to call prepare_run
            #
            from cellprofiler.utilities.hdf5_dict import HDF5FileList
            with h5py.File(options.pipeline_filename, "r") as src:
                if HDF5FileList.has_file_list(src):
                    HDF5FileList.copy(src,
                                      initial_measurements.hdf5_dict.hdf5_file)
    else:
        pipeline.load(options.pipeline_filename)
    if options.groups is not None:
        kvs = [x.split('=') for x in options.groups.split(',')]
        groups = dict(kvs)
    else:
        groups = None
    file_list = cpprefs.get_image_set_file()
    if file_list is not None:
        pipeline.read_file_list(file_list)
    #
    # Fixup CreateBatchFiles with any command-line input or output directories
    #
    if pipeline.in_batch_mode():
        create_batch_files = [
            m for m in pipeline.modules() if m.is_create_batch_module()
        ]
        if len(create_batch_files) > 0:
            create_batch_files = create_batch_files[0]
            if options.output_directory is not None:
                create_batch_files.custom_output_directory.value = \
                    options.output_directory
            if options.image_directory is not None:
                create_batch_files.default_image_directory.value = \
                    options.image_directory

    use_hdf5 = len(args) > 0 and not args[0].lower().endswith(".mat")
    measurements = pipeline.run(
        image_set_start=image_set_start,
        image_set_end=image_set_end,
        grouping=groups,
        measurements_filename=None if not use_hdf5 else args[0],
        initial_measurements=initial_measurements)
    if len(args) > 0 and not use_hdf5:
        pipeline.save_measurements(args[0], measurements)
    if options.done_file is not None:
        if (measurements is not None
                and measurements.has_feature(cpmeas.EXPERIMENT, EXIT_STATUS)):
            done_text = measurements.get_experiment_measurement(EXIT_STATUS)

            exit_code = (0 if done_text == "Complete" else -1)
        else:
            done_text = "Failure"

            exit_code = -1

        fd = open(options.done_file, "wt")
        fd.write("%s\n" % done_text)
        fd.close()
    if measurements is not None:
        measurements.close()

    return exit_code
示例#20
0
    def OnInit(self):
        javabridge.activate_awt()

        return True