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. self.SetAppName('CellProfiler2.0') 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() import bioformats from cellprofiler.utilities.jutil import activate_awt activate_awt() from cellprofiler.gui.cpframe import CPFrame self.frame = CPFrame(None, -1, "Cell Profiler") self.destroy_splash_screen() self.frame.start(self.workspace_path, self.pipeline_path) 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 begin(self): if self.enabled: # # Implement workaround from # http://code.google.com/p/python-nose/issues/detail?id=326 # # Prevents setup.py from being considered as a test suite # try: from nose.suite import ContextSuite ContextSuite.moduleSetup = tuple( filter(lambda x: x != "setup", ContextSuite.moduleSetup)) except: pass # # Start PySimpleApp for unit tests # import unittest import bioformats try: import wx wx.GetApp() has_wx = True except unittest.SkipTest: has_wx = False if has_wx: from cellprofiler.utilities.jutil \ import activate_awt activate_awt() self.app = wx.GetApp() if self.app is None: class KVMApp(wx.PySimpleApp): def __init__(self): super(self.__class__, self).__init__(False) def OnExit(self): from cellprofiler.utilities.jutil \ import deactivate_awt deactivate_awt() self.app = KVMApp() # # At least one H5PY build has had debug mode on # import h5py import logging logging.getLogger("h5py").setLevel(logging.WARNING)
def begin(self): if self.enabled: # # Implement workaround from # http://code.google.com/p/python-nose/issues/detail?id=326 # # Prevents setup.py from being considered as a test suite # try: from nose.suite import ContextSuite ContextSuite.moduleSetup = tuple(filter( lambda x: x != "setup", ContextSuite.moduleSetup)) except: pass # # Start PySimpleApp for unit tests # import unittest import bioformats try: import wx wx.GetApp() has_wx = True except unittest.SkipTest: has_wx = False if has_wx: from cellprofiler.utilities.jutil \ import activate_awt activate_awt() self.app = wx.GetApp() if self.app is None: class KVMApp(wx.PySimpleApp): def __init__(self): super(self.__class__, self).__init__(False) def OnExit(self): from cellprofiler.utilities.jutil \ import deactivate_awt deactivate_awt() self.app = KVMApp() # # At least one H5PY build has had debug mode on # import h5py import logging logging.getLogger("h5py").setLevel(logging.WARNING)
def create_settings(self): '''Create the settings for the module''' logger.debug("Creating RunImageJ module settings") J.activate_awt() logger.debug("Activated AWT") self.command_or_macro = cps.Choice( "Run an ImageJ command or macro?", [CM_COMMAND, CM_MACRO],doc = """ This setting determines whether <b>RunImageJ</b> runs either a: <ul> <li><i>%(CM_COMMAND)s:</i> Select from a list of available ImageJ commands (those items contained in the ImageJ menus); or</li> <li><i>%(CM_MACRO)s:</i> A series of ImageJ commands/plugins that you write yourself.</li> </ul>"""%globals()) # # Load the commands in visible_settings so that we don't call # ImageJ unless someone tries the module # self.command = self.make_command_choice( "Command",doc = """ <i>(Used only if running a %(CM_COMMAND)s)</i><br> The command to execute when the module runs."""%globals()) self.command_settings_dictionary = {} self.command_settings = [] self.command_settings_count = cps.HiddenCount( self.command_settings, "Command settings count") self.pre_command_settings_dictionary = {} self.pre_command_settings = [] self.pre_command_settings_count = cps.HiddenCount( self.pre_command_settings, "Prepare group command settings count") self.post_command_settings_dictionary = {} self.post_command_settings = [] self.post_command_settings_count = cps.HiddenCount( self.post_command_settings, "Post-group command settings count") self.macro = cps.Text( "Macro", """import imagej.command.CommandService; cmdSvcClass = CommandService.class; cmdSvc = ImageJ.getService(cmdSvcClass); cmdSvc.run("imagej.core.commands.assign.InvertDataValues", new Object [] {"allPlanes", true}).get();""", multiline = True,doc=""" <i>(Used only if running a %(CM_MACRO)s)</i><br> This is the ImageJ macro to be executed. The syntax for ImageJ macros depends on the scripting language engine chosen. We suggest that you use the Beanshell scripting language <a href="http://www.beanshell.org/manual/contents.html"> (Beanshell documentation)</a>."""%globals()) all_engines = ij2.get_script_service(get_context()).getLanguages() self.language_dictionary = dict( [(engine.getLanguageName(), engine) for engine in all_engines]) self.macro_language = cps.Choice( "Macro language", choices = self.language_dictionary.keys(),doc = """ This setting chooses the scripting language used to execute any macros in this module""") self.wants_to_set_current_image = cps.Binary( "Input the currently active image in ImageJ?", True,doc=""" Check this setting if you want to set the currently active ImageJ image using an image from a prior CellProfiler module. <p>Leave it unchecked to use the currently active image in ImageJ. You may want to do this if you have an output image from a prior <b>RunImageJ</b> that you want to perform further operations upon before retrieving the final result back to CellProfiler.</p>""") self.current_input_image_name = cps.ImageNameSubscriber( "Select the input image",doc=""" <i>(Used only if setting the currently active image)</i><br> This is the CellProfiler image that will become ImageJ's currently active image. The ImageJ commands and macros in this module will perform their operations on this image. You may choose any image produced by a prior CellProfiler module.""") self.wants_to_get_current_image = cps.Binary( "Retrieve the currently active image from ImageJ?", True,doc=""" Check this setting if you want to retrieve ImageJ's currently active image after running the command or macro. <p>Leave the setting unchecked if the pipeline does not need to access the current ImageJ image. For example, you might want to run further ImageJ operations with additional <b>RunImageJ</b> upon the current image prior to retrieving the final image back to CellProfiler.</p>""") self.current_output_image_name = cps.ImageNameProvider( "Name the current output image", "ImageJImage",doc=""" <i>(Used only if retrieving the currently active image from ImageJ)</i><br> This is the CellProfiler name for ImageJ's current image after processing by the command or macro. The image will be a snapshot of the current image after the command has run, and will be available for processing by subsequent CellProfiler modules.""") self.pause_before_proceeding = cps.Binary( "Wait for ImageJ before continuing?", False,doc = """ Some ImageJ commands and macros are interactive; you may want to adjust the image in ImageJ before continuing. Check this box to stop CellProfiler while you adjust the image in ImageJ. Leave the box unchecked to immediately use the image. <p>This command will not wait if CellProfiler is executed in batch mode. See <i>%(BATCH_PROCESSING_HELP_REF)s</i> for more details on batch processing.</p>"""%globals()) self.prepare_group_choice = cps.Choice( "Function to run before each group of images?", [CM_NOTHING, CM_COMMAND, CM_MACRO],doc=""" You can run an ImageJ macro or a command <i>before</i> each group of images. This can be useful in order to set up ImageJ before processing a stack of images. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run or <i>%(CM_MACRO)s</i> to run a macro. """ % globals()) logger.debug("Finding ImageJ commands") self.prepare_group_command = self.make_command_choice( "Command", doc = """ <i>(Used only if running a command before an image group)</i><br> Select the command to execute before processing a group of images.""") self.prepare_group_macro = cps.Text( "Macro", 'run("Invert");', multiline = True,doc=""" <i>(Used only if running a macro before an image group)</i><br> This is the ImageJ macro to be executed before processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""") self.post_group_choice = cps.Choice( "Function to run after each group of images?", [CM_NOTHING, CM_COMMAND, CM_MACRO],doc=""" You can run an ImageJ macro or a command <i>after</i> each group of images. This can be used to do some sort of operation on a whole stack of images that have been accumulated by the group operation. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run or <i>%(CM_MACRO)s</i> to run a macro. """ % globals()) self.post_group_command = self.make_command_choice( "Command", doc = """ <i>(Used only if running a command after an image group)</i><br> The command to execute after processing a group of images.""") self.post_group_macro = cps.Text( "Macro", 'run("Invert");', multiline = True,doc=""" <i>(Used only if running a macro after an image group)</i><br> This is the ImageJ macro to be executed after processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""") self.wants_post_group_image = cps.Binary( "Retrieve the image output by the group operation?", False,doc=""" You can retrieve the image that is currently active in ImageJ at the end of macro processing and use it later in CellProfiler. The image will only be available during the last cycle of the image group. Check this setting to use the active image in CellProfiler or leave it unchecked if you do not want to use the active image. """) self.post_group_output_image = cps.ImageNameProvider( "Name the group output image", "ImageJGroupImage",doc=""" <i>(Used only if retrieving an image after an image group operation)</i><br> This setting names the output image produced by the ImageJ command or macro that CellProfiler runs after processing all images in the group. The image is only available at the last cycle in the group""", provided_attributes={cps.AGGREGATE_IMAGE_ATTRIBUTE: True, cps.AVAILABLE_ON_LAST_ATTRIBUTE: True } ) self.show_imagej_button = cps.DoSomething( "Show ImageJ", "Show", self.on_show_imagej,doc=""" Press this button to show the ImageJ user interface. You can use the user interface to run ImageJ commands or set up ImageJ before a CellProfiler run.""") logger.debug("Finished creating settings")
def start_cellprofiler_jvm(): '''Start the Java VM with arguments appropriate for CellProfiler''' global logger if hasattr(sys, 'frozen'): if sys.platform != 'darwin': root_path = os.path.split(os.path.abspath(sys.argv[0]))[0] bioformats_path = os.path.join(root_path, 'bioformats') else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] imagej_path = os.path.join(root_path, 'imagej','jars') def sort_fn(a, b): aa,bb = [(0 if x.startswith("cellprofiler-java") else 1, x) for x in a, b] return cmp(aa, bb) jar_files = [ jar_filename for jar_filename in os.listdir(imagej_path) if jar_filename.lower().endswith(".jar")] jar_files = sorted(jar_files, cmp = sort_fn) else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] jar_files = get_cellprofiler_jars() imagej_path = os.path.join(root_path, 'imagej','jars') class_path = os.pathsep.join( [os.path.join(imagej_path, jar_file) for jar_file in jar_files]) if os.environ.has_key("CLASSPATH"): class_path += os.pathsep + os.environ["CLASSPATH"] plugin_directory = get_ij_plugin_directory() logger.debug("Using %s as imagej plugin directory" % plugin_directory) if (plugin_directory is not None and os.path.isdir(plugin_directory)): # # Add the plugin directory to pick up .class files in a directory # hierarchy. # class_path += os.pathsep + plugin_directory logger.debug("Adding %s to class path" % plugin_directory) # # Add any .jar files in the directory # for jarfile in os.listdir(plugin_directory): jarpath = os.path.join(plugin_directory, jarfile) if jarfile.lower().endswith(".jar"): logger.debug("Adding %s to class path" % jarpath) class_path += os.pathsep + jarpath else: logger.debug("Skipping %s" % jarpath) else: logger.info("Plugin directory doesn't point to valid folder: " + plugin_directory) if sys.platform.startswith("win") and not hasattr(sys, 'frozen'): # Have to find tools.jar from cellprofiler.utilities.setup import find_jdk jdk_path = find_jdk() if jdk_path is not None: tools_jar = os.path.join(jdk_path, "lib","tools.jar") class_path += os.pathsep + tools_jar else: logger.warning("Failed to find tools.jar") jvm_arg = [x.groups()[0] for x in [ re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv] if x is not None] if len(jvm_arg) > 0: jvm_arg = jvm_arg[0] else: jvm_arg = "512m" args = [r"-Djava.class.path="+class_path, r"-Dloci.bioformats.loaded=true", #r"-verbose:class", #r"-verbose:jni", r"-Xmx%s" % jvm_arg] # # Get the log4j logger setup from a file in the bioformats directory # if such a file exists. # log4j_properties = os.path.join(bioformats_path, "log4j.properties") if os.path.exists(log4j_properties): log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/") args += [r"-Dlog4j.configuration="+log4j_properties] init_logger = False else: init_logger = True if get_headless(): # We're running silently, so don't change the Java preferences # The following definition uses a process-scope preferences factory args += [ "-Djava.util.prefs.PreferencesFactory=" "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"] run_headless = (get_headless() and not os.environ.has_key("CELLPROFILER_USE_XVFB")) run_headless = False logger.debug("JVM arguments: " + " ".join(args)) jutil.start_vm(args, run_headless) logger.debug("Java virtual machine started.") jutil.attach() try: jutil.static_call("loci/common/Location", "cacheDirectoryListings", "(Z)V", True) except: logger.warning("Bioformats version does not support directory cacheing") # # Start the log4j logger to avoid error messages. # if init_logger: try: jutil.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = jutil.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN", "Lorg/apache/log4j/Level;") jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level) del logger del warn_level except: logger.error("Failed to initialize log4j\n", exc_info=True) if not get_headless(): jutil.activate_awt()
def start_cellprofiler_jvm(): '''Start the Java VM with arguments appropriate for CellProfiler''' global logger if hasattr(sys, 'frozen'): if sys.platform != 'darwin': root_path = os.path.split(os.path.abspath(sys.argv[0]))[0] bioformats_path = os.path.join(root_path, 'bioformats') else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] imagej_path = os.path.join(root_path, 'imagej', 'jars') def sort_fn(a, b): aa, bb = [(0 if x.startswith("cellprofiler-java") else 1, x) for x in a, b] return cmp(aa, bb) jar_files = [ jar_filename for jar_filename in os.listdir(imagej_path) if jar_filename.lower().endswith(".jar") ] jar_files = sorted(jar_files, cmp=sort_fn) else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] jar_files = get_cellprofiler_jars() imagej_path = os.path.join(root_path, 'imagej', 'jars') class_path = os.pathsep.join( [os.path.join(imagej_path, jar_file) for jar_file in jar_files]) if os.environ.has_key("CLASSPATH"): class_path += os.pathsep + os.environ["CLASSPATH"] if (get_ij_plugin_directory() is not None and os.path.isdir(get_ij_plugin_directory())): plugin_directory = get_ij_plugin_directory() # # Add the plugin directory to pick up .class files in a directory # hierarchy. # class_path += os.pathsep + plugin_directory # # Add any .jar files in the directory # class_path += os.pathsep + os.pathsep.join([ os.path.join(plugin_directory, jarfile) for jarfile in os.listdir(plugin_directory) if jarfile.lower().endswith(".jar") ]) if sys.platform.startswith("win") and not hasattr(sys, 'frozen'): # Have to find tools.jar from cellprofiler.utilities.setup import find_jdk jdk_path = find_jdk() if jdk_path is not None: tools_jar = os.path.join(jdk_path, "lib", "tools.jar") class_path += os.pathsep + tools_jar else: logger.warning("Failed to find tools.jar") jvm_arg = [ x.groups()[0] for x in [re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv] if x is not None ] if len(jvm_arg) > 0: jvm_arg = jvm_arg[0] else: jvm_arg = "512m" args = [ r"-Djava.class.path=" + class_path, r"-Dloci.bioformats.loaded=true", #r"-verbose:class", #r"-verbose:jni", r"-Xmx%s" % jvm_arg ] # # Get the log4j logger setup from a file in the bioformats directory # if such a file exists. # log4j_properties = os.path.join(bioformats_path, "log4j.properties") if os.path.exists(log4j_properties): log4j_properties = "file:/" + log4j_properties.replace( os.path.sep, "/") args += [r"-Dlog4j.configuration=" + log4j_properties] init_logger = False else: init_logger = True if get_headless(): # We're running silently, so don't change the Java preferences # The following definition uses a process-scope preferences factory args += [ "-Djava.util.prefs.PreferencesFactory=" "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory" ] run_headless = (get_headless() and not os.environ.has_key("CELLPROFILER_USE_XVFB")) run_headless = False logger.debug("JVM arguments: " + " ".join(args)) jutil.start_vm(args, run_headless) logger.debug("Java virtual machine started.") jutil.attach() try: jutil.static_call("loci/common/Location", "cacheDirectoryListings", "(Z)V", True) except: logger.warning( "Bioformats version does not support directory cacheing") # # Start the log4j logger to avoid error messages. # if init_logger: try: jutil.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = jutil.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = jutil.get_static_field("org/apache/log4j/Level", "WARN", "Lorg/apache/log4j/Level;") jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level) del logger del warn_level except: logger.error("Failed to initialize log4j\n", exc_info=True) if not get_headless(): jutil.activate_awt()
def run_pipeline_headless(options, args): '''Run a CellProfiler pipeline in headless mode''' if sys.platform == 'darwin': if options.start_awt: import bioformats from cellprofiler.utilities.jutil 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()
def start_cellprofiler_jvm(): '''Start the Java VM with arguments appropriate for CellProfiler''' global logger if hasattr(sys, 'frozen'): if sys.platform != 'darwin': root_path = os.path.split(os.path.abspath(sys.argv[0]))[0] bioformats_path = os.path.join(root_path, 'bioformats') else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] imagej_path = os.path.join(root_path, 'imagej','jars') def sort_fn(a, b): aa,bb = [(0 if x.startswith("cellprofiler-java") else 1, x) for x in a, b] return cmp(aa, bb) jar_files = [ jar_filename for jar_filename in os.listdir(imagej_path) if jar_filename.lower().endswith(".jar")] jar_files = sorted(jar_files, cmp = sort_fn) else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] jar_files = get_cellprofiler_jars() imagej_path = os.path.join(root_path, 'imagej','jars') class_path = os.pathsep.join( [os.path.join(imagej_path, jar_file) for jar_file in jar_files]) if os.environ.has_key("CLASSPATH"): class_path += os.pathsep + os.environ["CLASSPATH"] plugin_directory = get_ij_plugin_directory() logger.debug("Using %s as imagej plugin directory" % plugin_directory) if (plugin_directory is not None and os.path.isdir(plugin_directory)): # # Add the plugin directory to pick up .class files in a directory # hierarchy. # class_path += os.pathsep + plugin_directory logger.debug("Adding %s to class path" % plugin_directory) # # Add any .jar files in the directory # for jarfile in os.listdir(plugin_directory): jarpath = os.path.join(plugin_directory, jarfile) if jarfile.lower().endswith(".jar"): logger.debug("Adding %s to class path" % jarpath) class_path += os.pathsep + jarpath else: logger.debug("Skipping %s" % jarpath) else: logger.info("Plugin directory doesn't point to valid folder: " + plugin_directory) if sys.platform.startswith("win") and not hasattr(sys, 'frozen'): # Have to find tools.jar from cellprofiler.utilities.setup import find_jdk jdk_path = find_jdk() if jdk_path is not None: tools_jar = os.path.join(jdk_path, "lib","tools.jar") class_path += os.pathsep + tools_jar else: logger.warning("Failed to find tools.jar") jvm_arg = jutil.get_jvm_heap_size_arg() if jvm_arg is None: jvm_arg = "512m" args = [r"-Djava.class.path="+class_path, r"-Dloci.bioformats.loaded=true", #r"-verbose:class", #r"-verbose:jni", r"-Xmx%s" % jvm_arg] # # Get the log4j logger setup from a file in the bioformats directory # if such a file exists. # log4j_properties = os.path.join(bioformats_path, "log4j.properties") if os.path.exists(log4j_properties): log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/") args += [r"-Dlog4j.configuration="+log4j_properties] init_logger = False else: init_logger = True if plugin_directory is not None and os.path.isdir(plugin_directory): # For IJ1 compatibility args += [r"-Dplugins.dir=%s" % plugin_directory] # In headless mode, we have to avoid changing the Java preferences. # # Aside from that, we need to prevent ImageJ from exiting and from # displaying the updater dialog - at least temporarily, we do that # through preferences. We use the HeadlessPreferencesFactory to # limit the scope of the changes to this process - otherwise we'd # turn off updating for the machine. # # TODO: ImageJ is implementing a pluggable mechanism to control the # quit process. We can also contribute a pluggable mechanism # that gives us more control over the updater. # args += [ "-Djava.util.prefs.PreferencesFactory=" "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory"] run_headless = (get_headless() and not os.environ.has_key("CELLPROFILER_USE_XVFB")) run_headless = False logger.debug("JVM arguments: " + " ".join(args)) jutil.start_vm(args, run_headless) logger.debug("Java virtual machine started.") jutil.attach() try: jutil.static_call("loci/common/Location", "cacheDirectoryListings", "(Z)V", True) except: logger.warning("Bioformats version does not support directory cacheing") # # Start the log4j logger to avoid error messages. # if init_logger: try: jutil.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = jutil.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN", "Lorg/apache/log4j/Level;") jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level) del logger del warn_level except: logger.error("Failed to initialize log4j\n", exc_info=True) if not get_headless(): jutil.activate_awt()
def start_cellprofiler_jvm(): '''Start the Java VM with arguments appropriate for CellProfiler''' global logger if hasattr(sys, 'frozen'): if sys.platform != 'darwin': root_path = os.path.split(os.path.abspath(sys.argv[0]))[0] bioformats_path = os.path.join(root_path, 'bioformats') else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] imagej_path = os.path.join(root_path, 'imagej', 'jars') def sort_fn(a, b): aa, bb = [(0 if x.startswith("cellprofiler-java") else 1, x) for x in a, b] return cmp(aa, bb) jar_files = [ jar_filename for jar_filename in os.listdir(imagej_path) if jar_filename.lower().endswith(".jar") ] jar_files = sorted(jar_files, cmp=sort_fn) else: bioformats_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(bioformats_path)[0] jar_files = get_cellprofiler_jars() imagej_path = os.path.join(root_path, 'imagej', 'jars') class_path = os.pathsep.join( [os.path.join(imagej_path, jar_file) for jar_file in jar_files]) if os.environ.has_key("CLASSPATH"): class_path += os.pathsep + os.environ["CLASSPATH"] plugin_directory = get_ij_plugin_directory() logger.debug("Using %s as imagej plugin directory" % plugin_directory) if (plugin_directory is not None and os.path.isdir(plugin_directory)): # # Add the plugin directory to pick up .class files in a directory # hierarchy. # class_path += os.pathsep + plugin_directory logger.debug("Adding %s to class path" % plugin_directory) # # Add any .jar files in the directory # for jarfile in os.listdir(plugin_directory): jarpath = os.path.join(plugin_directory, jarfile) if jarfile.lower().endswith(".jar"): logger.debug("Adding %s to class path" % jarpath) class_path += os.pathsep + jarpath else: logger.debug("Skipping %s" % jarpath) else: logger.info("Plugin directory doesn't point to valid folder: " + plugin_directory) if sys.platform.startswith("win") and not hasattr(sys, 'frozen'): # Have to find tools.jar from cellprofiler.utilities.setup import find_jdk jdk_path = find_jdk() if jdk_path is not None: tools_jar = os.path.join(jdk_path, "lib", "tools.jar") class_path += os.pathsep + tools_jar else: logger.warning("Failed to find tools.jar") jvm_arg = jutil.get_jvm_heap_size_arg() if jvm_arg is None: jvm_arg = "512m" args = [ r"-Djava.class.path=" + class_path, r"-Dloci.bioformats.loaded=true", #r"-verbose:class", #r"-verbose:jni", r"-Xmx%s" % jvm_arg ] # # Get the log4j logger setup from a file in the bioformats directory # if such a file exists. # log4j_properties = os.path.join(bioformats_path, "log4j.properties") if os.path.exists(log4j_properties): log4j_properties = "file:/" + log4j_properties.replace( os.path.sep, "/") args += [r"-Dlog4j.configuration=" + log4j_properties] init_logger = False else: init_logger = True if plugin_directory is not None and os.path.isdir(plugin_directory): # For IJ1 compatibility args += [r"-Dplugins.dir=%s" % plugin_directory] # In headless mode, we have to avoid changing the Java preferences. # # Aside from that, we need to prevent ImageJ from exiting and from # displaying the updater dialog - at least temporarily, we do that # through preferences. We use the HeadlessPreferencesFactory to # limit the scope of the changes to this process - otherwise we'd # turn off updating for the machine. # # TODO: ImageJ is implementing a pluggable mechanism to control the # quit process. We can also contribute a pluggable mechanism # that gives us more control over the updater. # args += [ "-Djava.util.prefs.PreferencesFactory=" "org.cellprofiler.headlesspreferences.HeadlessPreferencesFactory" ] run_headless = (get_headless() and not os.environ.has_key("CELLPROFILER_USE_XVFB")) run_headless = False logger.debug("JVM arguments: " + " ".join(args)) jutil.start_vm(args, run_headless) logger.debug("Java virtual machine started.") jutil.attach() try: jutil.static_call("loci/common/Location", "cacheDirectoryListings", "(Z)V", True) except: logger.warning( "Bioformats version does not support directory cacheing") # # Start the log4j logger to avoid error messages. # if init_logger: try: jutil.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = jutil.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = jutil.get_static_field("org/apache/log4j/Level", "WARN", "Lorg/apache/log4j/Level;") jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level) del logger del warn_level except: logger.error("Failed to initialize log4j\n", exc_info=True) if not get_headless(): jutil.activate_awt()
def create_settings(self): '''Create the settings for the module''' logger.debug("Creating RunImageJ module settings") J.activate_awt() logger.debug("Activated AWT") self.command_or_macro = cps.Choice("Run an ImageJ command or macro?", [CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" This setting determines whether <b>RunImageJ</b> runs either a: <ul> <li><i>%(CM_COMMAND)s:</i> Select from a list of available ImageJ commands (those items contained in the ImageJ menus); or</li> <li><i>%(CM_SCRIPT)s:</i> A script written in one of ImageJ 2.0's supported scripting languages.</li> <li><i>%(CM_MACRO)s:</i> An ImageJ 1.x macro, written in the ImageJ 1.x macro language. <b>Run_ImageJ</b> runs ImageJ in 1.x compatability mode.</li> </ul>""" % globals()) # # Load the commands in visible_settings so that we don't call # ImageJ unless someone tries the module # self.command = self.make_command_choice("Command", doc=""" <i>(Used only if running a %(CM_COMMAND)s)</i><br> The command to execute when the module runs.""" % globals()) self.command_settings_dictionary = {} self.command_settings = [] self.command_settings_count = cps.HiddenCount( self.command_settings, "Command settings count") self.pre_command_settings_dictionary = {} self.pre_command_settings = [] self.pre_command_settings_count = cps.HiddenCount( self.pre_command_settings, "Prepare group command settings count") self.post_command_settings_dictionary = {} self.post_command_settings = [] self.post_command_settings_count = cps.HiddenCount( self.post_command_settings, "Post-group command settings count") self.macro = cps.Text("Macro", """import imagej.command.CommandService; cmdSvcClass = CommandService.class; cmdSvc = ImageJ.getService(cmdSvcClass); cmdSvc.run("imagej.core.commands.assign.InvertDataValues", new Object [] {"allPlanes", true}).get();""", multiline=True, doc=""" <i>(Used only if running a %(CM_MACRO)s)</i><br> This is the ImageJ macro to be executed. The syntax for ImageJ macros depends on the scripting language engine chosen. We suggest that you use the Beanshell scripting language <a href="http://www.beanshell.org/manual/contents.html"> (Beanshell documentation)</a>.""" % globals()) all_engines = ij2.get_script_service(get_context()).getLanguages() self.language_dictionary = dict([(engine.getLanguageName(), engine) for engine in all_engines]) self.macro_language = cps.Choice( "Macro language", choices=self.language_dictionary.keys(), doc=""" This setting chooses the scripting language used to execute any macros in this module""") self.wants_to_set_current_image = cps.Binary( "Input the currently active image in ImageJ?", True, doc=""" Select <i>%(YES)s</i> if you want to set the currently active ImageJ image using an image from a prior CellProfiler module. <p>Select <i>%(NO)s</i> to use the currently active image in ImageJ. You may want to do this if you have an output image from a prior <b>RunImageJ</b> that you want to perform further operations upon before retrieving the final result back to CellProfiler.</p>""" % globals()) self.current_input_image_name = cps.ImageNameSubscriber( "Select the input image", doc=""" <i>(Used only if setting the currently active image)</i><br> This is the CellProfiler image that will become ImageJ's currently active image. The ImageJ commands and macros in this module will perform their operations on this image. You may choose any image produced by a prior CellProfiler module.""") self.wants_to_get_current_image = cps.Binary( "Retrieve the currently active image from ImageJ?", True, doc=""" Select <i>%(YES)s</i> if you want to retrieve ImageJ's currently active image after running the command or macro. <p>Select <i>%(NO)s</i> if the pipeline does not need to access the current ImageJ image. For example, you might want to run further ImageJ operations with additional <b>RunImageJ</b> upon the current image prior to retrieving the final image back to CellProfiler.</p>""" % globals()) self.current_output_image_name = cps.ImageNameProvider( "Name the current output image", "ImageJImage", doc=""" <i>(Used only if retrieving the currently active image from ImageJ)</i><br> This is the CellProfiler name for ImageJ's current image after processing by the command or macro. The image will be a snapshot of the current image after the command has run, and will be available for processing by subsequent CellProfiler modules.""" ) self.pause_before_proceeding = cps.Binary( "Wait for ImageJ before continuing?", False, doc=""" Some ImageJ commands and macros are interactive; you may want to adjust the image in ImageJ before continuing. Select <i>%(YES)s</i> to stop CellProfiler while you adjust the image in ImageJ. Select <i>%(NO)s</i> to immediately use the image. <p>This command will not wait if CellProfiler is executed in batch mode. See <i>%(BATCH_PROCESSING_HELP_REF)s</i> for more details on batch processing.</p>""" % globals()) self.prepare_group_choice = cps.Choice( "Function to run before each group of images?", [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" You can run an ImageJ 2.0 script, an ImageJ 1.x macro or a command <i>before</i> each group of images. This can be useful in order to set up ImageJ before processing a stack of images. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x macro in ImageJ 1.x compatibility mode. """ % globals()) logger.debug("Finding ImageJ commands") self.prepare_group_command = self.make_command_choice("Command", doc=""" <i>(Used only if running a command before an image group)</i><br> Select the command to execute before processing a group of images.""" ) self.prepare_group_macro = cps.Text("Macro", 'run("Invert");', multiline=True, doc=""" <i>(Used only if running a macro before an image group)</i><br> This is the ImageJ macro to be executed before processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""" ) self.post_group_choice = cps.Choice( "Function to run after each group of images?", [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO], doc=""" You can run an ImageJ 2.0 script, an ImageJ macro or a command <i>after</i> each group of images. This can be used to do some sort of operation on a whole stack of images that have been accumulated by the group operation. Choose <i>%(CM_NOTHING)s</i> if you do not want to run a command or macro, <i>%(CM_COMMAND)s</i> to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x macro in ImageJ 1.x compatibility mode. """ % globals()) self.post_group_command = self.make_command_choice("Command", doc=""" <i>(Used only if running a command after an image group)</i><br> The command to execute after processing a group of images.""") self.post_group_macro = cps.Text("Macro", 'run("Invert");', multiline=True, doc=""" <i>(Used only if running a macro after an image group)</i><br> This is the ImageJ macro to be executed after processing a group of images. For help on writing macros, see <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>.""" ) self.wants_post_group_image = cps.Binary( "Retrieve the image output by the group operation?", False, doc=""" You can retrieve the image that is currently active in ImageJ at the end of macro processing and use it later in CellProfiler. The image will only be available during the last cycle of the image group. <p>Select <i>%(YES)s</i> to retrieve the active image for use in CellProfiler. Select <i>%(NO)s</i> if you do not want to retrieve the active image.</p> """ % globals()) self.post_group_output_image = cps.ImageNameProvider( "Name the group output image", "ImageJGroupImage", doc=""" <i>(Used only if retrieving an image after an image group operation)</i><br> This setting names the output image produced by the ImageJ command or macro that CellProfiler runs after processing all images in the group. The image is only available at the last cycle in the group""", provided_attributes={ cps.AGGREGATE_IMAGE_ATTRIBUTE: True, cps.AVAILABLE_ON_LAST_ATTRIBUTE: True }) self.show_imagej_button = cps.DoSomething("Show ImageJ", "Show", self.on_show_imagej, doc=""" Press this button to show the ImageJ user interface. You can use the user interface to run ImageJ commands or set up ImageJ before a CellProfiler run.""") logger.debug("Finished creating settings")
def start_cellprofiler_jvm(): '''Start the Java VM with arguments appropriate for CellProfiler''' global USE_IJ2 global logger if hasattr(sys, 'frozen') and sys.platform != 'darwin': root_path = os.path.split(os.path.abspath(sys.argv[0]))[0] else: root_path = os.path.abspath(os.path.split(__file__)[0]) root_path = os.path.split(root_path)[0] path = os.path.join(root_path, 'bioformats') imagej_path = os.path.join(root_path, 'imagej') loci_jar = os.path.join(path, "loci_tools.jar") ij2_jar = os.path.join(imagej_path, "imagej-2.0-SNAPSHOT-all.jar") ij_jar = os.path.join(imagej_path, "ij.jar") imglib_jar = os.path.join(imagej_path, "imglib.jar") javacl_jar = os.path.join(imagej_path, "javacl-1.0-beta-4-shaded.jar") USE_IJ2 = get_ij_version() == IJ_2 if os.path.exists(ij2_jar) and USE_IJ2: class_path = os.pathsep.join((loci_jar, ij2_jar)) USE_IJ2 = True else: USE_IJ2 = False class_path = os.pathsep.join((loci_jar, ij_jar, imglib_jar, javacl_jar)) if os.environ.has_key("CLASSPATH"): class_path += os.pathsep + os.environ["CLASSPATH"] if sys.platform.startswith("win") and not hasattr(sys, 'frozen'): # Have to find tools.jar from cellprofiler.utilities.setup import find_jdk jdk_path = find_jdk() if jdk_path is not None: tools_jar = os.path.join(jdk_path, "lib","tools.jar") class_path += os.pathsep + tools_jar else: logger.warning("Failed to find tools.jar") jvm_arg = [x.groups()[0] for x in [ re.match('--jvm-heap-size=([0-9]+[gGkKmM])', y) for y in sys.argv] if x is not None] if len(jvm_arg) > 0: jvm_arg = jvm_arg[0] else: jvm_arg = "512m" args = [r"-Djava.class.path="+class_path, r"-Dloci.bioformats.loaded=true", #r"-verbose:class", #r"-verbose:jni", r"-Xmx%s" % jvm_arg] if get_ij_plugin_directory() is not None: args.append("-Dplugins.dir="+get_ij_plugin_directory()) # # Get the log4j logger setup from a file in the bioformats directory # if such a file exists. # log4j_properties = os.path.join(path, "log4j.properties") if os.path.exists(log4j_properties): log4j_properties = "file:/"+log4j_properties.replace(os.path.sep, "/") args += [r"-Dlog4j.configuration="+log4j_properties] init_logger = False else: init_logger = True run_headless = (get_headless() and not os.environ.has_key("CELLPROFILER_USE_XVFB")) logger.debug("JVM arguments: " + " ".join(args)) jutil.start_vm(args, run_headless) logger.debug("Java virtual machine started.") jutil.attach() try: jutil.static_call("loci/common/Location", "cacheDirectoryListings", "(Z)V", True) except: logger.warning("Bioformats version does not support directory cacheing") # # Start the log4j logger to avoid error messages. # if init_logger: try: jutil.static_call("org/apache/log4j/BasicConfigurator", "configure", "()V") log4j_logger = jutil.static_call("org/apache/log4j/Logger", "getRootLogger", "()Lorg/apache/log4j/Logger;") warn_level = jutil.get_static_field("org/apache/log4j/Level","WARN", "Lorg/apache/log4j/Level;") jutil.call(log4j_logger, "setLevel", "(Lorg/apache/log4j/Level;)V", warn_level) del logger del warn_level except: logger.error("Failed to initialize log4j\n", exc_info=True) if not run_headless: jutil.activate_awt()
def OnInit(self): # The wx.StandardPaths aren't available until this is set. self.SetAppName('CellProfiler2.0') 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() import bioformats from cellprofiler.utilities.jutil import activate_awt activate_awt() from cellprofiler.gui.cpframe import CPFrame self.frame = CPFrame(None, -1, "Cell Profiler") self.destroy_splash_screen() self.frame.start(self.workspace_path, self.pipeline_path) 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