Example #1
0
            def __init__(self, index, operation):
                self.__index = index
                self.__operation = operation
                self.__operand_choice = Choice(
                    self.operand_choice_text(),
                    MC_ALL,
                    doc="""Indicate whether the operand is an image or object measurement.""",
                )

                self.__operand_objects = LabelName(
                    self.operand_objects_text(),
                    "None",
                    doc="""Choose the objects you want to measure for this operation.""",
                )

                self.__operand_measurement = Measurement(
                    self.operand_measurement_text(),
                    self.object_fn,
                    doc="""\
Enter the category that was used to create the measurement. You
will be prompted to add additional information depending on
the type of measurement that is requested.""",
                )

                self.__multiplicand = Float(
                    "Multiply the above operand by",
                    1,
                    doc="""Enter the number by which you would like to multiply the above operand.""",
                )

                self.__exponent = Float(
                    "Raise the power of above operand by",
                    1,
                    doc="""Enter the power by which you would like to raise the above operand.""",
                )
Example #2
0
    def create_settings(self):
        """Create your settings by subclassing this function

        create_settings is called at the end of initialization.

        You should create the setting variables for your module here:
            # Ask the user for the input image
            self.image_name = .ImageSubscriber(...)
            # Ask the user for the name of the output image
            self.output_image = .ImageName(...)
            # Ask the user for a parameter
            self.smoothing_size = .Float(...)"""

        self.grouping_values = Measurement(
            "Select the image measurement describing the positive and negative control status",
            lambda: IMAGE,
            doc="""\
The Z’ factor, a measure of assay quality, is calculated by this module
based on measurements from images that are specified as positive
controls and images that are specified as negative controls. Images
that are neither are ignored. The module assumes that all of the
negative controls are specified by a minimum value, all of the positive
controls are specified by a maximum value, and all other images have an
intermediate value; this might allow you to use your dosing information
to also specify the positive and negative controls. If you don’t use
actual dose data to designate your controls, a common practice is to
designate -1 as a negative control, 0 as an experimental sample, and 1
as a positive control. In other words, positive controls should all be
specified by a single high value (for instance, 1) and negative controls
should all be specified by a single low value (for instance, -1). Other
samples should have an intermediate value to exclude them from the Z’
factor analysis.

The typical way to provide this information in the pipeline is to create
a text comma-delimited (CSV) file outside of CellProfiler and then load
that file into the pipeline using the **Metadata** module or the legacy
**LoadData** module. In that case, choose the measurement that matches
the column header of the measurement in the input file. See the main
module help for this module or for the **Metadata** module for an
example text file.
""",
        )
        self.dose_values = []
        self.add_dose_value(can_remove=False)
        self.add_dose_button = DoSomething(
            "", "Add another dose specification", self.add_dose_value
        )
Example #3
0
    def add_image(self, removable=True):
        # The text for these settings will be replaced in renumber_settings()
        group = SettingsGroup()
        group.removable = removable
        group.append(
            "image_or_measurement",
            Choice(
                "Image or measurement?",
                [IM_IMAGE, IM_MEASUREMENT],
                doc="""\
You can perform math operations using two images or you can use a
measurement for one of the operands. For instance, to divide the
intensity of one image by another, choose *%(IM_IMAGE)s* for both and
pick the respective images. To divide the intensity of an image by its
median intensity, use **MeasureImageIntensity** prior to this module to
calculate the median intensity, then select *%(IM_MEASUREMENT)s* and
use the median intensity measurement as the denominator.
""" % globals(),
            ),
        )

        group.append(
            "image_name",
            ImageSubscriber(
                "Select the image",
                "None",
                doc="""\
Select the image that you want to use for this operation.""",
            ),
        )

        group.append(
            "measurement",
            Measurement(
                "Measurement",
                lambda: "Image",
                "",
                doc="""\
Select a measurement made on the image. The value of the
measurement is used for the operand for all of the pixels of the
other operand's image.""",
            ),
        )

        group.append(
            "factor",
            Float(
                "Multiply the image by",
                1,
                doc="""\
Enter the number that you would like to multiply the above image by. This multiplication
is applied before other operations.""",
            ),
        )

        if removable:
            group.append(
                "remover",
                RemoveSettingButton("", "Remove this image", self.images,
                                    group),
            )

        group.append("divider", Divider())
        self.images.append(group)
Example #4
0
    def create_settings(self):
        """Create the module settings

        create_settings is called at the end of initialization.
        """
        self.object = LabelSubscriber(
            text="Select the object whose measurements will be displayed",
            value="None",
            doc=textwrap.dedent("""\
                Choose the name of objects identified by some previous module (such as
                **IdentifyPrimaryObjects** or **IdentifySecondaryObjects**) whose
                measurements are to be displayed.
            """),
        )

        self.x_axis = Measurement(
            text="Select the object measurement to plot",
            object_fn=self.get_object,
            value="None",
            doc=
            "Choose the object measurement made by a previous module to plot.",
        )

        self.bins = Integer(
            text="Number of bins",
            value=100,
            minval=1,
            maxval=1000,
            doc=
            "Enter the number of equally-spaced bins that you want used on the X-axis.",
        )

        self.xscale = Choice(
            text="How should the X-axis be scaled?",
            choices=["linear", "log"],
            value=None,
            doc=textwrap.dedent("""\
                The measurement data can be scaled with either a **{LINEAR}** scale or
                a **{LOG_NATURAL}** (natural log) scaling.

                Log scaling is useful when one of the measurements being plotted covers
                a large range of values; a log scale can bring out features in the
                measurements that would not easily be seen if the measurement is plotted
                linearly.
                """.format(
                LINEAR="linear",
                LOG_NATURAL="log",
            )),
        )

        self.yscale = Choice(
            text="How should the Y-axis be scaled?",
            choices=["linear", "log"],
            value=None,
            doc=textwrap.dedent("""\
                The Y-axis can be scaled either with either a **{LINEAR}** scale or a **{LOG_NATURAL}**
                (natural log) scaling.

                Log scaling is useful when one of the measurements being plotted covers
                a large range of values; a log scale can bring out features in the
                measurements that would not easily be seen if the measurement is plotted
                linearly.
                """.format(
                LINEAR="linear",
                LOG_NATURAL="log",
            )),
        )

        self.title = Text(
            text="Enter a title for the plot, if desired",
            value="",
            doc=textwrap.dedent("""\
                Enter a title for the plot. If you leave this blank, the title will
                default to *(cycle N)* where *N* is the current image cycle being
                executed.
                """),
        )

        self.wants_xbounds = Binary(
            text="Specify min/max bounds for the X-axis?",
            value=False,
            doc=textwrap.dedent("""\
                Select "**{YES}**" to specify minimum and maximum values for the plot on
                the X-axis. This is helpful if an outlier bin skews the plot such that
                the bins of interest are no longer visible.
                """.format(YES="Yes")),
        )

        self.xbounds = FloatRange(
            text="Minimum/maximum values for the X-axis",
            doc="Set lower/upper limits for X-axis of the histogram.",
        )
Example #5
0
    def create_settings(self):
        self.x_source = Choice(
            "Type of measurement to plot on X-axis",
            SOURCE_CHOICE,
            doc="""\
You can plot two types of measurements:

-  *%(SOURCE_IM)s:* For a per-image measurement, one numerical value is
   recorded for each image analyzed. Per-image measurements are produced
   by many modules. Many have **MeasureImage** in the name but others do
   not (e.g., the number of objects in each image is a per-image
   measurement made by the **Identify** modules).
-  *%(SOURCE_OBJ)s:* For a per-object measurement, each identified
   object is measured, so there may be none or many numerical values
   recorded for each image analyzed. These are usually produced by
   modules with **MeasureObject** in the name.
"""
            % globals(),
        )

        self.x_object = LabelSubscriber(
            "Select the object to plot on the X-axis",
            "None",
            doc="""\
*(Used only when plotting objects)*

Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**) whose
measurements are to be displayed on the X-axis.
""",
        )

        self.x_axis = Measurement(
            "Select the measurement to plot on the X-axis",
            self.get_x_object,
            "None",
            doc="""Choose the measurement (made by a previous module) to plot on the X-axis.""",
        )

        self.y_source = Choice(
            "Type of measurement to plot on Y-axis",
            SOURCE_CHOICE,
            doc="""\
You can plot two types of measurements:

-  *%(SOURCE_IM)s:* For a per-image measurement, one numerical value is
   recorded for each image analyzed. Per-image measurements are produced
   by many modules. Many have **MeasureImage** in the name but others do
   not (e.g., the number of objects in each image is a per-image
   measurement made by **Identify** modules).
-  *%(SOURCE_OBJ)s:* For a per-object measurement, each identified
   object is measured, so there may be none or many numerical values
   recorded for each image analyzed. These are usually produced by
   modules with **MeasureObject** in the name.
"""
            % globals(),
        )

        self.y_object = LabelSubscriber(
            "Select the object to plot on the Y-axis",
            "None",
            doc="""\
*(Used only when plotting objects)*

Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**) whose
measurements are to be displayed on the Y-axis.
""",
        )

        self.y_axis = Measurement(
            "Select the measurement to plot on the Y-axis",
            self.get_y_object,
            "None",
            doc="""Choose the measurement (made by a previous module) to plot on the Y-axis.""",
        )

        self.xscale = Choice(
            "How should the X-axis be scaled?",
            SCALE_CHOICE,
            None,
            doc="""\
The X-axis can be scaled with either a *linear* scale or a *log* (base
10) scaling.

Log scaling is useful when one of the measurements being plotted covers
a large range of values; a log scale can bring out features in the
measurements that would not easily be seen if the measurement is plotted
linearly.
""",
        )

        self.yscale = Choice(
            "How should the Y-axis be scaled?",
            SCALE_CHOICE,
            None,
            doc="""\
The Y-axis can be scaled with either a *linear* scale or with a *log*
(base 10) scaling.

Log scaling is useful when one of the measurements being plotted covers
a large range of values; a log scale can bring out features in the
measurements that would not easily be seen if the measurement is plotted
linearly.
""",
        )

        self.title = Text(
            "Enter a title for the plot, if desired",
            "",
            doc="""\
Enter a title for the plot. If you leave this blank, the title will
default to *(cycle N)* where *N* is the current image cycle being
executed.
""",
        )
Example #6
0
    def add_measurement(self, flag_settings, can_delete=True):
        measurement_settings = flag_settings.measurement_settings

        group = SettingsGroup()
        group.append("divider1", Divider(line=False))
        group.append(
            "source_choice",
            Choice(
                "Flag is based on",
                S_ALL,
                doc="""\
-  *%(S_IMAGE)s:* A per-image measurement, such as intensity or
   granularity.
-  *%(S_AVERAGE_OBJECT)s:* The average of all object measurements in
   the image.
-  *%(S_ALL_OBJECTS)s:* All the object measurements in an image,
   without averaging. In other words, if *any* of the objects meet the
   criteria, the image will be flagged.
-  *%(S_RULES)s:* Use a text file of rules produced by CellProfiler
   Analyst. With this option, you will have to ensure that this pipeline
   produces every measurement in the rules file upstream of this module.
-  *%(S_CLASSIFIER)s:* Use a classifier built by CellProfiler Analyst.
""" % globals(),
            ),
        )

        group.append(
            "object_name",
            LabelSubscriber(
                "Select the object to be used for flagging",
                "None",
                doc="""\
*(Used only when flag is based on an object measurement)*

Select the objects whose measurements you want to use for flagging.
""",
            ),
        )

        def object_fn():
            if group.source_choice == S_IMAGE:
                return IMAGE
            return group.object_name.value

        group.append(
            "rules_directory",
            Directory(
                "Rules file location",
                doc="""\
*(Used only when flagging using "{rules}")*

Select the location of the rules file that will be used for flagging images.
{folder_choice}
""".format(rules=S_RULES, folder_choice=IO_FOLDER_CHOICE_HELP_TEXT),
            ),
        )

        def get_directory_fn():
            """Get the directory for the rules file name"""
            return group.rules_directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = group.rules_directory.get_parts_from_path(
                path)
            group.rules_directory.join_parts(dir_choice, custom_path)

        group.append(
            "rules_file_name",
            Filename(
                "Rules file name",
                "rules.txt",
                get_directory_fn=get_directory_fn,
                set_directory_fn=set_directory_fn,
                doc="""\
*(Used only when flagging using "%(S_RULES)s")*

The name of the rules file, most commonly from CellProfiler Analyst's
Classifier. This file should be a plain text file
containing the complete set of rules.

Each line of this file should be a rule naming a measurement to be made
on an image, for instance:

    IF (Image_ImageQuality_PowerLogLogSlope_DNA < -2.5, [0.79, -0.79], [-0.94, 0.94])

The above rule will score +0.79 for the positive category and -0.94
for the negative category for images whose power log slope is less
than -2.5 pixels and will score the opposite for images whose slope is
larger. The filter adds positive and negative and flags the images
whose positive score is higher than the negative score.
""" % globals(),
            ),
        )

        def get_rules_class_choices(group=group):
            """Get the available choices from the rules file"""
            try:
                if group.source_choice == S_CLASSIFIER:
                    return self.get_bin_labels(group)
                elif group.source_choice == S_RULES:
                    rules = self.get_rules(group)
                    nclasses = len(rules.rules[0].weights[0])
                    return [str(i) for i in range(1, nclasses + 1)]
                else:
                    return ["None"]
                rules = self.get_rules(group)
                nclasses = len(rules.rules[0].weights[0])
                return [str(i) for i in range(1, nclasses + 1)]
            except:
                return [str(i) for i in range(1, 3)]

        group.append(
            "rules_class",
            MultiChoice(
                "Class number",
                choices=["1", "2"],
                doc="""\
*(Used only when flagging using "%(S_RULES)s")*

Select which classes to flag when filtering. The CellProfiler Analyst
Classifier user interface lists the names of the classes in order. By
default, these are the positive (class 1) and negative (class 2)
classes. **FlagImage** uses the first class from CellProfiler Analyst
if you choose “1”, etc.

Please note the following:

-  The flag is set if the image falls into the selected class.
-  You can make multiple class selections. If you do so, the module will
   set the flag if the image falls into any of the selected classes.
""" % globals(),
            ),
        )

        group.rules_class.get_choices = get_rules_class_choices

        group.append(
            "measurement",
            Measurement(
                "Which measurement?",
                object_fn,
                doc="""Choose the measurement to be used as criteria.""",
            ),
        )

        group.append(
            "wants_minimum",
            Binary(
                "Flag images based on low values?",
                True,
                doc="""\
Select *Yes* to flag images with measurements below the specified
cutoff. If the measurement evaluates to Not-A-Number (NaN), then the
image is not flagged.
""" % globals(),
            ),
        )

        group.append(
            "minimum_value",
            Float("Minimum value", 0, doc="""Set a value as a lower limit."""),
        )

        group.append(
            "wants_maximum",
            Binary(
                "Flag images based on high values?",
                True,
                doc="""\
Select *Yes* to flag images with measurements above the specified
cutoff. If the measurement evaluates to Not-A-Number (NaN), then the
image is not flagged.
""" % globals(),
            ),
        )

        group.append(
            "maximum_value",
            Float("Maximum value", 1,
                  doc="""Set a value as an upper limit."""),
        )

        if can_delete:
            group.append(
                "remover",
                RemoveSettingButton("", "Remove this measurement",
                                    measurement_settings, group),
            )

        group.append("divider2", Divider(line=True))
        measurement_settings.append(group)
Example #7
0
    def create_settings(self):
        self.x_object = LabelSubscriber(
            "Select the object to display on the X-axis",
            "None",
            doc="""\
Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**) whose
measurements are to be displayed on the X-axis.
""",
        )

        self.x_axis = Measurement(
            "Select the object measurement to plot on the X-axis",
            self.get_x_object,
            "None",
            doc="""Choose the object measurement made by a previous module to display on the X-axis.""",
        )

        self.y_object = LabelSubscriber(
            "Select the object to display on the Y-axis",
            "None",
            doc="""\
Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**) whose
measurements are to be displayed on the Y-axis.
""",
        )

        self.y_axis = Measurement(
            "Select the object measurement to plot on the Y-axis",
            self.get_y_object,
            "None",
            doc="""Choose the object measurement made by a previous module to display on the Y-axis.""",
        )

        self.gridsize = Integer(
            "Select the grid size",
            100,
            1,
            1000,
            doc="""\
Enter the number of grid regions you want used on each
axis. Increasing the number of grid regions increases the
resolution of the plot.""",
        )

        self.xscale = Choice(
            "How should the X-axis be scaled?",
            ["linear", "log"],
            None,
            doc="""\
The X-axis can be scaled either with a *linear* scale or with a *log*
(base 10) scaling.

Using a log scaling is useful when one of the measurements being plotted
covers a large range of values; a log scale can bring out features in
the measurements that would not easily be seen if the measurement is
plotted linearly.
""",
        )

        self.yscale = Choice(
            "How should the Y-axis be scaled?",
            ["linear", "log"],
            None,
            doc="""\
The Y-axis can be scaled either with a *linear* scale or with a *log*
(base 10) scaling.

Using a log scaling is useful when one of the measurements being plotted
covers a large range of values; a log scale can bring out features in
the measurements that would not easily be seen if the measurement is
plotted linearly.
""",
        )

        self.bins = Choice(
            "How should the colorbar be scaled?",
            ["linear", "log"],
            None,
            doc="""\
The colorbar can be scaled either with a *linear* scale or with a *log*
(base 10) scaling.

Using a log scaling is useful when one of the measurements being plotted
covers a large range of values; a log scale can bring out features in
the measurements that would not easily be seen if the measurement is
plotted linearly.
""",
        )

        maps = [m for m in list(matplotlib.cm.datad.keys()) if not m.endswith("_r")]
        maps.sort()

        self.colormap = Choice(
            "Select the color map",
            maps,
            "jet",
            doc="""\
Select the color map for the density plot. See `this page`_ for pictures
of the available colormaps.

.. _this page: http://matplotlib.org/users/colormaps.html
""",
        )

        self.title = Text(
            "Enter a title for the plot, if desired",
            "",
            doc="""\
Enter a title for the plot. If you leave this blank, the title will
default to *(cycle N)* where *N* is the current image cycle being
executed.
""",
        )
Example #8
0
    def add_dose_value(self, can_remove=True):
        """Add a dose value measurement to the list

        can_delete - set this to False to keep from showing the "remove"
                     button for images that must be present."""
        group = SettingsGroup()
        group.append(
            "measurement",
            Measurement(
                "Select the image measurement describing the treatment dose",
                lambda: IMAGE,
                doc="""\
The V and Z’ factors, metrics of assay quality, and the EC50,
indicating dose-response, are calculated by this module based on each
image being specified as a particular treatment dose. Choose a
measurement that gives the dose of some treatment for each of your
images. See the help for the previous setting for details.""",
            ),
        )

        group.append(
            "log_transform",
            Binary(
                "Log-transform the dose values?",
                False,
                doc="""\
Select *Yes* if you have dose-response data and you want to
log-transform the dose values before fitting a sigmoid curve.

Select *No* if your data values indicate only positive vs. negative
controls.
"""
                % globals(),
            ),
        )

        group.append(
            "wants_save_figure",
            Binary(
                """Create dose-response plots?""",
                False,
                doc="""Select *Yes* if you want to create and save dose-response plots.
You will be asked for information on how to save the plots."""
                % globals(),
            ),
        )

        group.append(
            "figure_name",
            Text(
                "Figure prefix",
                "",
                doc="""\
*(Used only when creating dose-response plots)*

CellProfiler will create a file name by appending the measurement name
to the prefix you enter here. For instance, if you specify a prefix
of “Dose\_”, when saving a file related to objects you have chosen (for
example, *Cells*) and a particular measurement (for example, *AreaShape_Area*),
CellProfiler will save the figure as *Dose_Cells_AreaShape_Area.m*.
Leave this setting blank if you do not want a prefix.
""",
            ),
        )
        group.append(
            "pathname",
            Directory(
                "Output file location",
                dir_choices=[
                    DEFAULT_OUTPUT_FOLDER_NAME,
                    DEFAULT_INPUT_FOLDER_NAME,
                    ABSOLUTE_FOLDER_NAME,
                    DEFAULT_OUTPUT_SUBFOLDER_NAME,
                    DEFAULT_INPUT_SUBFOLDER_NAME,
                ],
                doc="""\
*(Used only when creating dose-response plots)*

This setting lets you choose the folder for the output files. {fcht}

{mht}
""".format(
                    fcht=IO_FOLDER_CHOICE_HELP_TEXT, mht=IO_WITH_METADATA_HELP_TEXT
                ),
            ),
        )

        group.append("divider", Divider())

        group.append(
            "remover",
            RemoveSettingButton(
                "", "Remove this dose measurement", self.dose_values, group
            ),
        )
        self.dose_values.append(group)
    def create_settings(self):
        self.objects_or_image = Choice(
            "Display object or image measurements?",
            [OI_OBJECTS, OI_IMAGE],
            doc="""\
-  *%(OI_IMAGE)s* allows you to select an image measurement to display
   for each well.
-  *%(OI_OBJECTS)s* allows you to select an object measurement to
   display for each well.
""" % globals(),
        )

        self.object = LabelSubscriber(
            "Select the object whose measurements will be displayed",
            "None",
            doc="""\
Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**)
whose measurements are to be displayed.
""",
        )

        self.plot_measurement = Measurement(
            "Select the measurement to plot",
            self.get_object,
            "None",
            doc=
            """Choose the image or object measurement made by a previous module to plot.""",
        )

        self.plate_name = Measurement(
            "Select your plate metadata",
            lambda: IMAGE,
            "Metadata_Plate",
            doc="""\
Choose the metadata tag that corresponds to the plate identifier. That
is, each plate should have a metadata tag containing a specifier
corresponding uniquely to that plate.

{meta_help}
""".format(meta_help=USING_METADATA_HELP_REF),
        )

        self.plate_type = Choice(
            "Multiwell plate format",
            ["96", "384"],
            doc="""\
The module assumes that your data is laid out in a multi-well plate
format common to high-throughput biological screens. Supported formats
are:

-  *96:* A 96-well plate with 8 rows × 12 columns
-  *384:* A 384-well plate with 16 rows × 24 columns
""",
        )

        self.well_format = Choice(
            "Well metadata format",
            [WF_NAME, WF_ROWCOL],
            doc="""\
-  *%(WF_NAME)s* allows you to select an image measurement to display
   for each well.
-  *%(WF_ROWCOL)s* allows you to select an object measurement to
   display for each well.
""" % globals(),
        )

        self.well_name = Measurement(
            "Select your well metadata",
            lambda: IMAGE,
            "Metadata_Well",
            doc="""\
Choose the metadata tag that corresponds to the well identifier. The
row-column format of these entries should be an alphabetical character
(specifying the plate row), followed by two integer characters
(specifying the plate column). For example, a standard format 96-well
plate would span from “A1” to “H12”, whereas a 384-well plate (16 rows
and 24 columns) would span from well “A01” to well “P24”."

%(USING_METADATA_HELP_REF)s
""" % globals(),
        )

        self.well_row = Measurement(
            "Select your well row metadata",
            lambda: IMAGE,
            "Metadata_WellRow",
            doc="""\
Choose the metadata tag that corresponds to the well row identifier,
typically specified as an alphabetical character. For example, a
standard format 96-well plate would span from row “A” to “H”, whereas a
384-well plate (16 rows and 24 columns) would span from row “A” to “P”.

%(USING_METADATA_HELP_REF)s
""" % globals(),
        )

        self.well_col = Measurement(
            "Select your well column metadata",
            lambda: IMAGE,
            "Metadata_WellCol",
            doc="""\
Choose the metadata tag that corresponds to the well column identifier,
typically specified with two integer characters. For example, a standard
format 96-well plate would span from column “01” to “12”, whereas a
384-well plate (16 rows and 24 columns) would span from column “01” to
“24”.

{meta_help}
""".format(meta_help=USING_METADATA_HELP_REF),
        )

        self.agg_method = Choice(
            "How should the values be aggregated?",
            AGG_NAMES,
            AGG_NAMES[0],
            doc="""\
Measurements must be aggregated to a single number for each well so that
they can be represented by a color. Options are:

-  *%(AGG_AVG)s:* Average
-  *%(AGG_STDEV)s:* Standard deviation
-  *%(AGG_MEDIAN)s*
-  *%(AGG_CV)s:* Coefficient of variation, defined as the ratio of the
   standard deviation to the mean. This is useful for comparing between
   data sets with different units or widely different means.
""" % globals(),
        )

        self.title = Text(
            "Enter a title for the plot, if desired",
            "",
            doc="""\
Enter a title for the plot. If you leave this blank, the title will
default to *(cycle N)* where *N* is the current image cycle being
executed.
""",
        )
Example #10
0
    def add_measurement(self, can_delete=True):
        """Add another measurement to the filter list"""
        group = SettingsGroup()

        group.append(
            "measurement",
            Measurement(
                "Select the measurement to filter by",
                self.x_name.get_value,
                "AreaShape_Area",
                doc="""\
*(Used only if filtering using {MODE_MEASUREMENTS})*

See the **Measurements** modules help pages for more information on the
features measured.""".format(
                    **{"MODE_MEASUREMENTS": MODE_MEASUREMENTS}
                ),
            ),
        )

        group.append(
            "wants_minimum",
            Binary(
                "Filter using a minimum measurement value?",
                True,
                doc="""\
*(Used only if {FI_LIMITS} is selected for filtering method)*

Select "*{YES}*" to filter the objects based on a minimum acceptable
object measurement value. Objects which are greater than or equal to
this value will be retained.""".format(
                    **{"FI_LIMITS": FI_LIMITS, "YES": "Yes"}
                ),
            ),
        )

        group.append("min_limit", Float("Minimum value", 0))

        group.append(
            "wants_maximum",
            Binary(
                "Filter using a maximum measurement value?",
                True,
                doc="""\
*(Used only if {FI_LIMITS} is selected for filtering method)*

Select "*{YES}*" to filter the objects based on a maximum acceptable
object measurement value. Objects which are less than or equal to this
value will be retained.""".format(
                    **{"FI_LIMITS": FI_LIMITS, "YES": "Yes"}
                ),
            ),
        )

        group.append("max_limit", Float("Maximum value", 1))

        group.append("divider", Divider())

        self.measurements.append(group)

        if can_delete:
            group.append(
                "remover",
                RemoveSettingButton(
                    "", "Remove this measurement", self.measurements, group
                ),
            )
    def add_single_measurement(self, can_delete=True):
        """Add a single measurement to the group of single measurements

        can_delete - True to include a "remove" button, False if you're not
                     allowed to remove it.
        """
        group = SettingsGroup()
        if can_delete:
            group.append("divider", Divider(line=True))

        group.append(
            "object_name",
            LabelSubscriber(
                "Select the object to be classified",
                "None",
                doc="""\
The name of the objects to be classified. You can choose from objects
created by any previous module. See **IdentifyPrimaryObjects**,
**IdentifySecondaryObjects**, **IdentifyTertiaryObjects**, or **Watershed**
""",
            ),
        )

        def object_fn():
            return group.object_name.value

        group.append(
            "measurement",
            Measurement(
                "Select the measurement to classify by",
                object_fn,
                doc="""\
*(Used only if using a single measurement)*

Select a measurement made by a previous module. The objects will be
classified according to their values for this measurement.
""",
            ),
        )

        group.append(
            "bin_choice",
            Choice(
                "Select bin spacing",
                [BC_EVEN, BC_CUSTOM],
                doc="""\
*(Used only if using a single measurement)*

Select how you want to define the spacing of the bins. You have the
following options:

-  *%(BC_EVEN)s:* Choose this if you want to specify bins of equal
   size, bounded by upper and lower limits. If you want two bins, choose
   this option and then provide a single threshold when asked.
-  *%(BC_CUSTOM)s:* Choose this option to create the indicated number
   of bins at evenly spaced intervals between the low and high
   threshold. You also have the option to create bins for objects that
   fall below or above the low and high threshold.
""" % globals(),
            ),
        )

        group.append(
            "bin_count",
            Integer(
                "Number of bins",
                3,
                minval=1,
                doc="""\
*(Used only if using a single measurement)*

This is the number of bins that will be created between
the low and high threshold""",
            ),
        )

        group.append(
            "low_threshold",
            Float(
                "Lower threshold",
                0,
                doc="""\
*(Used only if using a single measurement and "%(BC_EVEN)s" selected)*

This is the threshold that separates the lowest bin from the others. The
lower threshold, upper threshold, and number of bins define the
thresholds of bins between the lowest and highest.
""" % globals(),
            ),
        )

        group.append(
            "wants_low_bin",
            Binary(
                "Use a bin for objects below the threshold?",
                False,
                doc="""\
*(Used only if using a single measurement)*

Select "*Yes*" if you want to create a bin for objects whose values
fall below the low threshold. Select "*No*" if you do not want a bin
for these objects.
""" % globals(),
            ),
        )

        group.append(
            "high_threshold",
            Float(
                "Upper threshold",
                1,
                doc="""\
*(Used only if using a single measurement and "%(BC_EVEN)s" selected)*

This is the threshold that separates the last bin from the others. Note
that if you would like two bins, you should select "*%(BC_CUSTOM)s*".
""" % globals(),
            ),
        )

        group.append(
            "wants_high_bin",
            Binary(
                "Use a bin for objects above the threshold?",
                False,
                doc="""\
*(Used only if using a single measurement)*

Select "*Yes*" if you want to create a bin for objects whose values
are above the high threshold.

Select "*No*" if you do not want a bin for these objects.
""" % globals(),
            ),
        )

        group.append(
            "custom_thresholds",
            Text(
                "Enter the custom thresholds separating the values between bins",
                "0,1",
                doc="""\
*(Used only if using a single measurement and "%(BC_CUSTOM)s" selected)*

This setting establishes the threshold values for the bins. You should
enter one threshold between each bin, separating thresholds with commas
(for example, *0.3, 1.5, 2.1* for four bins). The module will create one
more bin than there are thresholds.
""" % globals(),
            ),
        )

        group.append(
            "wants_custom_names",
            Binary(
                "Give each bin a name?",
                False,
                doc="""\
*(Used only if using a single measurement)*

Select "*Yes*" to assign custom names to bins you have specified.

Select "*No*" for the module to automatically assign names based on
the measurements and the bin number.
""" % globals(),
            ),
        )

        group.append(
            "bin_names",
            Text(
                "Enter the bin names separated by commas",
                "None",
                doc="""\
*(Used only if "Give each bin a name?" is checked)*

Enter names for each of the bins, separated by commas.
An example including three bins might be *First,Second,Third*.""",
            ),
        )

        group.append(
            "wants_images",
            Binary(
                "Retain an image of the classified objects?",
                False,
                doc="""\
Select "*Yes*" to keep an image of the objects which is color-coded
according to their classification, for use later in the pipeline (for
example, to be saved by a **SaveImages** module).
""" % globals(),
            ),
        )

        group.append(
            "image_name",
            ImageName(
                "Name the output image",
                "ClassifiedNuclei",
                doc=
                """Enter the name to be given to the classified object image.""",
            ),
        )

        group.can_delete = can_delete

        def number_of_bins():
            """Return the # of bins in this classification"""
            if group.bin_choice == BC_EVEN:
                value = group.bin_count.value
            else:
                value = len(group.custom_thresholds.value.split(",")) - 1
            if group.wants_low_bin:
                value += 1
            if group.wants_high_bin:
                value += 1
            return value

        group.number_of_bins = number_of_bins

        def measurement_name():
            """Get the measurement name to use inside the bin name

            Account for conflicts with previous measurements
            """
            measurement_name = group.measurement.value
            other_same = 0
            for other in self.single_measurements:
                if id(other) == id(group):
                    break
                if other.measurement.value == measurement_name:
                    other_same += 1
            if other_same > 0:
                measurement_name += str(other_same)
            return measurement_name

        def bin_feature_names():
            """Return the feature names for each bin"""
            if group.wants_custom_names:
                return [
                    name.strip() for name in group.bin_names.value.split(",")
                ]
            return [
                "_".join((measurement_name(), "Bin_%d" % (i + 1)))
                for i in range(number_of_bins())
            ]

        group.bin_feature_names = bin_feature_names

        def validate_group():
            bin_name_count = len(bin_feature_names())
            bin_count = number_of_bins()
            if bin_count < 1:
                bad_setting = (group.bin_count if group.bin_choice == BC_EVEN
                               else group.custom_thresholds)
                raise ValidationError(
                    "You must have at least one bin in order to take measurements. "
                    "Either add more bins or ask for bins for objects above or below threshold",
                    bad_setting,
                )
            if bin_name_count != number_of_bins():
                raise ValidationError(
                    "The number of bin names (%d) does not match the number of bins (%d)."
                    % (bin_name_count, bin_count),
                    group.bin_names,
                )
            for bin_feature_name in bin_feature_names():
                Alphanumeric.validate_alphanumeric_text(
                    bin_feature_name, group.bin_names, True)
            if group.bin_choice == BC_CUSTOM:
                try:
                    [
                        float(x.strip())
                        for x in group.custom_thresholds.value.split(",")
                    ]
                except ValueError:
                    raise ValidationError(
                        "Custom thresholds must be a comma-separated list "
                        'of numbers (example: "1.0, 2.3, 4.5")',
                        group.custom_thresholds,
                    )
            elif group.bin_choice == BC_EVEN:
                if group.low_threshold.value >= group.high_threshold.value:
                    raise ValidationError(
                        "Lower Threshold must be less than Upper Threshold",
                        group.low_threshold,
                    )

        group.validate_group = validate_group

        if can_delete:
            group.remove_settings_button = RemoveSettingButton(
                "", "Remove this classification", self.single_measurements,
                group)
        self.single_measurements.append(group)
    def create_settings(self):
        """Create the settings for the module

        Create the settings for the module during initialization.
        """
        self.contrast_choice = Choice(
            "Make each classification decision on how many measurements?",
            [BY_SINGLE_MEASUREMENT, BY_TWO_MEASUREMENTS],
            doc="""\
This setting controls how many measurements are used to make a
classifications decision for each object:

-  *%(BY_SINGLE_MEASUREMENT)s:* Classifies each object based on a
   single measurement.
-  *%(BY_TWO_MEASUREMENTS)s:* Classifies each object based on a pair
   of measurements taken together (that is, an object must meet two
   criteria to belong to a class).
""" % globals(),
        )

        ############### Single measurement settings ##################
        #
        # A list holding groupings for each of the single measurements
        # to be done
        #
        self.single_measurements = []
        #
        # A count of # of measurements
        #
        self.single_measurement_count = HiddenCount(self.single_measurements)
        #
        # Add one single measurement to start off
        #
        self.add_single_measurement(False)
        #
        # A button to press to get another measurement
        #
        self.add_measurement_button = DoSomething(
            "", "Add another classification", self.add_single_measurement)
        #
        ############### Two-measurement settings #####################
        #
        # The object for the contrasting method
        #
        self.object_name = LabelSubscriber(
            "Select the object name",
            "None",
            doc="""\
Choose the object that you want to measure from the list. This should be
an object created by a previous module such as
**IdentifyPrimaryObjects**, **IdentifySecondaryObjects**, **IdentifyTertiaryObjects**, or **Watershed**
""",
        )

        #
        # The two measurements for the contrasting method
        #
        def object_fn():
            return self.object_name.value

        self.first_measurement = Measurement(
            "Select the first measurement",
            object_fn,
            doc="""\
*(Used only if using a pair of measurements)*

Choose a measurement made on the above object. This is the first of two
measurements that will be contrasted together. The measurement should be
one made on the object in a prior module.
""",
        )

        self.first_threshold_method = Choice(
            "Method to select the cutoff",
            [TM_MEAN, TM_MEDIAN, TM_CUSTOM],
            doc="""\
*(Used only if using a pair of measurements)*

Objects are classified as being above or below a cutoff value for a
measurement. You can set this cutoff threshold in one of three ways:

-  *%(TM_MEAN)s*: At the mean of the measurement’s value for all
   objects in the image cycle.
-  *%(TM_MEDIAN)s*: At the median of the measurement’s value for all
   objects in the image set.
-  *%(TM_CUSTOM)s*: You specify a custom threshold value.
""" % globals(),
        )

        self.first_threshold = Float(
            "Enter the cutoff value",
            0.5,
            doc="""\
*(Used only if using a pair of measurements)*

This is the cutoff value separating objects in the two classes.""",
        )

        self.second_measurement = Measurement(
            "Select the second measurement",
            object_fn,
            doc="""\
*(Used only if using a pair of measurements)*

Select a measurement made on the above object. This is
the second of two measurements that will be contrasted together.
The measurement should be one made on the object in a prior
module.""",
        )

        self.second_threshold_method = Choice(
            "Method to select the cutoff",
            [TM_MEAN, TM_MEDIAN, TM_CUSTOM],
            doc="""\
*(Used only if using a pair of measurements)*

Objects are classified as being above or below a cutoff value for a
measurement. You can set this cutoff threshold in one of three ways:

-  *%(TM_MEAN)s:* At the mean of the measurement’s value for all
   objects in the image cycle.
-  *%(TM_MEDIAN)s:* At the median of the measurement’s value for all
   objects in the image set.
-  *%(TM_CUSTOM)s:* You specify a custom threshold value.
""" % globals(),
        )

        self.second_threshold = Float(
            "Enter the cutoff value",
            0.5,
            doc="""\
*(Used only if using a pair of measurements)*

This is the cutoff value separating objects in the two classes.""",
        )

        self.wants_custom_names = Binary(
            "Use custom names for the bins?",
            False,
            doc="""\
*(Used only if using a pair of measurements)*

Select "*Yes*" if you want to specify the names of each bin
measurement.

Select "*No*" to create names based on the measurements. For instance,
for “Intensity_MeanIntensity_Green” and
“Intensity_TotalIntensity_Blue”, the module generates measurements
such as
“Classify_Intensity_MeanIntensity_Green_High_Intensity_TotalIntensity_Low”.
""" % globals(),
        )

        self.low_low_custom_name = Alphanumeric(
            "Enter the low-low bin name",
            "low_low",
            doc="""\
*(Used only if using a pair of measurements)*

Name of the measurement for objects that fall below the threshold for
both measurements.
""",
        )

        self.low_high_custom_name = Alphanumeric(
            "Enter the low-high bin name",
            "low_high",
            doc="""\
*(Used only if using a pair of measurements)*

Name of the measurement for objects whose
first measurement is below threshold and whose second measurement
is above threshold.
""",
        )

        self.high_low_custom_name = Alphanumeric(
            "Enter the high-low bin name",
            "high_low",
            doc="""\
*(Used only if using a pair of measurements)*

Name of the measurement for objects whose
first measurement is above threshold and whose second measurement
is below threshold.""",
        )

        self.high_high_custom_name = Alphanumeric(
            "Enter the high-high bin name",
            "high_high",
            doc="""\
*(Used only if using a pair of measurements)*

Name of the measurement for objects that
are above the threshold for both measurements.""",
        )

        self.wants_image = Binary(
            "Retain an image of the classified objects?",
            False,
            doc="""\
Select "*Yes*" to retain the image of the objects color-coded
according to their classification, for use later in the pipeline (for
example, to be saved by a **SaveImages** module).
""" % globals(),
        )

        self.image_name = ImageName(
            "Enter the image name",
            "None",
            doc="""\
*(Used only if the classified object image is to be retained for later use in the pipeline)*

Enter the name to be given to the classified object image.""",
        )
    def create_settings(self):
        """Create your settings by subclassing this function

        create_settings is called at the end of initialization.

        You should create the setting variables for your module here:
            # Ask the user for the input image
            self.image_name = .ImageSubscriber(...)
            # Ask the user for the name of the output image
            self.output_image = .ImageName(...)
            # Ask the user for a parameter
            self.smoothing_size = .Float(...)
        """
        self.objects_or_image = Choice(
            "Display object or image measurements?",
            [OI_OBJECTS, OI_IMAGE],
            doc="""\
-  *%(OI_OBJECTS)s* displays measurements made on objects.
-  *%(OI_IMAGE)s* displays a single measurement made on an image.
""" % globals(),
        )

        self.objects_name = LabelSubscriber(
            "Select the input objects",
            "None",
            doc="""\
*(Used only when displaying object measurements)*

Choose the name of objects identified by some previous module (such as
**IdentifyPrimaryObjects** or **IdentifySecondaryObjects**).
""",
        )

        def object_fn():
            if self.objects_or_image == OI_OBJECTS:
                return self.objects_name.value
            else:
                return "Image"

        self.measurement = Measurement(
            "Measurement to display",
            object_fn,
            doc="""\
Choose the measurement to display. This will be a measurement made by
some previous module on either the whole image (if displaying a single
image measurement) or on the objects you selected.
""",
        )

        self.wants_image = Binary(
            "Display background image?",
            True,
            doc="""\
Choose whether or not to display the measurements on
a background image. Usually, you will want to see the image
context for the measurements, but it may be useful to save
just the overlay of the text measurements and composite the
overlay image and the original image later. Choose "Yes" to
display the measurements on top of a background image or "No"
to display the measurements on a black background.""",
        )

        self.image_name = ImageSubscriber(
            "Select the image on which to display the measurements",
            "None",
            doc="""\
Choose the image to be displayed behind the measurements.
This can be any image created or loaded by a previous module.
If you have chosen not to display the background image, the image
will only be used to determine the dimensions of the displayed image.""",
        )

        self.color_or_text = Choice(
            "Display mode",
            [CT_TEXT, CT_COLOR],
            doc="""\
*(Used only when displaying object measurements)*

Choose how to display the measurement information. If you choose
%(CT_TEXT)s, **DisplayDataOnImage** will display the numeric value on
top of each object. If you choose %(CT_COLOR)s, **DisplayDataOnImage**
will convert the image to grayscale, if necessary, and display the
portion of the image within each object using a hue that indicates the
measurement value relative to the other objects in the set using the
default color map.
""" % globals(),
        )

        self.colormap = Colormap(
            "Color map",
            doc="""\
*(Used only when displaying object measurements)*

This is the color map used as the color gradient for coloring the
objects by their measurement values. See `this page`_ for pictures
of the available colormaps.

.. _this page: http://matplotlib.org/users/colormaps.html
            """,
        )
        self.text_color = Color(
            "Text color",
            "red",
            doc=
            """This is the color that will be used when displaying the text.""",
        )

        self.display_image = ImageName(
            "Name the output image that has the measurements displayed",
            "DisplayImage",
            doc="""\
The name that will be given to the image with the measurements
superimposed. You can use this name to refer to the image in subsequent
modules (such as **SaveImages**).
""",
        )

        self.font_size = Integer(
            "Font size (points)",
            10,
            minval=1,
            doc="""Set the font size of the letters to be displayed.""",
        )

        self.decimals = Integer(
            "Number of decimals",
            2,
            minval=0,
            doc=
            """Set how many decimals to be displayed, for example 2 decimals for 0.01; 3 decimals for 0.001.""",
        )

        self.saved_image_contents = Choice(
            "Image elements to save",
            [E_IMAGE, E_FIGURE, E_AXES],
            doc="""\
This setting controls the level of annotation on the image:

-  *%(E_IMAGE)s:* Saves the image with the overlaid measurement
   annotations.
-  *%(E_AXES)s:* Adds axes with tick marks and image coordinates.
-  *%(E_FIGURE)s:* Adds a title and other decorations.
""" % globals(),
        )

        self.offset = Integer(
            "Annotation offset (in pixels)",
            0,
            doc="""\
Add a pixel offset to the measurement. Normally, the text is
placed at the object (or image) center, which can obscure relevant features of
the object. This setting adds a specified offset to the text, in a random
direction.""",
        )

        self.color_map_scale_choice = Choice(
            "Color map scale",
            [CMS_USE_MEASUREMENT_RANGE, CMS_MANUAL],
            doc="""\
*(Used only when displaying object measurements as a colormap)*

**DisplayDataOnImage** assigns a color to each object’s measurement
value from a colormap when in colormap-mode, mapping the value to a
color along the colormap’s continuum. This mapping has implicit upper
and lower bounds to its range which are the extremes of the colormap.
This setting determines whether the extremes are the minimum and
maximum values of the measurement from among the objects in the
current image or manually-entered extremes.

-  *%(CMS_USE_MEASUREMENT_RANGE)s:* Use the full range of colors to
   get the maximum contrast within the image.
-  *%(CMS_MANUAL)s:* Manually set the upper and lower bounds so that
   images with different maxima and minima can be compared by a uniform
   color mapping.
""" % globals(),
        )
        self.color_map_scale = FloatRange(
            "Color map range",
            value=(0.0, 1.0),
            doc="""\
*(Used only when setting a manual colormap range)*

This setting determines the lower and upper bounds of the values for the
color map.
""",
        )