Esempio n. 1
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  cps.NONE)

        self.probability_maps = []

        self.probability_map_count = cps.HiddenCount(self.probability_maps,
                                                     "Probability map count")

        self.add_probability_map(False)

        self.add_probability_button = cps.DoSomething(
            "",
            "Add another probability map",
            self.add_probability_map,
            doc="""
            Press this button to output another
            probability map image from the classifier. Ilastik can be trained
            to recognize any number of classes of pixels. You can generate
            probability maps for any or all of them simultaneously by adding
            more images.""")

        self.h5_directory = cps.DirectoryPath(
            "Classifier file location",
            dir_choices=[
                DEFAULT_OUTPUT_FOLDER_NAME, DEFAULT_INPUT_FOLDER_NAME,
                ABSOLUTE_FOLDER_NAME, DEFAULT_INPUT_SUBFOLDER_NAME,
                DEFAULT_OUTPUT_SUBFOLDER_NAME, URL_FOLDER_NAME
            ],
            allow_metadata=False,
            doc="""
                Select the folder containing the classifier file to be loaded.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals())

        def get_directory_fn():
            '''Get the directory for the CSV file name'''
            return self.h5_directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = self.h5_directory.get_parts_from_path(
                path)
            self.h5_directory.join_parts(dir_choice, custom_path)

        self.classifier_file_name = cps.FilenameText(
            "Classfier file name",
            cps.NONE,
            doc="""This is the name of the Classfier file.""",
            get_directory_fn=get_directory_fn,
            set_directory_fn=set_directory_fn,
            browse_msg="Choose Classifier file",
            exts=[("Classfier file (*.h5)", "*.h5"),
                  ("All files (*.*)", "*.*")])
        self.no_ilastik_msg = cps.HTMLText("",
                                           content="""
            ClassifyPixels cannot run on this platform because
            the necessary libraries are not available. ClassifyPixels is
            supported on 64-bit versions of Windows Vista, Windows 7 and
            Windows 8 and on Linux.""",
                                           size=(-1, 50))
Esempio n. 2
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  "None")

        self.probability_maps = []

        self.probability_map_count = cps.HiddenCount(self.probability_maps,
                                                     "Probability map count")

        self.add_probability_map(False)

        self.add_probability_button = cps.DoSomething(
            "Add another probability map",
            "Add",
            self.add_probability_map,
            doc="""Press the <i>Add</i> button to output another
            probability map image from the classifier. Ilastik can be trained
            to recognize any number of classes of pixels. You can generate
            probability maps for any or all of them simultaneously by adding
            more images.""")

        self.h5_directory = cps.DirectoryPath(
            "Classifier file location",
            dir_choices=[
                DEFAULT_OUTPUT_FOLDER_NAME, DEFAULT_INPUT_FOLDER_NAME,
                ABSOLUTE_FOLDER_NAME, DEFAULT_INPUT_SUBFOLDER_NAME,
                DEFAULT_OUTPUT_SUBFOLDER_NAME
            ],
            allow_metadata=False,
            doc=
            """Select the folder containing the classifier file to be loaded. 
            %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals())

        def get_directory_fn():
            '''Get the directory for the CSV file name'''
            return self.h5_directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = self.h5_directory.get_parts_from_path(
                path)
            self.h5_directory.join_parts(dir_choice, custom_path)

        self.classifier_file_name = cps.FilenameText(
            "Classfier file name",
            "None",
            doc="""This is the name of the Classfier file.""",
            get_directory_fn=get_directory_fn,
            set_directory_fn=set_directory_fn,
            browse_msg="Choose Classifier file",
            exts=[("Classfier file (*.h5)", "*.h5"),
                  ("All files (*.*)", "*.*")])
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  "None")

        # The following settings are used for the combine option
        self.output_image = cps.ImageNameProvider(
            "Name the output probability map", "ProbabilityMap")

        self.class_sel = cps.Integer(
            "Select the class",
            0,
            0,
            42,
            doc='''Select the class you want to use. The class number 
            corresponds to the label-class in ilastik''')

        self.h5_directory = cps.DirectoryPath(
            "Classifier file location",
            dir_choices=[
                DEFAULT_OUTPUT_FOLDER_NAME, DEFAULT_INPUT_FOLDER_NAME,
                ABSOLUTE_FOLDER_NAME, DEFAULT_INPUT_SUBFOLDER_NAME,
                DEFAULT_OUTPUT_SUBFOLDER_NAME
            ],
            allow_metadata=False,
            doc=
            """Select the folder containing the classifier file to be loaded. 
            %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals())

        def get_directory_fn():
            '''Get the directory for the CSV file name'''
            return self.h5_directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = self.h5_directory.get_parts_from_path(
                path)
            self.h5_directory.join_parts(dir_choice, custom_path)

        self.classifier_file_name = cps.FilenameText(
            "Classfier file name",
            "None",
            doc="""This is the name of the Classfier file.""",
            get_directory_fn=get_directory_fn,
            set_directory_fn=set_directory_fn,
            browse_msg="Choose Classifier file",
            exts=[("Classfier file (*.h5)", "*.h5"),
                  ("All files (*.*)", "*.*")])
Esempio n. 4
0
    def add_file(self, can_remove = True):
        """Add settings for another file to the list"""
        group = cps.SettingsGroup()
        if can_remove:
            group.append("divider", cps.Divider(line=False))
        def get_directory_fn():
            return self.directory.get_absolute_path()
        
        group.append("file_name", cps.FilenameText(
                    FILE_TEXT,
                    cps.NONE,
                    metadata=True,
                    get_directory_fn = get_directory_fn,
                    exts = [("TIF - Tagged Image File format (*.tif,*.tiff)","*.tif,*.tiff"),
                            ("PNG - Portable Network Graphics (*.png)", "*.png"),
                            ("JPG/JPEG file (*.jpg,*.jpeg)", "*.jpg,*.jpeg"),
                            ("BMP - Windows Bitmap (*.bmp)", "*.bmp"),
                            ("Compuserve GIF file (*.gif)", "*.gif"),
                            ("MATLAB image (*.mat)","*.mat"),
                            ("All files (*.*)", "*.*")],doc = """
                    The filename can be constructed in one of two ways:
                    <ul>
                    <li>As a fixed filename (e.g., <i>Exp1_D03f00d0.tif</i>). </li>
                    <li>Using the metadata associated with an image set in 
                    <b>LoadImages</b> or <b>LoadData</b>. This is especially useful 
                    if you want your output given a unique label according to the
                    metadata corresponding to an image group. The name of the metadata 
                    to substitute is included in a special tag format embedded 
                    in your file specification. %(USING_METADATA_TAGS_REF)s%(USING_METADATA_HELP_REF)s.</li>
                    </ul>
                    <p>Keep in mind that in either case, the image file extension, if any, must be included."""% globals() ))
        
        group.append("image_objects_choice", cps.Choice(
                    'Load as images or objects?', IO_ALL, doc = """
                    This setting determines whether you load an image as image data
                    or as segmentation results (i.e., objects):
                    <ul>
                    <li><i>%(IO_IMAGES)s:</i> The input image will be given a user-specified name by
                    which it will be refered downstream. This is the most common usage for this
                    module.</li>
                    <li><i>%(IO_OBJECTS)s:</i> Use this option if the input image is a label matrix 
                    and you want to obtain the objects that it defines. A <i>label matrix</i>
                    is a grayscale or color image in which the connected regions share the
                    same label, and defines how objects are represented in CellProfiler.
                    The labels are integer values greater than or equal to 0. 
                    The elements equal to 0 are the background, whereas the elements equal to 1 
                    make up one object, the elements equal to 2 make up a second object, and so on.
                    This option allows you to use the objects without needing to insert an 
                    <b>Identify</b> module to extract them first. See <b>IdentifyPrimaryObjects</b> 
                    for more details.</li>
                    </ul>"""%globals()))
        
        group.append("image_name", cps.FileImageNameProvider("Name the image that will be loaded", 
                    "OrigBlue", doc = '''
                    <i>(Used only if an image is output)</i><br>
                    Enter the name of the image that will be loaded. 
                    You can use this name to select the image in downstream modules.'''))
        
        group.append("rescale", cps.Binary(
                    "Rescale intensities?",True,doc = """
                    <i>(Used only if an image is output)</i><br>
                    This option determines whether image metadata should be
                    used to rescale the image's intensities. Some image formats
                    save the maximum possible intensity value along with the pixel data.
                    For instance, a microscope might acquire images using a 12-bit
                    A/D converter which outputs intensity values between zero and 4095,
                    but stores the values in a field that can take values up to 65535.
                    <p>Select <i>%(YES)s</i> to rescale the image intensity so that
                    saturated values are rescaled to 1.0 by dividing all pixels
                    in the image by the maximum possible intensity value. </p>
                    <p>Select <i>%(NO)s</i> to ignore the image metadata and rescale the image
                    to 0 &ndash; 1.0 by dividing by 255 or 65535, depending on the number
                    of bits used to store the image.</p>"""%globals()))

        group.append("objects_name", cps.ObjectNameProvider(
                    'Name this loaded object',
                    "Nuclei",
                    doc = """<i>(Used only if objects are output)</i><br>
                    This is the name for the objects loaded from your image"""))
        
        group.append("wants_outlines", cps.Binary(
                    "Retain outlines of loaded objects?", False, doc = """
                    <i>(Used only if objects are output)</i><br>
                    Select <i>%(YES)s</i> if you want to save an image of the outlines
                    of the loaded objects."""%globals()))
        
        group.append("outlines_name", cps.OutlineNameProvider(
                    'Name the outlines',
                    'NucleiOutlines',doc = """
                    <i>(Used only if objects are output)</i><br>
                    Enter a name that will allow the outlines to be selected later in the pipeline."""))
        
        if can_remove:
            group.append("remove", cps.RemoveSettingButton("", "Remove this image", self.file_settings, group))
        self.file_settings.append(group)
Esempio n. 5
0
    def add_measurement(self, flag_settings, can_delete=True):
        measurement_settings = flag_settings.measurement_settings

        group = cps.SettingsGroup()
        group.append("divider1", cps.Divider(line=False))
        group.append(
            "source_choice",
            cps.Choice("Flag is based on",
                       S_ALL,
                       doc='''
                        <ul>
                        <li><i>%(S_IMAGE)s:</i> A per-image measurement, such as intensity or 
                        granularity.</li>
                        <li><i>%(S_AVERAGE_OBJECT)s:</i> The average of all 
                        object measurements in the image.</li>
                        <li><i>%(S_ALL_OBJECTS)s:</i> All the 
                        object measurements in an image, without averaging. In other words, if <i>any</i> 
                        of the objects meet the criteria, the image will be flagged.</li>
                        <li><i>%(S_RULES)s:</i>Use a text file of rules produced by CellProfiler Analyst. If you 
                        choose <i>Rules</i>, you will have to ensure that this pipeline makes every measurement 
                        in the rules file prior to this module.</li>
                        </ul>''' % globals()))

        group.append(
            "object_name",
            cps.ObjectNameSubscriber(
                "Select the object to be used for flagging",
                cps.NONE,
                doc='''
                        <i>(Used only when flag is based on an object measurement)</i><br>
                        Select the objects whose measurements you want to use for flagging.'''
            ))

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

        group.append(
            "rules_directory",
            cps.DirectoryPath("Rules file location",
                              doc="""
                        <i>(Used only when flagging using %(S_RULES)s)</i><br>
                        Select the location of the rules file that will be used for filtering.
                        %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals()))

        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",
            cps.FilenameText("Rules file name",
                             "rules.txt",
                             get_directory_fn=get_directory_fn,
                             set_directory_fn=set_directory_fn,
                             doc="""
                        <i>(Used only when flagging using %(S_RULES)s)</i><br>
                        The name of the rules file. This file should be a plain text
                        file containing the complete set of rules.
                        <p>Each line of
                        this file should be a rule naming a measurement to be made
                        on an image, for instance:
                        <pre>IF (Image_ImageQuality_PowerLogLogSlope_DNA &lt; -2.5, [0.79, -0.79], [-0.94, 0.94])</pre><br><br>
                        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.</p>"""
                             % globals()))

        def get_rules_class_choices(group=group):
            '''Get the available choices from the rules file'''
            try:
                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",
            cps.MultiChoice("Class number",
                            choices=["1", "2"],
                            doc="""
                        <i>(Used only when flagging using %(S_RULES)s)</i><br>
                        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. <b>FlagImage</b> uses the
                        first class from CellProfiler Analyst if you choose "1", etc. 
                        <p>Please note the following:
                        <ul>
                        <li>The flag is set if the image falls into the selected class.</li>
                        <li>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.</li>
                        </ul></p>""" % globals()))

        group.rules_class.get_choices = get_rules_class_choices

        group.append("measurement",
                     cps.Measurement("Which measurement?", object_fn))

        group.append(
            "wants_minimum",
            cps.Binary("Flag images based on low values?",
                       True,
                       doc='''
                         Select <i>%(YES)s</i> to flag images with measurements below the specified cutoff.'''
                       % globals()))

        group.append("minimum_value", cps.Float("Minimum value", 0))

        group.append(
            "wants_maximum",
            cps.Binary("Flag images based on high values?",
                       True,
                       doc='''
                         Select <i>%(YES)s</i> to flag images with measurements above the specified cutoff.'''
                       % globals()))

        group.append("maximum_value", cps.Float("Maximum value", 1))

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

        group.append("divider2", cps.Divider(line=True))
        measurement_settings.append(group)
Esempio n. 6
0
    def create_settings(self):
        '''Create the settings for the ExportToCellH5 module'''
        self.directory = cps.DirectoryPath("Output file location",
                                           doc="""
            This setting lets you choose the folder for the output files.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s
            """ % globals())

        def get_directory_fn():
            '''Get the directory for the CellH5 file'''
            return self.directory.get_absolute_path()

        def set_directory_fn(path):
            dir_choice, custom_path = self.directory.get_parts_from_path(path)
            self.directory.join_parts(dir_choice, custom_path)

        self.file_name = cps.FilenameText("Output file name",
                                          "DefaultOut.ch5",
                                          get_directory_fn=get_directory_fn,
                                          set_directory_fn=set_directory_fn,
                                          metadata=True,
                                          browse_msg="Choose CellH5 file",
                                          mode=cps.FilenameText.MODE_APPEND,
                                          exts=[("CellH5 file (*.cellh5)",
                                                 "*.ch5"),
                                                ("HDF5 file (*.h5)", "*.h5"),
                                                ("All files (*.*", "*.*")],
                                          doc="""
            This setting lets you name your CellH5 file. If you choose an
            existing file, CellProfiler will add new data to the file
            or overwrite existing locations.
            <p>%(IO_WITH_METADATA_HELP_TEXT)s %(USING_METADATA_TAGS_REF)s.
            For instance, if you have a metadata tag named
            "Plate", you can create a per-plate folder by selecting one the subfolder options
            and then specifying the subfolder name as "\g&lt;Plate&gt;". The module will
            substitute the metadata values for the current image set for any metadata tags in the
            folder name.%(USING_METADATA_HELP_REF)s.</p>

            """ % globals())
        self.overwrite_ok = cps.Binary(
            "Overwrite existing data without warning?",
            False,
            doc="""
            Select <i>%(YES)s</i> to automatically overwrite any existing data
            for a site. Select <i>%(NO)s</i> to be prompted first.

            If you are running the pipeline on a computing cluster,
            select <i>%(YES)s</i> unless you want execution to stop because you
            will not be prompted to intervene. Also note that two instances
            of CellProfiler cannot write to the same file at the same time,
            so you must ensure that separate names are used on a cluster.
            """ % globals())
        self.repack = cps.Binary("Repack after analysis",
                                 True,
                                 doc="""
            This setting determines whether CellProfiler in multiprocessing mode
            repacks the data at the end of analysis. If you select <i>%(YES)s</i>,
            CellProfiler will combine all of the satellite files into a single
            file upon completion. This option requires some extra temporary disk
            space and takes some time at the end of analysis, but results in
            a single file which may occupy less disk space. If you select
            <i>%(NO)s</i>, CellProfiler will create a master file using the
            name that you give and this file will have links to individual
            data files that contain the actual data. Using the data generated by
            this option requires that you keep the master file and the linked
            files together when copying them to a new folder.
            """ % globals())
        self.plate_metadata = cps.Choice("Plate metadata", [],
                                         value="Plate",
                                         choices_fn=self.get_metadata_choices,
                                         doc="""
            This is the metadata tag that identifies the plate name of
            the images for the current cycle. Choose <i>None</i> if
            your assay does not have metadata for plate name. If your
            assay is slide-based, you can use a metadata item that identifies
            the slide as the choice for this setting and set the well
            and site metadata items to <i>None</i>.""")
        self.well_metadata = cps.Choice(
            "Well metadata", [],
            value="Well",
            choices_fn=self.get_metadata_choices,
            doc="""This is the metadata tag that identifies the well name
            for the images in the current cycle. Choose <i>None</i> if
            your assay does not have metadata for the well.""")
        self.site_metadata = cps.Choice(
            "Site metadata", [],
            value="Site",
            choices_fn=self.get_metadata_choices,
            doc="""This is the metadata tag that identifies the site name
                for the images in the current cycle. Choose <i>None</i> if
                your assay doesn't divide wells up into sites or if this
                tag is not required for other reasons.""")
        self.divider = cps.Divider()
        self.wants_to_choose_measurements = cps.Binary("Choose measurements?",
                                                       False,
                                                       doc="""
            This setting lets you choose between exporting all measurements or
            just the ones that you choose. Select <i>%(YES)s</i> to pick the
            measurements to be exported. Select <i>%(NO)s</i> to automatically
            export all measurements available at this stage of the pipeline.
            """ % globals())
        self.measurements = cps.MeasurementMultiChoice(
            "Measurements to export",
            doc="""
            <i>(Used only if choosing measurements.)</i>
            <br>
            This setting lets you choose individual measurements to be exported.
            Check the measurements you want to export.
            """)
        self.objects_to_export = []
        self.add_objects_button = cps.DoSomething("Add objects to export",
                                                  "Add objects",
                                                  self.add_objects)
        self.images_to_export = []
        self.add_image_button = cps.DoSomething("Add an image to export",
                                                "Add image", self.add_image)
        self.objects_count = cps.HiddenCount(self.objects_to_export)
        self.images_count = cps.HiddenCount(self.images_to_export)
Esempio n. 7
0
 def get_command_settings(self, command, d):
     '''Get the settings associated with the current command
     
     d - the dictionary that persists the setting. None = regular
     '''
     key = command.get_unicode_value()
     if not d.has_key(key):
         try:
             module_info = command.get_selected_leaf()[2]
         except cps.ValidationError:
             logger.info("Could not find command %s" % key)
             return []
         result = []
         inputs = module_info.getInputs()
         for module_item in inputs:
             field_type = module_item.getType()
             label = module_item.getLabel()
             if label is None:
                 label = module_item.getName()
             if module_item.isOutput():
                 # if both, qualify which is for input and which for output
                 label = "%s (Input)" % label
             minimum = module_item.getMinimumValue()
             maximum = module_item.getMaximumValue()
             default = module_item.loadValue()
             description = module_item.getDescription()
             if field_type == ij2.FT_BOOL:
                 value = (J.is_instance_of(default, 'java/lang/Boolean')
                          and J.call(default, "booleanValue", "()Z"))
                 setting = cps.Binary(label, value=value, doc=description)
             elif field_type == ij2.FT_INTEGER:
                 if J.is_instance_of(default, 'java/lang/Number'):
                     value = J.call(default, "intValue", "()I")
                 elif minimum is not None:
                     value = minimum
                 elif maximum is not None:
                     value = maximum
                 else:
                     value = 0
                 setting = cps.Integer(label, value=value, doc=description)
             elif field_type == ij2.FT_FLOAT:
                 if J.is_instance_of(default, 'java/lang/Number'):
                     value = J.call(default, "doubleValue", "()D")
                 elif minimum is not None:
                     value = minimum
                 elif maximum is not None:
                     value = maximum
                 else:
                     value = 0
                 setting = cps.Float(label, value=value, doc=description)
             elif field_type == ij2.FT_STRING:
                 choices = module_item.getChoices()
                 value = J.to_string(default)
                 if choices is not None:
                     choices = J.get_collection_wrapper(choices)
                     setting = cps.Choice(label,
                                          choices,
                                          value,
                                          doc=description)
                 else:
                     setting = cps.Text(label, value, doc=description)
             elif field_type == ij2.FT_COLOR:
                 value = "#ffffff"
                 setting = cps.Color(label, value, doc=description)
             elif field_type == ij2.FT_IMAGE:
                 setting = cps.ImageNameSubscriber(label,
                                                   "InputImage",
                                                   doc=description)
             elif field_type == ij2.FT_TABLE:
                 setting = IJTableSubscriber(label,
                                             "InputTable",
                                             doc=description)
             elif field_type == ij2.FT_FILE:
                 setting = cps.FilenameText(label, None, doc=description)
             else:
                 continue
             result.append((setting, module_item))
         for output in module_info.getOutputs():
             field_type = output.getType()
             label = output.getLabel()
             if label is None:
                 label = output.getName()
             if output.isInput():
                 # if both, qualify which is for input and which for output
                 label = "%s (Output)" % label
             if field_type == ij2.FT_IMAGE:
                 result.append(
                     (cps.ImageNameProvider(label,
                                            "ImageJImage",
                                            doc=description), output))
             elif field_type == ij2.FT_TABLE:
                 result.append((IJTableProvider(label,
                                                "ImageJTable",
                                                doc=description), output))
         d[key] = result
     else:
         result = d[key]
     return [setting for setting, module_info in result]
Esempio n. 8
0
    def add_measurement(self, flag_settings, can_delete=True):
        measurement_settings = flag_settings.measurement_settings

        group = cps.SettingsGroup()
        group.append("divider1", cps.Divider(line=False))
        group.append("source_choice",
                     cps.Choice(
                "Flag is based on", S_ALL, doc = '''
                <ul>
                <li><i> Whole-image measurement:</i> A per-image measurement, such as intensity or 
                granularity.</li>
                <li><i> Average measurement for all objects in each image:</i> The average of all 
                object measurements in the image.</li>
                <li><i> Measurements for all objects in each image:</i> All the 
                object measurements in an image, without averaging. In other words, if <i>any</i> 
                of the objects meet the criteria, the image will be flagged.</li>
                <li><i>Rules:</i>Use a text file of rules produced by CellProfiler Analyst. If you 
                choose <i>Rules</i>, you will have to ensure that this pipeline makes every measurement 
                in the rules file prior to this module.</li>
                </ul>'''))
        group.append("object_name",
                     cps.ObjectNameSubscriber(
                "Select the object whose measurements will be used to flag",
                "None", doc = '''<i>(Used only when flag is based on an object measurement)</i><br>What did you call the objects whose measurements you want to use for flagging?'''))

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

        group.append("rules_directory",
                     cps.DirectoryPath(
                    "Rules file location",
                    doc = """<i>(Used only when filtering by rules)</i>
                    <br>
                    Select the location of the rules file that will be used for filtering.
                    %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals()))
         
        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", cps.FilenameText(
                    "Rules file name","rules.txt",
                    get_directory_fn = get_directory_fn,
                    set_directory_fn = set_directory_fn,
                    doc="""<i>(Used only when filtering using rules)</i>
                    <br>The name of the file holding the rules. Each line of
                    this file should be a rule naming a measurement to be made
                    on an image, for instance:<pre>IF (Image_ImageQuality_PowerLogLogSlope_DNA &lt; -2.5, [0.79, -0.79], [-0.94, 0.94])</pre><br><br>
                    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.
                    <p>Note that if the rules are obtained from CellProfiler Analyst, the images
                    that are fail are those represented by the second number between the brackets.</p>"""))

        group.append("measurement", cps.Measurement("Which measurement?",
                                                    object_fn))
        group.append("wants_minimum",
                     cps.Binary("Flag images based on low values?",
                                True, doc = '''Images with measurements below this cutoff will be flagged.'''))
        group.append("minimum_value", cps.Float("Minimum value", 0))
        group.append("wants_maximum",
                     cps.Binary("Flag images based on high values?",
                                True, doc = '''Images with measurements above this cutoff will be flagged.'''))
        group.append("maximum_value", cps.Float("Maximum value", 1))
        
        if can_delete:
            group.append("remover", cps.RemoveSettingButton("", "Remove this measurement", measurement_settings, group))
            
        group.append("divider2", cps.Divider(line=True))
        measurement_settings.append(group)
Esempio n. 9
0
    def create_settings(self):
        '''Create the settings for the module'''
        self.images = []

        self.objects_name = cps.ObjectNameSubscriber(
            'Select the input untangled worm objects', 'OverlappingWorms',
            doc = """This is the name of the objects produced by the
            <b>UntangleWorms</b> module. <b>StraightenWorms</b> can use
            either the overlapping or non-overlapping objects as input. It
            will use the control point measurements associated with the objects
            to reconstruct the straight worms. You can also use objects
            saved from a previous run and loaded via <b>LoadImages</b>, objects
            edited using <b>EditObjectsManually</b> or objects from one
            of the Identify modulues. <b>StraightenWorms</b>
            will recalculate the control points for these images.""")

        self.straightened_objects_name = cps.ObjectNameProvider(
            "Name the output straightened worm objects", "StraightenedWorms",
            doc = """This is the name that will be given to the straightened
            worm objects. These objects can then be used in a subsequent
            measurement module.""")
        
        self.width = cps.Integer(
            "Worm width", 20, minval = 3,
            doc = """This setting determines the width of the image of each
            worm. The width should be set to at least the maximum width of
            any untangled worm, but can be set to be larger to include the
            worm's background in the straightened image.""")
        
        self.training_set_directory = cps.DirectoryPath(
            "Training set file location", support_urls = True,
            allow_metadata = False,
            doc = """Select the folder containing the training set to be loaded.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s
            <p>An additional option is the following:
            <ul>
            <li><i>URL</i>: Use the path part of a URL. For instance, your
            training set might be hosted at 
            <i>http://university.edu/~johndoe/TrainingSet.mat</i>
            To access this file, you would choose <i>URL</i> and enter
            <i>https://svn.broadinstitute.org/CellProfiler/trunk/ExampleImages/ExampleSBSImages</i>
            as the path location.</li>
            </ul></p>"""%globals())
        def get_directory_fn():
            '''Get the directory for the CSV file name'''
            return self.training_set_directory.get_absolute_path()
        def set_directory_fn(path):
            dir_choice, custom_path = self.training_set_directory.get_parts_from_path(path)
            self.training_set_directory.join_parts(dir_choice, custom_path)
            
        self.training_set_file_name = cps.FilenameText(
            "Training set file name", "TrainingSet.mat",
            doc = "This is the name of the training set file.",
            get_directory_fn = get_directory_fn,
            set_directory_fn = set_directory_fn,
            browse_msg = "Choose training set",
            exts = [("Worm training set (*.xml)", "*.xml"),
                    ("All files (*.*)", "*.*")])
        
        self.wants_measurements = cps.Binary(
            "Measure intensity distribution?", True,
            doc = """<b>StraightenWorms</b> can divide a worm into sections
            and measure the intensities of each section in each of the
            straightened images. These measurements can help classify
            phenotypes if the staining pattern across the segments differs
            between phenotypes.""")
        
        self.number_of_segments = cps.Integer(
            "Number of transverse segments", 4, 1,
            doc = """(<i>Only displayed if intensities are measured</i>)<br>
            This setting controls the number of segments measured, dividing
            the worm longitudally into transverse segments starting at the head 
            and ending at the tail.
            These measurements might be used to identify a phenotype in which
            a stain is localized longitudally, for instance, in the head.
            
            Set the number of vertical segments to 1 to only measure intensity
            in the horizontal direction.""")

        self.number_of_stripes = cps.Integer(
            "Number of longitudinal stripes", 3, 1,
            doc = """(<i>Only displayed if intensities are measured</i>)<br>
            This setting controls the number of stripes measured, dividing
            the worm transversely into areas that run longitudally. These
            measurements might be used to identify a phenotype in which a
            stain is localized transversely, for instance in the gut of the
            worm.
            
            Set the number of horizontal stripes to 1 to only measure intensity
            in the vertical direction.""")
        
        self.flip_worms = cps.Choice(
            "Align worms?", [FLIP_NONE, FLIP_TOP, FLIP_BOTTOM],
            doc = """(<i>Only displayed if intensities are measured</i>)<br>
            <b>StraightenWorms</b> can align worms so that the brightest
            half of the worm (the half with the highest mean intensity) is
            at the top of the image or at the bottom of the image. This
            can be used to align all worms similarly if some feature,
            such as the larynx, is stained and is always at the same end
            of the worm. Choose <i>%(FLIP_TOP)s</i> if the brightest part of the
            worm should be at the top of the image, <i>%(FLIP_BOTTOM)s</i> if the
            brightest part of the worm should be at the bottom or
            <i>%(FLIP_NONE)s</i> if the worm should not be aligned."""%globals())
        
        def image_choices_fn(pipeline):
            '''Return the image choices for the alignment image'''
            return [ group.image_name.value
                     for group in self.images ]
        
        self.flip_image = cps.Choice(
            "Alignment image", [ "None" ], choices_fn = image_choices_fn,
            doc = """(<i>Only displayed if aligning worms</i>)<br>
            This is the image whose intensity will be used to align the worms.
            You must use one of the straightened images below.""")
        
        
        self.image_count = cps.HiddenCount(self.images, "Image count")
        
        self.add_image(False)
        
        self.add_image_button = cps.DoSomething(
            "", "Add another image", self.add_image,
            doc = """Press this button to add another image to be straightened""")
Esempio n. 10
0
    def create_settings(self):
        '''Create the initial settings and name the module'''
        self.target_name = cps.ObjectNameProvider('Name the output objects',
                                                  'FilteredBlue',
                                                  doc="""
                                What do you want to call the filtered objects? This will be the name for 
                                the collection of objects that are retained after applying the filter(s)."""
                                                  )

        self.object_name = cps.ObjectNameSubscriber(
            'Select the object to filter',
            'None',
            doc="""
                                What object would you like to filter? This setting 
                                also controls which measurement choices appear for filtering:
                                you can only filter based on measurements made on the object you select.
                                If you intend to use a measurement 
                                calculated by the <b>CalculateMath</b> module to to filter objects, select
                                the first operand's object here, because <b>CalculateMath</b> measurements
                                are stored with the first operand's object.""")

        self.spacer_1 = cps.Divider(line=False)

        self.rules_or_measurement = cps.Choice(
            'Filter using classifier rules or measurements?',
            [ROM_MEASUREMENTS, ROM_RULES],
            doc="""You can choose either a measurement made on the objects or
            a rules file produced by CellProfiler Analyst. If you choose
            <i>Rules</i>, you will have to ensure that this pipeline makes every
            measurement in that rules file.""")
        self.spacer_2 = cps.Divider(line=False)

        self.measurements = []
        self.measurement_count = cps.HiddenCount(self.measurements,
                                                 "Measurement count")
        self.add_measurement(False)
        self.add_measurement_button = cps.DoSomething(
            "Add another measurement", "Add", self.add_measurement)
        self.filter_choice = cps.Choice("Select the filtering method",
                                        FI_ALL,
                                        FI_LIMITS,
                                        doc="""
                                <i>(Used only if filtering using measurements)</i><br>
                                There are five different ways to filter objects:
                                <ul>
                                <li><i>Limits:</i> Keep an object if its measurement value falls within a range you specify.</li> 
                                <li><i>Maximal:</i> Keep the object with the maximum value for the measurement
                                of interest. If multiple objects share a maximal value, retain one object 
                                selected arbitrarily per image.</li>
                                <li><i>Minimal:</i> Keep the object with the minimum value for the measurement
                                of interest. If multiple objects share a minimal value, retain one object 
                                selected arbitrarily per image.</li>
                                <li><i>Maximal per object:</i> This option requires you to choose a parent object.
                                The parent object might contain several child objects of
                                choice (for instance, mitotic spindles within a cell or FISH
                                probe spots within a nucleus). Only the child object whose measurements equal the maximum child-measurement
                                value among that set of child objects will be kept 
                                (for example, the longest spindle
                                in each cell).  You do not have to explicitly relate objects before using this module.</li>
                                <li><i>Minimal per object:</i> Same as <i>Maximal per object</i>, except filtering is based on the minimum value.</li>
                                </ul>""")

        self.enclosing_object_name = cps.ObjectNameSubscriber(
            'Select the objects that contain the filtered objects',
            'None',
            doc="""
                                <i>(Used only if a per-object filtering method is selected)</i><br>
                                This setting selects the container (i.e., parent) objects for the <i>Maximal per object</i> 
                                and <i>Minimal per object</i> filtering choices."""
        )

        self.rules_directory = cps.DirectoryPath(
            "Rules file location",
            doc="""<i>(Used only when filtering by rules)</i>
            <br>
            Select the location of the rules file that will be used for filtering.
            %(IO_FOLDER_CHOICE_HELP_TEXT)s""" % globals())

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

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

        self.rules_file_name = cps.FilenameText(
            "Rules file name",
            "rules.txt",
            get_directory_fn=get_directory_fn,
            set_directory_fn=set_directory_fn,
            doc="""<i>(Used only when filtering using rules)</i>
            <br>The name of the file holding the rules. Each line of
            this file should be a rule naming a measurement to be made
            on the object you selected, for instance:
            <br><tt>
            IF (Nuclei_AreaShape_Area < 351.3, [0.79, -0.79], [-0.94, 0.94])
            </tt><br>
            The above rule will score +.79 for the positive category and -0.94
            for the negative category for nuclei whose area is less than 351.3 
            pixels and will score the opposite for nuclei whose area is larger.
            The filter adds positive and negative and keeps only objects whose
            positive score is higher than the negative score""")

        self.wants_outlines = cps.Binary(
            'Retain outlines of the identified objects?', False)

        self.outlines_name = cps.OutlineNameProvider('Name the outline image',
                                                     'FilteredObjects',
                                                     doc='''
                                 <i>(Used only if the outline image is to be retained for later use in the  
                                 pipeline)</i> <br> Choose a name by which the outline image can be 
                                 selected later in the pipeline.
                                 <p><i>Special note on saving images:</i> You can use the settings in this module
                                 to pass object outlines along to the module <b>OverlayOutlines</b>, and then save
                                 them with the <b>SaveImages</b> module. Also, the identified objects themselves
                                 can be passed along to the object processing module <b>ConvertToImage</b>
                                 and then saved with the <b>SaveImages</b> module.'''
                                                     )
        self.additional_objects = []
        self.additional_object_count = cps.HiddenCount(
            self.additional_objects, "Additional object count")
        self.spacer_3 = cps.Divider(line=False)

        self.additional_object_button = cps.DoSomething(
            'Relabel additional objects to match the filtered object?',
            'Add an additional object',
            self.add_additional_object,
            doc="""
                                Click this button to add an object to receive the same post-filtering labels as
                                the filtered object. This is useful in making sure that labeling is maintained 
                                between related objects (e.g., primary and secondary objects) after filtering."""
        )