How to use the cellprofiler.workspace.Workspace function in CellProfiler

To help you get started, we’ve selected a few CellProfiler examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github CellProfiler / CellProfiler / tests / modules / test_exporttospreadsheet.py View on Github external
m = cellprofiler.measurement.Measurements()
    numpy.random.seed(0)
    data = numpy.random.uniform(size=(6,))
    m.add_image_measurement("Count_my_objects", 6)
    m.add_image_measurement("first_measurement", numpy.sum(data))
    m.add_image_measurement("another_measurement", 43.2)
    m.add_measurement("my_objects", "Number_Object_Number", numpy.arange(1, 7))
    m.add_measurement("my_objects", "my_measurement", data)
    m.add_measurement(
        "my_objects", "my_filtered_measurement", numpy.random.uniform(size=(6,))
    )
    image_set_list = cellprofiler.image.ImageSetList()
    image_set = image_set_list.get_image_set(0)
    object_set = cellprofiler.object.ObjectSet()
    object_set.add_objects(cellprofiler.object.Objects(), "my_objects")
    workspace = cellprofiler.workspace.Workspace(
        make_measurements_pipeline(m), module, image_set, object_set, m, image_set_list
    )
    module.post_run(workspace)
    try:
        fd = open(image_path, "r")
        reader = csv.reader(fd, delimiter=module.delimiter_char)
        header = next(reader)
        assert len(header) == 4
        expected_image_columns = (
            "ImageNumber",
            "Count_my_objects",
            "first_measurement",
            "Mean_my_objects_my_measurement",
        )
        d = {}
        for index, caption in enumerate(header):
github CellProfiler / CellProfiler / tests / modules / test_loadimages.py View on Github external
module.images[0].common_text.value = filename
    module.images[0].channels[
        0
    ].image_object_choice.value = cellprofiler.modules.loadimages.IO_OBJECTS
    module.images[0].channels[0].object_name.value = OBJECTS_NAME
    module.images[0].channels[0].wants_outlines.value = True
    module.images[0].channels[0].outlines_name.value = OUTLINES_NAME
    module.location.dir_choice = cellprofiler.setting.ABSOLUTE_FOLDER_NAME
    module.location.custom_path = directory
    module.set_module_num(1)
    pipeline = cellprofiler.pipeline.Pipeline()
    pipeline.add_module(module)
    pipeline.add_listener(error_callback)
    image_set_list = cellprofiler.image.ImageSetList()
    m = cellprofiler.measurement.Measurements()
    workspace = cellprofiler.workspace.Workspace(
        pipeline, module, None, None, m, image_set_list
    )
    module.prepare_run(workspace)
    module.prepare_group(workspace, (), [0])
    workspace = cellprofiler.workspace.Workspace(
        pipeline,
        module,
        image_set_list.get_image_set(0),
        cellprofiler.object.ObjectSet(),
        m,
        image_set_list,
    )
    return workspace, module
github CellProfiler / CellProfiler / tests / modules / test_identifyprimaryobjects.py View on Github external
x.size_range.min = 40
        x.size_range.max = 60
        x.watershed_method.value = cellprofiler.modules.identifyprimaryobjects.WA_NONE
        x.threshold_scope.value = cellprofiler.modules.identify.TS_MANUAL
        x.manual_threshold.value = .3
        img = numpy.zeros((200, 200))
        draw_circle(img, (100, 100), 25, .5)
        draw_circle(img, (25, 25), 10, .5)
        image = cellprofiler.image.Image(img)
        image_set_list = cellprofiler.image.ImageSetList()
        image_set = image_set_list.get_image_set(0)
        image_set.providers.append(cellprofiler.image.VanillaImageProvider("my_image", image))
        object_set = cellprofiler.object.ObjectSet()
        measurements = cellprofiler.measurement.Measurements()
        pipeline = cellprofiler.pipeline.Pipeline()
        x.run(cellprofiler.workspace.Workspace(pipeline, x, image_set, object_set, measurements, None))
        objects = object_set.get_objects("my_object")
        self.assertEqual(objects.segmented[25, 25], 0, "The small object was not filtered out")
        self.assertEqual(objects.segmented[100, 100], 1, "The large object was not present")
        self.assertTrue(objects.small_removed_segmented[25, 25] == 0,
                        "The small object was in the small_removed label set")
        self.assertTrue(objects.small_removed_segmented[100, 100] > 0,
                        "The large object was not in the small-removed label set")
        self.assertTrue(objects.unedited_segmented[25, 25], "The small object was not in the unedited set")
        self.assertTrue(objects.unedited_segmented[100, 100], "The large object was not in the unedited set")
        location_center_x = measurements.get_current_measurement("my_object", "Location_Center_X")
        self.assertTrue(isinstance(location_center_x, numpy.ndarray))
        self.assertEqual(numpy.product(location_center_x.shape), 1)
github CellProfiler / CellProfiler / tests / modules / test_identifyyeastcells.py View on Github external
def test_01_00_test_zero_objects(self):
        x = YS.IdentifyYeastCells()
        x.object_name.value = OBJECTS_NAME
        x.segmentation_precision.value = 11
        x.input_image_name.value = IMAGE_NAME
        x.background_brighter_then_cell_inside.value = False
        x.average_cell_diameter.value = 5
        img = np.zeros((25, 25))
        image = cpi.Image(img, file_name="test_01_00_test_zero_objects")
        image_set_list = cpi.ImageSetList()
        image_set = image_set_list.get_image_set(0)
        image_set.providers.append(cpi.VanillaImageProvider(IMAGE_NAME, image))
        object_set = cpo.ObjectSet()
        measurements = cpmeas.Measurements()
        pipeline = cellprofiler.pipeline.Pipeline()
        x.run(Workspace(pipeline, x, image_set, object_set, measurements, None))
        self.assertEqual(len(object_set.object_names), 1)
        self.assertTrue(OBJECTS_NAME in object_set.object_names)
        objects = object_set.get_objects(OBJECTS_NAME)
        segmented = objects.segmented
        self.assertTrue(np.all(segmented == 0))
        self.assertTrue("Image" in measurements.get_object_names())
        self.assertTrue(OBJECTS_NAME in measurements.get_object_names())
        self.assertTrue("Count_" + OBJECTS_NAME in measurements.get_feature_names("Image"))
        count = measurements.get_current_measurement("Image", "Count_" + OBJECTS_NAME)
        self.assertEqual(count, 0)
        self.assertTrue("Location_Center_X" in measurements.get_feature_names(OBJECTS_NAME))
        location_center_x = measurements.get_current_measurement(OBJECTS_NAME, "Location_Center_X")
        self.assertTrue(isinstance(location_center_x, np.ndarray))
        self.assertEqual(np.product(location_center_x.shape), 0)
        self.assertTrue("Location_Center_Y" in measurements.get_feature_names(OBJECTS_NAME))
        location_center_y = measurements.get_current_measurement(OBJECTS_NAME, "Location_Center_Y")
github CellProfiler / CellProfiler / tests / modules / test_correctilluminationcalculate.py View on Github external
cellprofiler.modules.correctilluminationcalculate.FI_MANUALLY
    )
    module.size_of_smoothing_filter.value = 10
    module.rescale_option.value = cellprofiler.setting.YES
    module.dilate_objects.value = False
    measurements = cellprofiler.measurement.Measurements()
    image_set_list = cellprofiler.image.ImageSetList()
    workspace = cellprofiler.workspace.Workspace(
        pipeline, None, None, None, measurements, image_set_list
    )
    pipeline.prepare_run(workspace)
    inj_module.prepare_group(workspace, {}, [1])
    module.prepare_group(workspace, {}, [1])
    image_set = image_set_list.get_image_set(0)
    object_set = cellprofiler.object.ObjectSet()
    workspace = cellprofiler.workspace.Workspace(
        pipeline, inj_module, image_set, object_set, measurements, image_set_list
    )
    inj_module.run(workspace)
    module.run(workspace)
    image = image_set.get_image("OutputImage")
    assert numpy.all(image.pixel_data == expected_image)
github CellProfiler / CellProfiler / tests / modules / test_definegrid.py View on Github external
image_set = image_set_list.get_image_set(0)
    image_set.add(INPUT_IMAGE_NAME, cellprofiler.image.Image(image))
    object_set = cellprofiler.object.ObjectSet()
    objects = cellprofiler.object.Objects()
    objects.segmented = labels
    object_set.add_objects(objects, OBJECTS_NAME)
    pipeline = cellprofiler.pipeline.Pipeline()

    def callback(caller, event):
        assert not isinstance(event, cellprofiler.pipeline.LoadExceptionEvent)
        assert not isinstance(event, cellprofiler.pipeline.RunExceptionEvent)

    pipeline.add_listener(callback)
    pipeline.add_module(module)
    measurements = cellprofiler.measurement.Measurements()
    workspace = cellprofiler.workspace.Workspace(
        pipeline, module, image_set, object_set, measurements, image_set_list
    )
    return workspace, module
github CellProfiler / CellProfiler / tests / modules / test_exporttospreadsheet.py View on Github external
module.object_groups[0].wants_automatic_file_name.value = False
    m = cellprofiler.measurement.Measurements()
    numpy.random.seed(0)
    mvalues = numpy.random.uniform(size=(4,))
    image_set_list = cellprofiler.image.ImageSetList()
    for index, measurement, metadata in zip(
        list(range(4)), mvalues, ("foo", "bar", "bar", "foo")
    ):
        image_set = image_set_list.get_image_set(index)
        m.add_image_measurement("my_measurement", measurement)
        m.add_image_measurement("Metadata_tag", metadata)
        if index < 3:
            m.next_image_set()
    object_set = cellprofiler.object.ObjectSet()
    object_set.add_objects(cellprofiler.object.Objects(), "my_objects")
    workspace = cellprofiler.workspace.Workspace(
        make_measurements_pipeline(m), module, image_set, object_set, m, image_set_list
    )
    for i in range(4):
        module.post_run(workspace)
    for file_name, value_indexes in (("foo.csv", (0, 3)), ("bar.csv", (1, 2))):
        path = os.path.join(output_dir, file_name)
        fd = open(path, "r")
        try:
            reader = csv.reader(fd, delimiter=module.delimiter_char)
            header = next(reader)
            assert len(header) == 3
            d = {}
            assert "ImageNumber" in header
            assert "my_measurement" in header
            assert "Metadata_tag" in header
            for caption, index in zip(header, list(range(3))):
github CellProfiler / CellProfiler / cellprofiler / distributed.py View on Github external
self.output_file = output_file
        self.status_callback = status_callback

        # make sure createbatchfiles is not in the pipeline
        if 'CreateBatchFiles' in [module.module_name for module in pipeline.modules()]:
            # XXX - should offer to ignore?
            raise RuntimeError('CreateBatchFiles should not be used with distributed processing.')

        # duplicate pipeline
        pipeline = pipeline.copy()

        # create the image list
        image_set_list = cpi.ImageSetList()
        image_set_list.combine_path_and_file = True
        measurements = cpmeas.Measurements()
        workspace = cpw.Workspace(pipeline, None, None, None, measurements,
                                  image_set_list)
                                  
        if not pipeline.prepare_run(workspace):
            raise RuntimeError('Could not create image set list for distributed processing.')

        # start server, get base URL
        self.work_server = nuageux.Server('CellProfiler work server', data_callback=self.data_server, validate_result=self.validate_result)
        self.server_URL = self.work_server.base_URL()

        # call prepare_to_create_batch to turn files into URLs
        self.URL_map.clear()
        pipeline.prepare_to_create_batch(workspace, self.rewrite_to_URL)

        # add a CreateBatchFiles module at the end of the pipeline,
        # and set it up for saving the pipeline state
        module = pipeline.instantiate_module('CreateBatchFiles')
github CellProfiler / CellProfiler / cellprofiler / knime_bridge.py View on Github external
def run_request(self, session_id, message_type, message):
        """Handle the run request message"""
        pipeline, m, object_set = self.prepare_run(message, session_id)
        if pipeline is None:
            return
        m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.GROUP_NUMBER] = 1
        m[cellprofiler.measurement.IMAGE, cellprofiler.measurement.GROUP_INDEX] = 1
        input_modules, other_modules = self.split_pipeline(pipeline)
        for module in other_modules:
            workspace = cellprofiler.workspace.Workspace(
                pipeline, module, m, None, m, None
            )
            module.prepare_run(workspace)
        for module in other_modules:
            workspace = cellprofiler.workspace.Workspace(
                pipeline, module, m, object_set, m, None
            )
            try:
                logger.info(
                    "Running module # %d: %s" % (module.module_num, module.module_name)
                )
                pipeline.run_module(module, workspace)
                if workspace.disposition in (
                    cellprofiler.workspace.DISPOSITION_SKIP,
                    cellprofiler.workspace.DISPOSITION_CANCEL,
                ):
github CellProfiler / CellProfiler / cellprofiler / pipeline.py View on Github external
for module in self.modules():
                    gc.collect()
                    if module.should_stop_writing_measurements():
                        should_write_measurements = False
                    else:
                        module_error_measurement = ('ModuleError_%02d%s' %
                                                    (module.module_num,
                                                     module.module_name))
                        execution_time_measurement = ('ExecutionTime_%02d%s' %
                                                      (module.module_num,
                                                       module.module_name))
                    failure = 1
                    exception = None
                    tb = None
                    frame_if_shown = frame if module.show_window else None
                    workspace = cpw.Workspace(self,
                                              module,
                                              image_set,
                                              object_set,
                                              measurements,
                                              image_set_list,
                                              frame_if_shown,
                                              outlines = outlines)
                    grids = workspace.set_grids(grids)
                    if status_callback:
                        status_callback(module, len(self.modules()), 
                                        image_set_count, num_image_sets)
                    start_time = datetime.datetime.now()
                    t0 = sum(os.times()[:-1])
                    if not run_in_background:
                        try:
                            module.run(workspace)