def analyze(conn, plate, pipeline):
    warnings.filterwarnings('ignore')
    print("analyzing...")
    # Set Cell Output Directory
    new_output_directory = os.path.normcase(tempfile.mkdtemp())
    cpprefs.set_default_output_directory(new_output_directory)

    wells = list(plate.listChildren())
    wells = wells[0:5]  # use the first 5 wells
    for count, well in enumerate(wells):
        # Load a single Image per Well
        image = well.getImage(0)
        print(image.getName())
        pixels = image.getPrimaryPixels()
        size_c = image.getSizeC()
        # For each Image in OMERO, we copy pipeline and inject image modules
        pipeline_copy = pipeline.copy()
        # Inject image for each Channel (pipeline only handles 2 channels)
        for c in range(0, size_c):
            plane = pixels.getPlane(0, c, 0)
            image_name = image.getName()
            # Name of the channel expected in the pipeline
            if c == 0:
                image_name = 'OrigBlue'
            if c == 1:
                image_name = 'OrigGreen'
            inject_image_module = InjectImage(image_name, plane)
            inject_image_module.set_module_num(1)
            pipeline_copy.add_module(inject_image_module)
        pipeline_copy.run()

        # Results obtained as CSV from Cell Profiler
        path = new_output_directory + '/Nuclei.csv'
        save_results(conn, path, image)
    print("analysis done")
Example #2
0
 def check_preferences(self):
     """Return True if preferences are OK (e.g., directories exist)"""
     path = self.__image_edit_box.GetValue()
     if not os.path.isdir(path):
         if (wx.MessageBox(
             ('The Default Input Folder is "%s", but '
              "the directory does not exist. Do you want to "
              "create it?") % path,
                 "Warning, cannot run pipeline",
                 style=wx.YES_NO,
         ) == wx.NO):
             return False, "Image directory does not exist"
         os.makedirs(path)
         set_default_image_directory(path)
     path = self.__output_edit_box.GetValue()
     if not os.path.isdir(path):
         if (wx.MessageBox(
             ('The Default Output Folder is "%s", but '
              "the directory does not exist. Do you want to "
              "create it?") % path,
                 "Warning, cannot run pipeline",
                 style=wx.YES_NO,
         ) == wx.NO):
             return False, "Output directory does not exist"
         os.makedirs(path)
         set_default_output_directory(path)
     return True, "OK"
 def enter_batch_mode(self, workspace):
     """Restore the image set list from its setting as we go into batch mode"""
     pipeline = workspace.pipeline
     assert isinstance(pipeline, cpp.Pipeline)
     assert not self.distributed_mode, "Distributed mode no longer supported"
     default_output_directory = self.custom_output_directory.value
     default_image_directory = self.default_image_directory.value
     if os.path.isdir(default_output_directory):
         cpprefs.set_default_output_directory(default_output_directory)
     else:
         logger.info(
             'Batch file default output directory, "%s", does not exist' %
             default_output_directory)
     if os.path.isdir(default_image_directory):
         cpprefs.set_default_image_directory(default_image_directory)
     else:
         logger.info(
             'Batch file default input directory "%s", does not exist' %
             default_image_directory)
def analyze(plate, pipeline):
    warnings.filterwarnings('ignore')
    print("analyzing...")
    # Set Cell Output Directory
    new_output_directory = os.path.normcase(tempfile.mkdtemp())
    cpprefs.set_default_output_directory(new_output_directory)

    files = list()
    wells = list(plate.listChildren())
    wells = wells[0:5]  # use the first 5 wells
    plate_id = plate.getId()
    for count, well in enumerate(wells):
        # Load a single Image per Well
        image = well.getImage(0)
        print(image.getName())
        data = load_dask_array_from_s3(plate_id, (well.row+1)*(well.column+1)-1)
        size_c = image.getSizeC()
        # For each Image in OMERO, we copy pipeline and inject image modules
        pipeline_copy = pipeline.copy()
        # Inject image for each Channel (pipeline only handles 2 channels)
        for c in range(0, size_c):
            plane = data[0, c, 0, :, :]
            image_name = image.getName()
            # Name of the channel expected in the pipeline
            if c == 0:
                image_name = 'OrigBlue'
            if c == 1:
                image_name = 'OrigGreen'
            inject_image_module = InjectImage(image_name, plane)
            inject_image_module.set_module_num(1)
            pipeline_copy.add_module(inject_image_module)
        pipeline_copy.run()

        # Results obtained as CSV from Cell Profiler
        path = new_output_directory + '/Nuclei.csv'
        files.append(path)
    print("analysis done")
    return files
Example #5
0
def main(args=None):
    """Run CellProfiler

    args - command-line arguments, e.g., sys.argv
    """
    if args is None:
        args = sys.argv

    set_awt_headless(True)

    exit_code = 0

    switches = ("--work-announce", "--knime-bridge-address")

    if any(
        [any([arg.startswith(switch) for switch in switches])
         for arg in args]):
        set_headless()
        aw_parse_args()
        main()
        return exit_code

    options, args = parse_args(args)

    if options.temp_dir is not None:
        if not os.path.exists(options.temp_dir):
            os.makedirs(options.temp_dir)
        set_temporary_directory(options.temp_dir, globally=False)

    temp_dir = get_temporary_directory()

    to_clean = []

    if options.pipeline_filename:
        o = urllib.parse.urlparse(options.pipeline_filename)
        if o[0] in ("ftp", "http", "https"):
            from urllib.request import urlopen

            temp_pipe_file = tempfile.NamedTemporaryFile(mode="w+b",
                                                         suffix=".cppipe",
                                                         dir=temp_dir,
                                                         delete=False)
            downloaded_pipeline = urlopen(options.pipeline_filename)
            for line in downloaded_pipeline:
                temp_pipe_file.write(line)
            options.pipeline_filename = temp_pipe_file.name
            to_clean.append(os.path.join(temp_dir, temp_pipe_file.name))

    if options.image_set_file:
        o = urllib.parse.urlparse(options.image_set_file)
        if o[0] in ("ftp", "http", "https"):
            from urllib.request import urlopen

            temp_set_file = tempfile.NamedTemporaryFile(mode="w+b",
                                                        suffix=".csv",
                                                        dir=temp_dir,
                                                        delete=False)
            downloaded_set_csv = urlopen(options.image_set_file)
            for line in downloaded_set_csv:
                temp_set_file.write(line)
            options.image_set_file = temp_set_file.name
            to_clean.append(os.path.join(temp_dir, temp_set_file.name))

    if options.data_file:
        o = urllib.parse.urlparse(options.data_file)
        if o[0] in ("ftp", "http", "https"):
            from urllib.request import urlopen

            temp_data_file = tempfile.NamedTemporaryFile(mode="w+b",
                                                         suffix=".csv",
                                                         dir=temp_dir,
                                                         delete=False)
            downloaded_data_csv = urlopen(options.data_file)
            for line in downloaded_data_csv:
                temp_data_file.write(line)
            options.data_file = temp_data_file.name
            to_clean.append(os.path.join(temp_dir, temp_data_file.name))

    if options.print_version:
        __version__(exit_code)

    if (not options.show_gui) or options.write_schema_and_exit:
        set_headless()

        options.run_pipeline = True

    if options.batch_commands_file:
        set_headless()
        options.run_pipeline = False
        options.show_gui = False

    set_log_level(options)

    if options.print_groups_file is not None:
        print_groups(options.print_groups_file)

    if options.batch_commands_file is not None:
        try:
            nr_per_batch = int(options.images_per_batch)
        except ValueError:
            logging.warning(
                "non-integer argument to --images-per-batch. Defaulting to 1.")
            nr_per_batch = 1
        get_batch_commands(options.batch_commands_file, nr_per_batch)

    if options.omero_credentials is not None:
        set_omero_credentials_from_string(options.omero_credentials)

    if options.plugins_directory is not None:
        set_plugin_directory(options.plugins_directory, globally=False)

    if not options.allow_schema_write:
        set_allow_schema_write(False)

    if options.output_directory:
        if not os.path.exists(options.output_directory):
            os.makedirs(options.output_directory)

        set_default_output_directory(options.output_directory)

    if options.image_directory:
        set_default_image_directory(options.image_directory)

    if options.run_pipeline and not options.pipeline_filename:
        raise ValueError("You must specify a pipeline filename to run")

    if options.data_file is not None:
        set_data_file(os.path.abspath(options.data_file))

    try:
        if not options.show_gui:
            start_java()

        if options.image_set_file is not None:
            set_image_set_file(options.image_set_file)

        #
        # Handle command-line tasks that that need to load the modules to run
        #
        if options.print_measurements:
            print_measurements(options)

        if options.write_schema_and_exit:
            write_schema(options.pipeline_filename)

        if options.show_gui:
            matplotlib.use("WXAgg")

            import cellprofiler.gui.app

            if options.pipeline_filename:
                if is_workspace_file(options.pipeline_filename):
                    workspace_path = os.path.expanduser(
                        options.pipeline_filename)

                    pipeline_path = None
                else:
                    pipeline_path = os.path.expanduser(
                        options.pipeline_filename)

                    workspace_path = None
            else:
                workspace_path = None

                pipeline_path = None

            app = cellprofiler.gui.app.App(0,
                                           workspace_path=workspace_path,
                                           pipeline_path=pipeline_path)

            if options.run_pipeline:
                app.frame.pipeline_controller.do_analyze_images()

            app.MainLoop()

            return
        elif options.run_pipeline:
            exit_code = run_pipeline_headless(options, args)

    finally:
        # Cleanup the temp files we made, if any
        if len(to_clean) > 0:
            for each_temp in to_clean:
                os.remove(each_temp)
        # If anything goes wrong during the startup sequence headlessly, the JVM needs
        # to be explicitly closed
        if not options.show_gui:
            stop_cellprofiler()

    return exit_code