def add_mapping(self):
        group = cps.SettingsGroup()
        group.append("local_directory",
                     cps.Text("Local root path",
                                cpprefs.get_default_image_directory(),doc="""
                                What is the path to files on this computer? 
                                This is the root path on the local machine (i.e., the computer setting up
                                the batch files). If <b>CreateBatchFiles</b> finds
                                any pathname that matches the local root path at the begining, it will replace the
                                start with the cluster root path.
                                <p>For example, if you have mapped the remote cluster machine like this:<br><br>
                                <tt>Z:\your_data\images</tt> (on a Windows machine, for instance)<br><br>
                                and the cluster machine sees the same folder like this:<br><br>
                                <tt>/server_name/your_name/your_data/images</tt><br><br>
                                you would enter <tt>Z:</tt> here and <t>/server_name/your_name/</tt> 
                                for the cluster path in the next setting."""))

        group.append("remote_directory",
                     cps.Text("Cluster root path",
                                cpprefs.get_default_image_directory(),doc="""
                                What is the path to files on the cluster? This is the cluster 
                                root path, i.e., how the cluster machine sees the
                                top-most folder where your input/output files are stored.
                                <p>For example, if you have mapped the remote cluster machine like this:<br><br>
                                <tt>Z:\your_data\images</tt> (on a Windows machine, for instance)<br><br>
                                and the cluster machine sees the same folder like this:<br><br>
                                <tt>/server_name/your_name/your_data/images</tt><br><br>
                                you would enter <tt>Z:</tt> in the previous setting for the
                                local machine path and <t>/server_name/your_name/</tt> here. """))
        group.append("remover",
                     cps.RemoveSettingButton("", "Remove this path mapping", self.mappings, group))
        group.append("divider", cps.Divider(line=False))
        self.mappings.append(group)
Example #2
0
 def add_flag(self, can_delete=True):
     group = cps.SettingsGroup()
     group.append("divider1", cps.Divider(line=False))
     group.append("measurement_settings", [])
     group.append("measurement_count", cps.HiddenCount(group.measurement_settings))
     group.append("category", cps.Text("Name the flag's category","Metadata", doc = '''
                             Name a measurement category in which the flag should reside. Metadata allows you to 
                             later group images in the <b>LoadImages</b> module based on the flag, if you load the 
                             flag data in a future pipeline via the <b>LoadData</b> module.  Otherwise, you might 
                             choose to have the flag stored in the "Image" category or using some other word you prefer.  
                             The flag is stored as a per-image measurement whose name is a combination of the
                             flag's category and feature name, underscore delimited. 
                             For instance, if the measurement category is
                             "Metadata" and the feature name is "QCFlag", then the default
                             measurement name would be "Metadata_QCFlag". %s'''%USING_METADATA_HELP_REF))
     
     group.append("feature_name", cps.Text("Name the flag","QCFlag", doc = '''
                             The flag is stored as a per-image measurement whose name is a combination of the
                             flag's category and feature name, underscore delimited. 
                             For instance, if the measurement category is
                             "Metadata" and the feature name is "QCFlag", then the default
                             measurement name would be "Metadata_QCFlag".'''))
     
     group.append("combination_choice", cps.Choice("Flag if any, or all, measurement(s) fails to meet the criteria?",
                             [ C_ANY, C_ALL], doc = '''
                             <ul>
                             <li><i>Any:</i> An image will be flagged if any of its measurements fail. This can be useful
                             for flagging images possessing multiple QC flaws; for example, you can flag all bright images and all out of focus images with one flag.</li>
                             <li><i>All:</i> A flag will only be assigned if all measurements fail.  This can be useful for flagging  images that possess only a combination
                             of QC flaws; for example, you can flag only images that are both bright and out of focus.</li>
                             </ul>'''))
     
     group.append(
         "wants_skip", cps.Binary("Skip image set if flagged?", False,
         doc = """You can skip the remainder of the pipeline for image sets
         that are flagged by checking this setting. If you check this
         setting, CellProfiler will not run subsequent modules in the
         pipeline on the images in any image set that is flagged. 
         CellProfiler will continue to process the pipeline if you leave
         the setting unchecked.<p>
         You may want to check this setting in order to filter out
         unwanted images during processing. For instance, you may want
         to exclude out of focus images when running 
         <b>CorrectIllumination_Calculate</b>. You can do this with a
         pipeline that measures image quality and flags inappropriate
         images before it runs <b>CorrectIllumination_Calculate</b>"""))
         
     group.append("add_measurement_button", 
                  cps.DoSomething("",
                                  "Add another measurement",
                                  self.add_measurement, group))
     self.add_measurement(group, False if not can_delete else True)
     if can_delete:
         group.append("remover", cps.RemoveSettingButton("", "Remove this flag", self.flags, group))
     group.append("divider2", cps.Divider(line=True))
     self.flags.append(group)
Example #3
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  cps.NONE,
                                                  doc='''
            Select the image to be resized.''')

        self.cropped_image_name = cps.ImageNameProvider(
            "Name the output image",
            "croppedImage",
            doc='''
            Enter the name of the cropped image.''')

        self.crop_random = cps.Choice('Crop random or specified section?',
                                      [C_RANDOM, C_SPECIFIC])

        self.crop_x = cps.Text("X of upper left corner",
                               '0',
                               doc='''
            X position.''',
                               metadata=True)

        self.crop_y = cps.Text("Y of upper left corner",
                               '0',
                               doc='''
            Y position.''',
                               metadata=True)

        self.crop_w = cps.Text("W width",
                               '100',
                               doc='''
            Width of cut.''',
                               metadata=True)

        self.crop_h = cps.Text("H height",
                               '100',
                               doc='''
            Height of cut.''',
                               metadata=True)

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

        self.additional_images = []

        self.additional_image_count = cps.HiddenCount(
            self.additional_images, "Additional image count")

        self.add_button = cps.DoSomething("", "Add another image",
                                          self.add_image)
Example #4
0
    def create_settings(self):
        self.image_name = cps.ImageNameSubscriber("Select the input image",
                                                  cps.NONE)

        self.conversion_method = cps.Choice("Conversion method",
                                            [MEAN, MEDIAN, CUSTOMFUNCTION],
                                            doc='''
            How do you want to summarize the multichannel image?
            <ul>
            <li><i>%(MEAN)s:</i> Takes the mean.</li>
            <li><i>%(MEDIAN)s</i> Takes the median</li>
            <li><i>%(MEDIAN)s</i> Applies a cutstom python function</li>
            </ul>''' % globals())

        self.custom_function = cps.Text("Input a Python function",
                                        'np.mean',
                                        doc='''
        Can be a simple function as "np.max" (without ") or complicated as "functools.partial(np.percentile,q=80, axis=2)".
        functools is imported as convenience.
        ''')
        # The following settings are used for the combine option
        self.grayscale_name = cps.ImageNameProvider("Name the output image",
                                                    "OrigGray")

        # The alternative model:
        self.channels = []
 def create_settings(self): # "self" refers to the module's class attributes
     self.text_setting = cps.Text("Text setting", "suggested value")
     self.choice_setting = cps.Choice(
         "Choice setting", ["Choice 1", "Choice 2", "Choice 3"])
     self.binary_setting = cps.Binary("Binary setting", False)
     self.integer_setting = cps.Integer("Integer setting", 15)
     self.float_setting = cps.Float("Float setting", 1.5)
Example #6
0
    def create_settings(self):
        '''Create the module settings and name the module'''
        self.wants_default_output_directory = cps.Binary(
            "Store batch files in default output folder?",
            True,
            doc="""
            Check this box to store batch files in the Default Output folder. Uncheck
            the box to enter the path to the folder that will be used to store
            these files.""")

        self.custom_output_directory = cps.Text(
            "Output folder path",
            cpprefs.get_default_output_directory(),
            doc="""
            Enter the path to the output folder.""")

        # Worded this way not because I am windows-centric but because it's
        # easier than listing every other OS in the universe except for VMS
        self.remote_host_is_windows = cps.Binary(
            "Are the cluster computers running Windows?",
            False,
            doc="""
            Check this box if the cluster computers are running one of the Microsoft
            Windows operating systems. If you check this box, <b>CreateBatchFiles</b> will
            modify all paths to use the Windows file separator (backslash &#92;). If you
            leave the box unchecked, <b>CreateBatchFiles</b> will modify all paths to use
            the Unix or Macintosh file separator (slash &#47;).""")

        self.batch_mode = cps.Binary("Hidden: in batch mode", False)
        self.distributed_mode = cps.Binary("Hidden: in distributed mode",
                                           False)
        self.default_image_directory = cps.Setting(
            "Hidden: default input folder at time of save",
            cpprefs.get_default_image_directory())
        self.revision = cps.Integer("Hidden: revision number", 0)
        self.from_old_matlab = cps.Binary("Hidden: from old matlab", False)
        self.acknowledge_old_matlab = cps.DoSomething(
            "Could not update CP1.0 pipeline to be compatible with CP2.0.  See module notes.",
            "OK", self.clear_old_matlab)
        self.mappings = []
        self.add_mapping()
        self.add_mapping_button = cps.DoSomething("",
                                                  "Add another path mapping",
                                                  self.add_mapping,
                                                  doc="""
            Use this option if another path must be mapped because there is a difference 
            between how the local computer sees a folder location vs. how the cluster 
            computer sees the folder location.""")

        self.check_path_button = cps.DoSomething(
            "Press this button to check pathnames on the remote server",
            "Check paths",
            self.check_paths,
            doc="""
            his button will start a routine that will ask the
            webserver to check whether the default input and default output
            folders exist. It will also check whether all remote
            path mappings exist.""")
    def add_object_group(self, can_remove=True):
        group = cps.SettingsGroup()
        group.append(
            "name",
            EEObjectNameSubscriber(
                "Data to export",
                doc=
                """<i>(Used only when Export all measurements? is left unchecked)</i><br>
            Choose <i>Image</i>, <i>Experiment</i>, <i>Object relationships</i> 
            or an object name from the list. <b>ExportToSpreadsheet</b> will write out a
            file of measurements for the given category."""))

        group.append(
            "previous_file",
            cps.Binary(
                "Combine these object measurements with those of the previous object?",
                False,
                doc=
                """<i>(Used only when Export all measurements? is left unchecked)</i><br>Check this setting to create a file composed
                of measurements made on this object and the one directly
                above it. Leave the box unchecked to create separate
                files for this and the previous object."""))

        group.append(
            "wants_automatic_file_name",
            cps.Binary(
                "Use the object name for the file name?",
                True,
                doc=
                """<i>(Used only when Export all measurements? is left unchecked)</i><br>Use the object name as selected above to generate a file
            name for the spreadsheet. For example, if you selected <i>Image</i>,
            above and have not checked the <i>Prepend output file name</i> option,
            your output file will be named "Image.csv". You can name
            the file yourself if you leave this box unchecked."""))

        group.append(
            "file_name",
            cps.Text(
                "File name",
                "DATA.csv",
                metadata=True,
                doc=
                """<i>(Used only when Export all measurements? is left unchecked)</i><br>Enter a file name for the named objects' 
                         measurements. <b>ExportToSpreadsheet</b> will
                         prepend the name of the measurements file to this
                         if you asked to do so above. If you have metadata 
                         associated with your images, this setting will also substitute
                         metadata tags if desired. %(USING_METADATA_TAGS_REF)s%(USING_METADATA_HELP_REF)s."""
                % globals()))

        group.append(
            "remover",
            cps.RemoveSettingButton("", "Remove this data set",
                                    self.object_groups, group))
        group.append("divider", cps.Divider(line=False))

        self.object_groups.append(group)
Example #8
0
 def add_when(self, can_delete = True):
     group = cps.SettingsGroup()
     group.append("choice", cps.Choice(
         "When should the email be sent?", S_ALL,
         doc="""Select the kind of event that causes
         <b>SendEmail</b> to send an email. You have the following choices:
         <br><ul><li><i>After first cycle:</i> Send an email during
         processing of the first image cycle.</li>
         <li><i>After last cycle:</i> Send an email after all processing
         is complete.</li>
         <li><i>After group start:</i> Send an email during the first
         cycle of each group of images.</li>
         <li><i>After group end:</i> Send an email after all processing
         for a group is complete.</li>
         <li><i>Every # of cycles</i> Send an email each time a certain
         number of image cycles have been processed. You will be prompted
         for the number of image cycles if you select this choice.</li>
         <li><i>After cycle #:</i> Send an email after the given number
         of image cycles have been processed. You will be prompted for
         the image cycle number if you select this choice. You can add
         more events if you want emails after more than one image cycle.</li>
         </ul>"""))
     
     group.append("image_set_number", cps.Integer(
         "Image cycle number", 1, minval = 1,
         doc='''
         <i>(Used only if sending email after a particular cycle number)</i><br>
         Send an email during processing of the given image cycle.
         For instance, if you enter 4, then <b>SendEmail</b>
         will send an email during processing of the fourth image cycle.'''))
     
     group.append("image_set_count", cps.Integer(
         "Image cycle count", 1, minval = 1,
         doc='''
         <i>(Used only if sending email after every N cycles)</i><br>
         Send an email each time this number of image cycles have
         been processed. For instance, if you enter 4,
         then <b>SendEmail</b> will send an email during processing of
         the fourth, eighth, twelfth, etc. image cycles.'''))
     
     group.append("message", cps.Text(
         "Message text","Notification from CellProfiler",
         metadata=True,
         doc="""The body of the message sent from CellProfiler.
         Your message can include metadata values. For instance,
         if you group by plate and want to send an email after processing each
         plate, you could use the message  
         "Finished processing plate \\g<Plate>". """))
     
     if can_delete:
         group.append("remover", cps.RemoveSettingButton(
             "Remove this email event", "Remove event", self.when, group))
     group.append("divider", cps.Divider())
     self.when.append(group)
    def create_settings(self):
        self.omero_host = cps.Text(
            "Host address",
            DEFAULT_OMERO_HOST,
            doc=
            """Host address of an omero server. Can be an ip-address or a hostname."""
        )
        self.omero_port = cps.Integer("Port",
                                      DEFAULT_OMERO_PORT,
                                      doc="""Port of an omero server.""")
        self.omero_username = cps.Text(
            "Username",
            DEFAULT_OMERO_USERNAME,
            doc="""Username is required for login into an omero server.""")
        self.omero_password = cps.Text(
            "Password",
            DEFAULT_OMERO_PASSWORD,
            doc="""Password is required for login into an omero server.""")
        self.omero_object = cps.Choice("Object to load",
                                       [MS_IMAGE, MS_DATASET, MS_PLATE],
                                       DEFAULT_OMERO_OBJECT)
        self.omero_object_id = cps.Integer(
            "Object id",
            DEFAULT_OMERO_OBJECT_ID,
            doc=
            """This is a number that omero uses to uniquely identify an object, be it a dataset, plate, or image."""
        )
        self.load_channels = cps.DoSomething("", "Load channels from OMERO",
                                             self.load_channels)

        # All the omero images that are loaded are assumed to have
        # as many or more channels than the highest channel number
        # the user specifies.
        self.channels = []
        self.channel_count = cps.HiddenCount(self.channels, "Channel count")
        # Add the first channel
        self.add_channelfn(False)

        # Button for adding other channels
        self.add_channel = cps.DoSomething("", "Add another channel",
                                           self.add_channelfn)
Example #10
0
 def test_01_01_display_text_setting(self):
     v=cps.Text("text","value")
     app,text_control,edit_control = self.set_setting(v)
     self.assertEqual(text_control.Label,"text")
     self.assertTrue(isinstance(text_control, wx.StaticText))
     self.assertEqual(edit_control.Value,"value")
     self.assertTrue(isinstance(edit_control,wx.TextCtrl))
     edit_control.SetValue("abc")
     app.ProcessPendingEvents()
     self.assertEqual(v.value,"abc")
     app.frame.Destroy()
     app.ProcessPendingEvents()
     app.ProcessIdle()
Example #11
0
 def add_recipient(self, can_delete = True):
     '''Add a recipient for the email to the list of emails'''
     group = cps.SettingsGroup()
     group.append("recipient", cps.Text(
         "Recipient address","recipient@domain",
         doc="""Enter the address to which the messages will be sent."""))
     if can_delete:
         group.append("remover", cps.RemoveSettingButton(
             "Remove above recipient", "Remove recipient", 
             self.recipients, group,
             doc="""Press this button to remove the above recipient from
             the list of people to receive the email"""))
     self.recipients.append(group)
    def add_image(self):
        def default_cpimage_name(index):
            # the usual suspects
            names = ['DNA', 'Actin', 'Protein']
            if index < len(names):
                return names[index]
            return 'Channel%d' % (index + 1)

        group = cps.SettingsGroup()
        group.append(
            "image_name",
            cps.FileImageNameProvider('Name of this image in CellProfiler',
                                      default_cpimage_name(len(self.images)),
                                      doc="""
                        Give your images a meaningful name that you will use when referring to
                        these images in later modules.  Keep the following points in mind when deciding 
                        on an image name:
                        <ul>
                        <li>Image names must begin with a letter, which may be followed by any 
                        combination of letters, digits, and underscores. The following names are all invalid:
                        <ul>
                        <li>My.Cells</li>
                        <li>1stCells</li>
                        <li>1+1=3</li>
                        <li>@MyCell</li>
                        </ul>
                        </li>
                        <li>Names are not case senstive. Therefore, <i>OrigBlue</i>, <i>origblue</i>, and <i>ORIGBLUE</i>
                        will correspond to the same name, and unexpected results may ensue.</li>
                        <li>Although the names can be of any length in CellProfiler, you may want to avoid 
                        making the name too long especially if you are uploading to a database. The name is used
                        to generate the column header for a given measurement, and in MySQL, the total bytes used
                        for the column headers cannot exceed 64K. A warning will be generated later if this limit
                        has been exceeded.</li>
                        </ul>"""))
        group.append("image_specifier",
                     cps.Text("What substring is common to these images?", ""))
        group.append(
            "remover",
            cps.RemoveSettingButton("", "Remove this image", self.images,
                                    group))
        group.append("divider", cps.Divider(line=False))
        self.images.append(group)
Example #13
0
    def create_settings(self):
        self.input_type = cps.Choice("Select the type of input",
                                     [IF_IMAGE, IF_OBJECTS], IF_IMAGE)

        self.image_name = cps.ImageNameSubscriber("Select input images",
                                                  cps.NONE)

        self.objects_name = cps.ObjectNameSubscriber(
            "Select the input objects",
            cps.NONE,
        )

        self.output_name = cps.ImageNameProvider(
            "Input the output image stack name",
            "BinStack",
            doc="""
            Input the output name.
            """ % globals())

        self.main_object_def = cps.Choice(
            "How should the main label be determined?",
            [SEL_MID, SEL_MAXAREA, SEL_PROVIDED],
            SEL_MID,
            doc="""
            The main object can be determined by 3 ways:
            <ul>
            <li> %(SEL_PROVIDED)s: Label provided by metadata or
            manual. <\li>
            <li> %(SEL_MAXAREA)s: Label with the biggest area is assumed to be
            the main label. <\li>
            <li> %(SEL_MID)s: The label closest to the middle of the image is
            considered the main label. <\li>
            <\ul>
            """ % globals())

        self.main_object_id = cps.Text("Indicate the object id",
                                       '1',
                                       doc="""
                Indicates the id from the main object.
                Rightclick to choose a metadata value.
                """ % globals(),
                                       metadata=True)
Example #14
0
 def create_settings(self): # "self" refers to the module's class attributes
     self.text_setting = cps.Text(
         "Text setting", "suggested value",
     ##    doc = "This is the help for the text setting"
     )
     self.choice_setting = cps.Choice(
         "Choice setting", ["Choice 1", "Choice 2", "Choice 3"],
     ##    doc = "This is the help for the choice setting"
     )
     self.binary_setting = cps.Binary(
         "Binary setting", False,
     ##    doc = "This is the help for the binary setting"
     )
     self.integer_setting = cps.Integer(
         "Integer setting", 15,
     ##    doc = "This is the help for the integer setting"
     )
     self.float_setting = cps.Float(
         "Float setting", 1.5,
         doc = "This is the help for the float setting")
Example #15
0
    def create_settings(self):
        '''Create the UI settings for this module'''

        self.recipients = []
        self.recipient_count = cps.HiddenCount(self.recipients)
        self.add_recipient(False)
        self.add_recipient_button = cps.DoSomething("Add a recipient address.",
                                                    "Add address",
                                                    self.add_recipient)

        if sys.platform.startswith("win"):
            user = os.environ.get("USERNAME", "yourname@yourdomain")
        else:
            user = os.environ.get("USER", "yourname@yourdomain")

        self.from_address = cps.Text("Sender address",
                                     user,
                                     doc="""
            Enter the address for the email's "From" field.""")

        self.subject = cps.Text("Subject line",
                                "CellProfiler notification",
                                metadata=True,
                                doc="""
            Enter the text for the email's subject line. If you have metadata 
            associated with your images, you can use metadata tags here. %(USING_METADATA_TAGS_REF)s<br>
            For instance, if you have plate metadata,
            you might use the line, "CellProfiler: processing plate " and insert the metadata tag
            for the plate at the end. %(USING_METADATA_HELP_REF)s.""" %
                                globals())

        self.smtp_server = cps.Text("Server name",
                                    "mail",
                                    doc="""
            Enter the address of your SMTP server. You can ask your
            network administrator for your outgoing mail server which is often
            made up of part of your email address, e.g., 
            "*****@*****.**". You might be able to find this information
            by checking your settings or preferences in whatever email program
            you use.""")

        self.port = cps.Integer("Port",
                                smtplib.SMTP_PORT,
                                0,
                                65535,
                                doc="""
            Enter your server's SMTP port. The default (25) is the
            port used by most SMTP servers. Your network administrator may
            have set up SMTP to use a different port; also, the connection
            security settings may require a different port.""")

        self.connection_security = cps.Choice("Select connection security",
                                              C_ALL,
                                              doc="""
            Select the connection security. Your network administrator 
            can tell you which setting is appropriate, or you can check the
            settings on your favorite email program.""")

        self.use_authentication = cps.Binary(
            "Username and password required to login?",
            False,
            doc="""
            Select <i>%(YES)s</i> if you need to enter a username and password 
            to authenticate.""" % globals())

        self.username = cps.Text("Username",
                                 user,
                                 doc="""
            Enter your server's SMTP username.""")

        self.password = cps.Text("Password",
                                 "",
                                 doc="""
            Enter your server's SMTP password.""")

        self.when = []
        self.when_count = cps.HiddenCount(self.when)
        self.add_when(False)

        self.add_when_button = cps.DoSomething("Add another email event",
                                               "Add email event",
                                               self.add_when,
                                               doc="""
            Press this button to add another event or condition.
            <b>SendEmail</b> will send an email when this event happens""")
Example #16
0
    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 = cps.SettingsGroup()
        if can_delete:
            group.append("divider", cps.Divider(line=True))

        group.append(
            "object_name",
            cps.ObjectNameSubscriber(
                "Select the object to be classified",
                cps.NONE,
                doc="""The name of the objects to be classified. You can
            choose from objects created by any previous module. See
            <b>IdentifyPrimaryObjects</b>, <b>IdentifySecondaryObjects</b>, or
            <b>IdentifyTertiaryObjects</b>."""))

        def object_fn():
            return group.object_name.value

        group.append(
            "measurement",
            cps.Measurement("Select the measurement to classify by",
                            object_fn,
                            doc="""
            Select a measurement made by a previous module. The objects
            will be classified according to their values for this
            measurement."""))

        group.append(
            "bin_choice",
            cps.Choice("Select bin spacing", [BC_EVEN, BC_CUSTOM],
                       doc="""
            Select how you want to define the spacing of the bins.
            You have the following options:
            <ul>
            <li><i>%(BC_EVEN)s:</i> 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.</li>
            <li><i>%(BC_CUSTOM)s:</i> 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.</li>
            </ul>
            """ % globals()))

        group.append(
            "bin_count",
            cps.Integer("Number of bins",
                        3,
                        minval=1,
                        doc="""
            This is the number of bins that will be created between
            the low and high threshold"""))

        group.append(
            "low_threshold",
            cps.Float("Lower threshold",
                      0,
                      doc="""
            <i>(Used only if "%(BC_EVEN)s" selected)</i><br>
            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",
            cps.Binary("Use a bin for objects below the threshold?",
                       False,
                       doc="""
            Select <i>%(YES)s</i> if you want to create a bin for objects
            whose values fall below the low threshold. Select <i>%(NO)s</i>
            if you do not want a bin for these objects.
            """ % globals()))

        def min_upper_threshold():
            return group.low_threshold.value + np.finfo(float).eps

        group.append(
            "high_threshold",
            cps.Float("Upper threshold",
                      1,
                      minval=cps.NumberConnector(min_upper_threshold),
                      doc="""
            <i>(Used only if "%(BC_EVEN)s" selected)</i><br>
            This is the threshold that separates the last bin from
            the others.
            <i>Note:</i> If you would like two bins, you should select <i>%(BC_CUSTOM)s</i>.
            """ % globals()))

        group.append(
            "wants_high_bin",
            cps.Binary("Use a bin for objects above the threshold?",
                       False,
                       doc="""
            Select <i>%(YES)s</i> if you want to create a bin for objects
            whose values are above the high threshold. <br>
            Select <i>%(NO)s</i> if you do not want a bin for these objects."""
                       % globals()))

        group.append(
            "custom_thresholds",
            cps.Text(
                "Enter the custom thresholds separating the values between bins",
                "0,1",
                doc="""
            <i>(Used only if "%(BC_CUSTOM)s" selected)</i><br>
            This setting establishes the threshold values for the
            bins. You should enter one threshold between each bin, separating
            thresholds with commas (for example, <i>0.3, 1.5, 2.1</i> for four bins).
            The module will create one more bin than there are thresholds.
            """ % globals()))

        group.append(
            "wants_custom_names",
            cps.Binary("Give each bin a name?",
                       False,
                       doc="""
            Select <i>%(YES)s</i> to assign custom names to bins you have
            specified.
            <p>Select <i>%(NO)s</i> for the module to automatically
            assign names based on the measurements and the bin number.""" %
                       globals()))

        group.append(
            "bin_names",
            cps.Text("Enter the bin names separated by commas",
                     cps.NONE,
                     doc="""
            <i>(Used only if Give each bin a name? is checked)</i><br>
            Enter names for each of the bins, separated by commas.
            An example including three bins might be <i>First,Second,Third</i>."""
                     ))

        group.append(
            "wants_images",
            cps.Binary("Retain an image of the classified objects?",
                       False,
                       doc="""
            Select <i>%(YES)s</i> 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 <b>SaveImages</b> module).""" % globals()))

        group.append(
            "image_name",
            cps.ImageNameProvider("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 cps.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 cps.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():
                cps.AlphanumericText.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 cps.ValidationError(
                        'Custom thresholds must be a comma-separated list '
                        'of numbers (example: "1.0, 2.3, 4.5")',
                        group.custom_thresholds)

        group.validate_group = validate_group

        if can_delete:
            group.remove_settings_button = cps.RemoveSettingButton(
                "", "Remove this classification", self.single_measurements,
                group)
        self.single_measurements.append(group)
    def create_settings(self):
        '''Create the UI settings for the module'''
        self.seed_objects_name = cps.ObjectNameSubscriber(
            "Select the seed objects",
            cps.NONE,
            doc="""
            Select the previously identified objects that you want to use as the
            seeds for measuring branches and distances. Branches and trunks are assigned
            per seed object. Seed objects are typically not single points/pixels but 
            instead are usually objects of varying sizes.""")

        self.image_name = cps.ImageNameSubscriber(
            "Select the skeletonized image",
            cps.NONE,
            doc="""
            Select the skeletonized image of the dendrites
            and/or axons as produced by the <b>Morph</b> module's
            <i>Skel</i> operation.""")

        self.wants_branchpoint_image = cps.Binary(
            "Retain the branchpoint image?",
            False,
            doc="""
            Select <i>%(YES)s</i> if you want to save the color image of
            branchpoints and trunks. This is the image that is displayed
            in the output window for this module.""" % globals())

        self.branchpoint_image_name = cps.ImageNameProvider(
            "Name the branchpoint image",
            "BranchpointImage",
            doc="""
            <i>(Used only if a branchpoint image is to be retained)</i><br>
            Enter a name for the branchpoint image here. You can then 
            use this image in a later module, such as <b>SaveImages</b>.""")

        self.wants_to_fill_holes = cps.Binary("Fill small holes?",
                                              True,
                                              doc="""
            The algorithm reskeletonizes the image and this can leave
            artifacts caused by small holes in the image prior to skeletonizing.
            These holes result in false trunks and branchpoints. 
            Select <i>%(YES)s</i> to fill in these small holes prior to skeletonizing."""
                                              % globals())

        self.maximum_hole_size = cps.Integer("Maximum hole size:",
                                             10,
                                             minval=1,
                                             doc="""
            <i>(Used only when filling small holes)</i><br>
            This is the area of the largest hole to fill, measured
            in pixels. The algorithm will fill in any hole whose area is
            this size or smaller.""")

        self.wants_neuron_graph = cps.Binary(
            "Export the neuron graph relationships?",
            False,
            doc="""
            Select <i>%(YES)s</i> to produce an edge file and a vertex
            file that give the relationships between trunks, branchpoints
            and vertices.""" % globals())

        self.intensity_image_name = cps.ImageNameSubscriber("Intensity image",
                                                            cps.NONE,
                                                            doc="""
            Select the image to be used to calculate
            the total intensity along the edges between the vertices.""")

        self.directory = cps.DirectoryPath(
            "File output directory",
            dir_choices=[
                cps.DEFAULT_OUTPUT_FOLDER_NAME, cps.DEFAULT_INPUT_FOLDER_NAME,
                cps.ABSOLUTE_FOLDER_NAME, cps.DEFAULT_OUTPUT_SUBFOLDER_NAME,
                cps.DEFAULT_INPUT_SUBFOLDER_NAME
            ])
        self.directory.dir_choice = cps.DEFAULT_OUTPUT_FOLDER_NAME

        self.vertex_file_name = cps.Text("Vertex file name",
                                         "vertices.csv",
                                         doc="""
            Enter the name of the file that will hold the edge information.
            You can use metadata tags in the file name. 
            <p>Each line of the file
            is a row of comma-separated values. The first row is the header;
            this names the file's columns. Each subsequent row represents
            a vertex in the neuron skeleton graph: either a trunk, 
            a branchpoint or an endpoint.
            The file has the following columns:
            <br><ul>
            <li><i>image_number:</i> The image number of the associated image</li>
            <li><i>vertex_number:</i> The number of the vertex within the image</li>
            <li><i>i:</i> The I coordinate of the vertex.</li>
            <li><i>j:</i> The J coordinate of the vertex.</li>
            <li><i>label:</i> The label of the seed object associated with
            the vertex.</li>
            <li><i>kind:</i> The vertex type, with the following choices:
            <ul><li><b>T:</b> Trunk</li>
            <li><b>B:</b> Branchpoint</li>
            <li><b>E:</b> Endpoint</li></ul></li></ul>
            </p>""")

        self.edge_file_name = cps.Text("Edge file name",
                                       "edges.csv",
                                       doc="""
            Enter the name of the file that will hold the edge information.
            You can use metadata tags in the file name. Each line of the file
            is a row of comma-separated values. The first row is the header;
            this names the file's columns. Each subsequent row represents
            an edge or connection between two vertices (including between
            a vertex and itself for certain loops).
            
            <p>The file has the following columns:
            <br><ul>
            <li><i>image_number:</i> The image number of the associated image</li>
            <li><i>v1:</i> The zero-based index into the vertex
            table of the first vertex in the edge.</li>
            <li><i>v2:</i> The zero-based index into the vertex table of the
            second vertex in the edge.</li>
            <li><i>length:</i> The number of pixels in the path connecting the
            two vertices, including both vertex pixels.</li>
            <li><i>total_intensity:</i> The sum of the intensities of the
            pixels in the edge, including both vertex pixel intensities.</li>
            </ul>
            </p>""")
    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 = cellprofiler.settings.ImageNameSubscriber(...)
            # Ask the user for the name of the output image
            self.output_image = cellprofiler.settings.ImageNameProvider(...)
            # Ask the user for a parameter
            self.smoothing_size = cellprofiler.settings.Float(...)
        """
        self.objects_or_image = cps.Choice(
            "Display object or image measurements?", [OI_OBJECTS, OI_IMAGE],
            doc="""
            <ul>
            <li><i>%(OI_OBJECTS)s</i> displays measurements made on
            objects.</li>
            <li><i>%(OI_IMAGE)s</i> displays a single measurement made
            on an image.</li> 
            </ul>""" % globals())

        self.objects_name = cps.ObjectNameSubscriber(
            "Select the input objects",
            cps.NONE,
            doc="""
            <i>(Used only when displaying object measurements)</i><br>
            Choose the name of objects identified by some previous
            module (such as <b>IdentifyPrimaryObjects</b> or
            <b>IdentifySecondaryObjects</b>).""")

        def object_fn():
            if self.objects_or_image == OI_OBJECTS:
                return self.objects_name.value
            else:
                return cpmeas.IMAGE

        self.measurement = cps.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.image_name = cps.ImageNameSubscriber(
            "Select the image on which to display the measurements",
            cps.NONE,
            doc="""
            Choose the image to be displayed behind the measurements.
            This can be any image created or loaded by a previous module.""")

        self.color_or_text = cps.Choice(
            "Display mode", [CT_TEXT, CT_COLOR],
            doc="""<i>(Used only when displaying object measurements)</i><br>
            Choose how to display the measurement information. If you choose
            %(CT_TEXT)s, <b>DisplayDataOnImage</b> will display the numeric
            value on top of each object. If you choose %(CT_COLOR)s,
            <b>DisplayDataOnImage</b> 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 = cps.Colormap(
            "Color map",
            doc="""<i>(Used only when displaying object measurements)</i><br>
            This is the color map used as the color gradient for coloring the
            objects by their measurement values.
            """)
        self.text_color = cps.Text("Text color",
                                   "red",
                                   doc="""
            This is the color that will be used when displaying the text.
            There are several different ways by which you can specify the color:<br>
            <ul>
            <li><i>Single letter:</i> "b"=blue, "g"=green, "r"=red, "c"=cyan, "m"=magenta,
            "y"=yellow, "k"=black, "w"=white</li>
            <li><i>Name:</i> You can use any name supported by HTML; a list of colors is shown on
            <a href="http://www.w3schools.com/html/html_colors.asp">this page</a>.
            </li>
            <li><i>RGB code:</i> You can specify the color as a combination of
            the red, green, and blue intensities, for instance, "#FFFF00"
            for yellow; yellow = red("FF") + green("FF") + blue("00"), where <i>FF</i> is
            hexadecimal for 255, the highest intensity. See  
            <a href="http://www.w3schools.com/html/html_colors.asp">this page</a> for a more detailed
            explanation.</li>
            </ul>""")

        self.display_image = cps.ImageNameProvider(
            "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 <b>SaveImages</b>).""")

        self.font_size = cps.Integer("Font size (points)", 10, minval=1)

        self.decimals = cps.Integer("Number of decimals", 2, minval=0)

        self.saved_image_contents = cps.Choice("Image elements to save",
                                               [E_IMAGE, E_FIGURE, E_AXES],
                                               doc="""
            This setting controls the level of annotation on the image:
            <ul>
            <li><i>%(E_IMAGE)s:</i> Saves the image with the overlaid measurement annotations.</li>
            <li><i>%(E_AXES)s:</i> Adds axes with tick marks and image coordinates.</li>
            <li><i>%(E_FIGURE)s:</i> Adds a title and other decorations.</li></ul>"""
                                               % globals())

        self.offset = cps.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.""")
Example #19
0
    def create_settings(self):
        #XXX needs to use cps.SettingsGroup
        class Operand(object):
            '''Represents the collection of settings needed by each operand'''
            def __init__(self, index, operation):
                self.__index = index
                self.__operation = operation
                self.__operand_choice = cps.Choice(
                    self.operand_choice_text(), MC_ALL,doc="""
                    Indicate whether the operand is an image or object measurement.""")
                
                self.__operand_objects = cps.ObjectNameSubscriber(
                    self.operand_objects_text(),cps.NONE,doc="""
                    Choose the objects you want to measure for this operation.""")
                
                self.__operand_measurement = cps.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 = cps.Float(
                    "Multiply the above operand by",1,doc="""
                    Enter the number by which you would like to multiply the above operand.""")
                
                self.__exponent = cps.Float(
                    "Raise the power of above operand by",1,doc="""
                    Enter the power by which you would like to raise the above operand.""")
            
            @property
            def operand_choice(self):
                '''Either MC_IMAGE for image measurements or MC_OBJECT for object'''
                return self.__operand_choice
            
            @property
            def operand_objects(self):
                '''Get measurements from these objects'''
                return self.__operand_objects
            
            @property
            def operand_measurement(self):
                '''The measurement providing the value of the operand'''
                return self.__operand_measurement
            
            @property 
            def multiplicand(self):
                '''Premultiply the measurement by this value'''
                return self.__multiplicand
            
            @property
            def exponent(self):
                '''Raise the measurement to this power'''
                return self.__exponent
            
            @property
            def object(self):
                '''The name of the object for measurement or "Image"'''
                if self.operand_choice == MC_IMAGE:
                    return cpmeas.IMAGE
                else:
                    return self.operand_objects.value
                
            def object_fn(self):
                if self.__operand_choice == MC_IMAGE:
                    return cpmeas.IMAGE
                elif self.__operand_choice == MC_OBJECT:
                    return self.__operand_objects.value
                else:
                    raise NotImplementedError("Measurement type %s is not supported"%
                                              self.__operand_choice.value)
            def operand_name(self):
                '''A fancy name based on what operation is being performed'''
                if self.__index == 0:
                    return ("first operand" 
                            if self.__operation in (O_ADD, O_MULTIPLY) else
                            "minuend" if self.__operation == O_SUBTRACT else
                            "numerator")
                elif self.__index == 1:
                    return ("second operand" 
                            if self.__operation in (O_ADD, O_MULTIPLY) else
                            "subtrahend" if self.__operation == O_SUBTRACT  else 
                            "denominator")
            
            def operand_choice_text(self):
                return self.operand_text("Select the %s measurement type") 
            
            def operand_objects_text(self):
                return self.operand_text("Select the %s objects")
            
            def operand_text(self, format):
                return format % self.operand_name()
                
            def operand_measurement_text(self): 
                return self.operand_text("Select the %s measurement")
            
            def settings(self):
                '''The operand settings to be saved in the output file'''
                return [self.operand_choice, self.operand_objects, 
                        self.operand_measurement, self.multiplicand, self.exponent]
            
            def visible_settings(self):
                '''The operand settings to be displayed'''
                self.operand_choice.text = self.operand_choice_text()
                self.operand_objects.text = self.operand_objects_text()
                self.operand_measurement.text = self.operand_measurement_text()
                result = [self.operand_choice]
                result += ([self.operand_objects] if self.operand_choice == MC_OBJECT \
                          else [])
                result += [self.operand_measurement, self.multiplicand, self.exponent]
                return (result)
            
        self.output_feature_name = cps.Text(
            "Name the output measurement",
            "Measurement",doc="""
            Enter a name for the measurement calculated by this module.""")
        
        self.operation = cps.Choice(
            "Operation",
            O_ALL,doc="""
            Choose the arithmetic operation would you like to perform. <i>None</i> is useful if 
            you simply want to select some of the later options in the module, such as multiplying
            or exponentiating your image by a constant.""")
        
        self.operands = (Operand(0, self.operation), Operand(1, self.operation))
        
        self.spacer_1 = cps.Divider(line=True)
                
        self.spacer_2 = cps.Divider(line=True)
        
        self.spacer_3 = cps.Divider(line=True)
        
        self.wants_log = cps.Binary(
            "Take log10 of result?", False,doc="""
            Check this box if you want the log (base 10) of the result.""")
        
        self.final_multiplicand = cps.Float(
            "Multiply the result by",1,doc="""
            <i>(Used only for operations other than None)</i><br>
            Enter the number by which you would like to multiply the result.""")
        
        self.final_exponent = cps.Float(
            "Raise the power of result by",1,doc="""
            <i>(Used only for operations other than None)</i><br>
            Enter the power by which you would like to raise the result.""")

        self.final_addend = cps.Float(
            "Add to the result",0,doc="""
            Enter the number you like to add to the result.""")

        self.constrain_lower_bound = cps.Binary(
            "Constrain the result to a lower bound?",False,doc="""
            Check this setting if you want the result to be 
            constrained to a lower bound.""")

        self.lower_bound = cps.Float(
            "Enter the lower bound",0,doc="""
            Enter the lower bound of the result here.""")

        self.constrain_upper_bound = cps.Binary(
            "Constrain the result to an upper bound?",False,doc="""
            Check this setting if you want the result to be 
            constrained to an upper bound.""")

        self.upper_bound = cps.Float(
            "Enter the upper bound",1,doc="""
            Enter the upper bound of the result here.""")
Example #20
0
 def test_00_00_init(self):
     x=cps.Text("text","value")
     x.test_valid(None)
     self.assertEqual(x.text,"text")
     self.assertEqual(x.value,"value")
     self.assertTrue(x.key())
Example #21
0
    def create_settings(self):
        self.x_source = cps.Choice("Type of measurement to plot on X-axis",
                                   SOURCE_CHOICE,
                                   doc='''
            You can plot two types of measurements:
            <ul>
            <li><i>%(SOURCE_IM)s:</i> For a per-image measurement, one numerical value is 
            recorded for each image analyzed.
            Per-image measurements are produced by
            many modules. Many have <b>MeasureImage</b> in the name but others do not
            (e.g., the number of objects in each image is a per-image 
            measurement made by the <b>IdentifyObject</b> 
            modules).</li>
            <li><i>%(SOURCE_OBJ)s:</i> 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 <b>MeasureObject</b> in the name.</li>
            </ul>''' % globals())

        self.x_object = cps.ObjectNameSubscriber(
            'Select the object to plot on the X-axis',
            cps.NONE,
            doc='''<i>(Used only when plotting objects)</i><br>
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the X-axis.'''
        )

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

        self.y_source = cps.Choice("Type of measurement to plot on Y-axis",
                                   SOURCE_CHOICE,
                                   doc='''
            You can plot two types of measurements:
            <ul>
            <li><i>%(SOURCE_IM)s:</i> For a per-image measurement, one numerical value is 
            recorded for each image analyzed.
            Per-image measurements are produced by
            many modules. Many have <b>MeasureImage</b> in the name but others do not
            (e.g., the number of objects in each image is a per-image 
            measurement made by <b>IdentifyObject</b> 
            modules).</li>
            <li><i>%(SOURCE_OBJ)s:</i> 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 <b>MeasureObject</b> in the name.</li>
            </ul>''' % globals())

        self.y_object = cps.ObjectNameSubscriber(
            'Select the object to plot on the Y-axis',
            cps.NONE,
            doc='''<i>(Used only when plotting objects)</i><br>
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the Y-axis.'''
        )

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

        self.xscale = cps.Choice('How should the X-axis be scaled?',
                                 SCALE_CHOICE,
                                 None,
                                 doc='''
            The X-axis can be scaled with either a <i>linear</i> 
            scale or a <i>log</i> (base 10) scaling. 
            <p>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.</p>''')

        self.yscale = cps.Choice('How should the Y-axis be scaled?',
                                 SCALE_CHOICE,
                                 None,
                                 doc='''
            The Y-axis can be scaled with either a <i>linear</i> 
            scale or with a <i>log</i> (base 10) scaling. 
            <p>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.</p>''')

        self.title = cps.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 <i>(cycle N)</i> where <i>N</i> is the current image 
            cycle being executed.''')
Example #22
0
    def create_settings(self):
        self.objects_or_image = cps.Choice(
            "Display object or image measurements?", [OI_OBJECTS, OI_IMAGE],
            doc="""
            <ul>
            <li><i>%(OI_IMAGE)s</i> allows you to select an image 
            measurement to display for each well.</li> 
            <li><i>%(OI_OBJECTS)s</i> allows you to select an object measurement to display 
            for each well.</li>
            </ul>""" % globals())

        self.object = cps.ObjectNameSubscriber(
            'Select the object whose measurements will be displayed',
            cps.NONE,
            doc='''
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed.'''
        )

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

        self.plate_name = cps.Measurement('Select your plate metadata',
                                          lambda: cpmeas.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. 
            <p>%(USING_METADATA_HELP_REF)s.</p>''' % globals())

        self.plate_type = cps.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:
            <ul>
            <li><i>96:</i> A 96-well plate with 8 rows &times; 12 columns</li>
            <li><i>384:</i> A 384-well plate with 16 rows &times; 24 columns</li>
            </ul>''')

        self.well_format = cps.Choice("Well metadata format",
                                      [WF_NAME, WF_ROWCOL],
                                      doc="""
            <ul>
            <li> <i>%(WF_NAME)s</i> allows you to select an image 
            measurement to display for each well.</li> 
            <li><i>%(WF_ROWCOL)s</i> allows you to select an object measurement to display 
            for each well.</li>
            </ul>""" % globals())

        self.well_name = cps.Measurement('Select your well metadata',
                                         lambda: cpmeas.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"." 
            <p>%(USING_METADATA_HELP_REF)s.</p>''' % globals())

        self.well_row = cps.Measurement('Select your well row metadata',
                                        lambda: cpmeas.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".
            <p>%(USING_METADATA_HELP_REF)s.</p>''' % globals())

        self.well_col = cps.Measurement('Select your well column metadata',
                                        lambda: cpmeas.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".
            <p>%(USING_METADATA_HELP_REF)s.</p>''' % globals())

        self.agg_method = cps.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:
            <ul>
            <li><i>%(AGG_AVG)s:</i> Average</li>
            <li><i>%(AGG_STDEV)s:</i> Standard deviation</li>
            <li><i>%(AGG_MEDIAN)s</i></li>
            <li><i>%(AGG_CV)s:</i> 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.</li>
            </ul>''' % globals())

        self.title = cps.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 <i>(cycle N)</i> where <i>N</i> is the current image 
            cycle being executed.''')
Example #23
0
    def create_settings(self):
        '''Create the settings for the module'''
        logger.debug("Creating RunImageJ module settings")
        J.activate_awt()
        logger.debug("Activated AWT")

        self.command_or_macro = cps.Choice("Run an ImageJ command or macro?",
                                           [CM_COMMAND, CM_SCRIPT, CM_MACRO],
                                           doc="""
            This setting determines whether <b>RunImageJ</b> runs either a:
            <ul>
            <li><i>%(CM_COMMAND)s:</i> Select from a list of available ImageJ commands
            (those items contained in the ImageJ menus); or</li>
            <li><i>%(CM_SCRIPT)s:</i> A script written in one of ImageJ 2.0's
            supported scripting languages.</li>
            <li><i>%(CM_MACRO)s:</i> An ImageJ 1.x macro, written in the
            ImageJ 1.x macro language. <b>Run_ImageJ</b> runs ImageJ in 1.x
            compatability mode.</li>
            </ul>""" % globals())
        #
        # Load the commands in visible_settings so that we don't call
        # ImageJ unless someone tries the module
        #
        self.command = self.make_command_choice("Command",
                                                doc="""
            <i>(Used only if running a %(CM_COMMAND)s)</i><br>
            The command to execute when the module runs.""" % globals())

        self.command_settings_dictionary = {}
        self.command_settings = []
        self.command_settings_count = cps.HiddenCount(
            self.command_settings, "Command settings count")
        self.pre_command_settings_dictionary = {}
        self.pre_command_settings = []
        self.pre_command_settings_count = cps.HiddenCount(
            self.pre_command_settings, "Prepare group command settings count")
        self.post_command_settings_dictionary = {}
        self.post_command_settings = []
        self.post_command_settings_count = cps.HiddenCount(
            self.post_command_settings, "Post-group command settings count")

        self.macro = cps.Text("Macro",
                              """import imagej.command.CommandService;
cmdSvcClass = CommandService.class;
cmdSvc = ImageJ.getService(cmdSvcClass);
cmdSvc.run("imagej.core.commands.assign.InvertDataValues", new Object [] {"allPlanes", true}).get();""",
                              multiline=True,
                              doc="""
            <i>(Used only if running a %(CM_MACRO)s)</i><br>
            This is the ImageJ macro to be executed. The syntax for ImageJ
            macros depends on the scripting language engine chosen.
            We suggest that you use the Beanshell scripting language
            <a href="http://www.beanshell.org/manual/contents.html">
            (Beanshell documentation)</a>.""" % globals())

        all_engines = ij2.get_script_service(get_context()).getLanguages()
        self.language_dictionary = dict([(engine.getLanguageName(), engine)
                                         for engine in all_engines])

        self.macro_language = cps.Choice(
            "Macro language",
            choices=self.language_dictionary.keys(),
            doc="""
            This setting chooses the scripting language used to execute
            any macros in this module""")

        self.wants_to_set_current_image = cps.Binary(
            "Input the currently active image in ImageJ?",
            True,
            doc="""
            Select <i>%(YES)s</i> if you want to set the currently 
            active ImageJ image using an image from a 
            prior CellProfiler module.
            <p>Select <i>%(NO)s</i> to use the currently 
            active image in ImageJ. You may want to do this if you
            have an output image from a prior <b>RunImageJ</b>
            that you want to perform further operations upon
            before retrieving the final result back to CellProfiler.</p>""" %
            globals())

        self.current_input_image_name = cps.ImageNameSubscriber(
            "Select the input image",
            doc="""
            <i>(Used only if setting the currently active image)</i><br>
            This is the CellProfiler image that will become 
            ImageJ's currently active image.
            The ImageJ commands and macros in this module will perform 
            their operations on this image. You may choose any image produced
            by a prior CellProfiler module.""")

        self.wants_to_get_current_image = cps.Binary(
            "Retrieve the currently active image from ImageJ?",
            True,
            doc="""
            Select <i>%(YES)s</i> if you want to retrieve ImageJ's
            currently active image after running the command or macro. 
            <p>Select <i>%(NO)s</i> if the pipeline does not need to access
            the current ImageJ image. For example, you might want to run
            further ImageJ operations with additional <b>RunImageJ</b>
            upon the current image prior to retrieving the final image 
            back to CellProfiler.</p>""" % globals())

        self.current_output_image_name = cps.ImageNameProvider(
            "Name the current output image",
            "ImageJImage",
            doc="""
            <i>(Used only if retrieving the currently active image from ImageJ)</i><br>
            This is the CellProfiler name for ImageJ's current image after
            processing by the command or macro. The image will be a
            snapshot of the current image after the command has run, and
            will be available for processing by subsequent CellProfiler modules."""
        )

        self.pause_before_proceeding = cps.Binary(
            "Wait for ImageJ before continuing?",
            False,
            doc="""
            Some ImageJ commands and macros are interactive; you
            may want to adjust the image in ImageJ before continuing. 
            Select <i>%(YES)s</i> to stop CellProfiler while you adjust the image in
            ImageJ. Select <i>%(NO)s</i> to immediately use the image.
            <p>This command will not wait if CellProfiler is executed in
            batch mode. See <i>%(BATCH_PROCESSING_HELP_REF)s</i> for more
            details on batch processing.</p>""" % globals())

        self.prepare_group_choice = cps.Choice(
            "Function to run before each group of images?",
            [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO],
            doc="""
            You can run an ImageJ 2.0 script, an ImageJ 1.x macro or a command <i>before</i> each group of
            images. This can be useful in order to set up ImageJ before
            processing a stack of images. Choose <i>%(CM_NOTHING)s</i> if
            you do not want to run a command or macro, <i>%(CM_COMMAND)s</i>
            to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an
            ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x
            macro in ImageJ 1.x compatibility mode.
            """ % globals())

        logger.debug("Finding ImageJ commands")

        self.prepare_group_command = self.make_command_choice("Command",
                                                              doc="""
            <i>(Used only if running a command before an image group)</i><br>
            Select the command to execute before processing a group of images."""
                                                              )

        self.prepare_group_macro = cps.Text("Macro",
                                            'run("Invert");',
                                            multiline=True,
                                            doc="""
            <i>(Used only if running a macro before an image group)</i><br>
            This is the ImageJ macro to be executed before processing
            a group of images. For help on writing macros, see 
            <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>."""
                                            )

        self.post_group_choice = cps.Choice(
            "Function to run after each group of images?",
            [CM_NOTHING, CM_COMMAND, CM_SCRIPT, CM_MACRO],
            doc="""
            You can run an ImageJ 2.0 script, an ImageJ macro or a command <i>after</i> each group of
            images. This can be used to do some sort of operation on a whole
            stack of images that have been accumulated by the group operation.
            Choose <i>%(CM_NOTHING)s</i> if
            you do not want to run a command or macro, <i>%(CM_COMMAND)s</i>
            to choose a command to run, <i>%(CM_SCRIPT)s</i> to run an
            ImageJ 2.0 script or <i>%(CM_MACRO)s</i> to run an ImageJ 1.x
            macro in ImageJ 1.x compatibility mode.
            """ % globals())

        self.post_group_command = self.make_command_choice("Command",
                                                           doc="""
            <i>(Used only if running a command after an image group)</i><br>
            The command to execute after processing a group of images.""")

        self.post_group_macro = cps.Text("Macro",
                                         'run("Invert");',
                                         multiline=True,
                                         doc="""
            <i>(Used only if running a macro after an image group)</i><br>
            This is the ImageJ macro to be executed after processing
            a group of images. For help on writing macros, see 
            <a href="http://rsb.info.nih.gov/ij/developer/macro/macros.html">here</a>."""
                                         )

        self.wants_post_group_image = cps.Binary(
            "Retrieve the image output by the group operation?",
            False,
            doc="""
            You can retrieve the image that is currently active in ImageJ
            at the end of macro processing and use it later in CellProfiler.
            The image will only be available during the last cycle of the
            image group. 
            <p>Select <i>%(YES)s</i> to retrieve the active image for use in CellProfiler.
            Select <i>%(NO)s</i> if you do not want to retrieve the active image.</p>
            """ % globals())

        self.post_group_output_image = cps.ImageNameProvider(
            "Name the group output image",
            "ImageJGroupImage",
            doc="""
            <i>(Used only if retrieving an image after an image group operation)</i><br>
            This setting names the output image produced by the
            ImageJ command or macro that CellProfiler runs after processing
            all images in the group. The image is only available at the
            last cycle in the group""",
            provided_attributes={
                cps.AGGREGATE_IMAGE_ATTRIBUTE: True,
                cps.AVAILABLE_ON_LAST_ATTRIBUTE: True
            })

        self.show_imagej_button = cps.DoSomething("Show ImageJ",
                                                  "Show",
                                                  self.on_show_imagej,
                                                  doc="""
            Press this button to show the ImageJ user interface.
            You can use the user interface to run ImageJ commands or
            set up ImageJ before a CellProfiler run.""")

        logger.debug("Finished creating settings")
Example #24
0
    def add_flag(self, can_delete=True):
        group = cps.SettingsGroup()
        group.append("divider1", cps.Divider(line=False))
        group.append("measurement_settings", [])
        group.append("measurement_count",
                     cps.HiddenCount(group.measurement_settings))
        group.append(
            "category",
            cps.Text("Name the flag's category",
                     "Metadata",
                     doc='''
                        Name a measurement category by which to categorize the flag. The <i>Metadata</i> 
                        category is the default used in CellProfiler to store information about 
                        images (referred to as <i>metadata</i>).</p>
                        <p>The flag is stored as a per-image measurement whose name is a combination of the
                        flag's category and feature name, underscore delimited. 
                        For instance, if the measurement category is
                        <i>Metadata</i> and the feature name is <i>QCFlag</i>, then the default
                        measurement name would be <i>Metadata_QCFlag</i>. %s</p>'''
                     % USING_METADATA_HELP_REF))

        group.append(
            "feature_name",
            cps.Text("Name the flag",
                     "QCFlag",
                     doc='''
                        The flag is stored as a per-image measurement whose name is a combination of the
                        flag's category and feature name, separated by underscores. 
                        For instance, if the measurement category is
                        <i>Metadata</i> and the feature name is <i>QCFlag</i>, then the default
                        measurement name would be <i>Metadata_QCFlag</i>.'''))

        group.append(
            "combination_choice",
            cps.Choice(
                "Flag if any, or all, measurement(s) fails to meet the criteria?",
                [C_ANY, C_ALL],
                doc='''
                        <ul>
                        <li><i>%(C_ANY)s:</i> An image will be flagged if any of its measurements fail. This can be useful
                        for flagging images possessing multiple QC flaws; for example, you can flag all bright images 
                        and all out of focus images with one flag.</li>
                        <li><i>%(C_ALL)s:</i> A flag will only be assigned if all measurements fail.  This can be useful 
                        for flagging images that possess only a combination
                        of QC flaws; for example, you can flag only images that are both bright and out of focus.</li>
                        </ul>''' % globals()))

        group.append(
            "wants_skip",
            cps.Binary("Skip image set if flagged?",
                       False,
                       doc="""
                        <p>Select <i>%(YES)s</i> to skip the remainder of the pipeline for image sets
                        that are flagged. CellProfiler will not run subsequent modules in the
                        pipeline on the images in any image set that is flagged. 
                        Select <i>%(NO)s</i> for CellProfiler to continue to process the pipeline regardless
                        of flagging.</p>
                        <p>You may want to skip processing in order to filter out
                        unwanted images. For instance, you may want
                        to exclude out of focus images when running 
                        <b>CorrectIllumination_Calculate</b>. You can do this with a
                        pipeline that measures image quality and flags inappropriate
                        images before it runs <b>CorrectIllumination_Calculate</b>.</p>"""
                       % globals()))

        group.append(
            "add_measurement_button",
            cps.DoSomething("", "Add another measurement",
                            self.add_measurement, group))
        self.add_measurement(group, False if not can_delete else True)
        if can_delete:
            group.append(
                "remover",
                cps.RemoveSettingButton("", "Remove this flag", self.flags,
                                        group))
        group.append("divider2", cps.Divider(line=True))
        self.flags.append(group)
    def create_settings(self):
        # Settings
        self.file_types = cps.Choice('File type to be loaded',
                                     FF_CHOICES,
                                     doc="""
                The following image file types are permissible for input into CellProfiler:
                <ul>
                <li><i>Individual images:</i>Each file represents a single image. 
                Some methods of file compression sacrifice image quality ("lossy") and should be avoided for automated image analysis 
                if at all possible (e.g., .jpg). Other file compression formats retain exactly the original image information but in 
                a smaller file ("lossless") so they are perfectly acceptable for image analysis (e.g., .png, .tif, .gif). 
                Uncompressed file formats are also fine for image analysis (e.g., .bmp)</li>
                <li><i>AVI movies:</i>An AVI (Audio Video Interleave) file is a type of movie file. Only uncompressed AVIs are supported.
                Files are opened as a stack of images.</li>
                <li><i>TIF,TIFF,FLEX movies:</i>A TIF/TIFF movie is a file in which a series of images are contained as individual frames. 
                The same is true for the FLEX file format (used by Evotec Opera automated microscopes). Files are opened as a stack of images.</li>
                <li><i>STK movies:</i> STKs are a proprietary image format used by MetaMorph (Molecular Devices). It is typically
                used to encode 3D image data, e.g. from confocal microscopy, and is a special version of the TIF format. </li>
                </ul>
                For the movie formats, the files are opened as a stack of images and each image is processed individually."""
                                     )

        self.descend_subdirectories = cps.Binary(
            'Descend into subdirectories?',
            False,
            doc="""
                If this box is checked, all the subfolders under the image directory location that you specify will be
                searched for images.""")

        self.top_spacer = cps.Divider()

        # Images settings
        self.exclude = cps.Binary('Exclude certain files?',
                                  False,
                                  doc="""
                <p>This settings allows you exclude certain files (such as thumbnails) from further consideration."""
                                  )

        # should this be a regexp?
        self.match_exclude_text = cps.Text('Substring in files to be excluded',
                                           cps.DO_NOT_USE,
                                           doc="""
                <i>(Used only if file exclusion is selected)</i> 
                <p>Here you can specify substring that marks files for exclusion.</p>"""
                                           )

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

        self.images = []
        self.add_image()

        self.add_image_button = cps.DoSomething("", "Add another image",
                                                self.add_image)

        self.image_spacer_bottom = cps.Divider()

        # Metadata settings
        self.metadata_label = cps.Divider("Metadata")

        # extraction settings
        self.grouping_label = cps.Divider("Grouping")
    def create_settings(self):
        '''Create the settings for the module's UI'''
        self.warning = cps.Divider(
            "This module allows you to rename (overwrite) your files. Please "
            "see the help for this module for warnings.")

        self.image_name = cps.FileImageNameSubscriber('Select the input image',
                                                      cps.NONE,
                                                      doc="""
            Select the images associated with the files
            you want to rename. This should be an image loaded by the
            <b>Input</b> modules.
            Be very careful because you will be renaming these files!""")

        self.number_characters_prefix = cps.Integer(
            "Number of characters to retain at start of file name",
            6,
            minval=0,
            doc="""
            Number of characters at the start of the old
            file name that will be copied over verbatim to the new file name. For
            instance, if this setting is "6" and the file name is 
            "Image-734.tif", the output file name will also start with 
            "Image-".""")

        self.number_characters_suffix = cps.Integer(
            "Number of characters to retain at the end of file name",
            4,
            minval=0,
            doc="""
            Number of characters at the end of the old
            file name that will be copied over verbatim to the new file name. For
            instance, if this setting is "4" and the file name is
            "Image-734.tif", the output file name will also end with ".tif"."""
        )

        self.action = cps.Choice("Handling of remaining characters",
                                 [A_RENUMBER, A_DELETE],
                                 doc="""
            You can either treat the characters between the start and
            end as numbers or you can delete them. If you treat them as numbers,
            you will be given the opportunity to pad the numbers with zeros
            so that all of your file names will have a uniform length. For
            instance, if you were to renumber the highlighted portion of the
            file "Image-<u>734</u>.tif" using four digits, the result would
            be "Image-0734.tif".""")

        self.number_digits = cps.Integer("Number of digits for numbers",
                                         4,
                                         minval=0,
                                         doc="""
            <i>(Used only if %(A_RENUMBER)s is selected)</i><br>
            Use this setting to pad numbers with zeros so that they
            all have a uniform number of characters. For instance, padding
            with four digits has the following result:<br>
            <code><table>
            <tr><th>Original</th><th>Padded</th></tr>
            <tr><td>1</td><td>0001</td></tr>
            <tr><td>10</td><td>0010</td></tr>
            <tr><td>100</td><td>0100</td></tr>
            <tr><td>1000</td><td>1000</td></tr>
            </table></code>""" % globals())

        self.wants_text = cps.Binary("Add text to the file name?",
                                     False,
                                     doc="""
            Select <i>%(YES)s</i> if you want to add text
            to the file name. If you had chosen <i>%(A_RENUMBER)s</i> above,
            the module will add the text after your number.
            If you had chosen <i>%(A_DELETE)s</i>, the module will replace
            the deleted text with the text you enter here.""" % globals())

        self.text_to_add = cps.Text("Replacement text",
                                    "",
                                    doc="""
            <i>(Used only if you chose to add text to the file name)</i><br>
            Enter the text that you want to add to each file name.""")

        self.wants_to_replace_spaces = cps.Binary("Replace spaces?",
                                                  False,
                                                  doc="""
            Select <i>%(YES)s</i> to replace spaces in the final
            version of the file name with some other text. 
            <p>Select <i>%(NO)s</i> if the file name can have spaces 
            or if none of the file names have spaces.</p>""" % globals())

        self.space_replacement = cps.Text("Space replacement",
                                          "_",
                                          doc="""
            This is the text that will be substituted for spaces
            in your file name.""")
    def create_settings(self):
        """Create the module settings
        
        create_settings is called at the end of initialization.
        """
        self.object = cps.ObjectNameSubscriber(
            'Select the object whose measurements will be displayed',
            cps.NONE,
            doc='''
            Choose the name of objects identified by some previous 
            module (such as <b>IdentifyPrimaryObjects</b> or 
            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed.'''
        )

        self.x_axis = cps.Measurement('Select the object measurement to plot',
                                      self.get_object,
                                      cps.NONE,
                                      doc='''
            Choose the object measurement made by a previous 
            module to plot.''')

        self.bins = cps.Integer('Number of bins',
                                100,
                                1,
                                1000,
                                doc='''
            Enter the number of equally-spaced bins that you want 
            used on the X-axis.''')

        self.xscale = cps.Choice(
            'Transform the data prior to plotting along the X-axis?',
            ['no', 'log'],
            None,
            doc='''
            The measurement data can be scaled with either a 
            linear scale (<i>No</i>) or a <i>log</i> (base 10) 
            scaling.
            <p>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.<p>''')

        self.yscale = cps.Choice('How should the Y-axis be scaled?',
                                 ['linear', 'log'],
                                 None,
                                 doc='''
            The Y-axis can be scaled either with either a <i>linear</i> 
            scale or a <i>log</i> (base 10) scaling. 
            <p>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.</p>''')

        self.title = cps.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 <i>(cycle N)</i> where <i>N</i> is the current image 
            cycle being executed.''')

        self.wants_xbounds = cps.Binary(
            'Specify min/max bounds for the X-axis?',
            False,
            doc='''
            Select <i>%(YES)s</i> 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.''' %
            globals())

        self.xbounds = cps.FloatRange('Minimum/maximum values for the X-axis')
    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 = cps.SettingsGroup()
        group.append("measurement",
                     cps.Measurement("Select the image measurement describing the treatment dose",
                                     lambda: cpmeas.IMAGE,
                                     doc="""
            The V and Z' factor, a measure 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. <p>
            The typical way to provide this information in the pipeline is to create
            a comma-delimited text file (CSV) outside of CellProfiler and then load that file into the pipeline
            using <b>Metadata</b> or the <b>LoadData</b>. In that case, choose the
            measurement that matches the column header of the measurement
            in the CSV input file. See <b>LoadData</b> help for an example text file.
            """))

        group.append("log_transform", cps.Binary(
                "Log-transform the dose values?", False, doc='''
            Select <i>%(YES)s</i> if you have dose-response data and you want to log-transform
            the dose values before fitting a sigmoid curve.
            <p>Select <i>%(NO)s</i> if your data values indicate only positive vs. negative
            controls.</p>''' % globals()))

        group.append('wants_save_figure', cps.Binary(
                '''Create dose/response plots?''', False, doc='''<a name='wants_save_figure'></a>
            Select <i>%(YES)s</i> 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', cps.Text(
                "Figure prefix", "", doc='''
            <i>(Used only when creating dose/response plots)</i><br>
            CellProfiler will create a file name by appending the measurement name
            to the prefix you enter here. For instance, if you have objects
            named, "Cells", the "AreaShape_Area measurement", and a prefix of "Dose_",
            CellProfiler will save the figure as <i>Dose_Cells_AreaShape_Area.m</i>.
            Leave this setting blank if you do not want a prefix.'''
        ))
        group.append('pathname', cps.DirectoryPath(
                "Output file location",
                dir_choices=[
                    cps.DEFAULT_OUTPUT_FOLDER_NAME, cps.DEFAULT_INPUT_FOLDER_NAME,
                    cps.ABSOLUTE_FOLDER_NAME, cps.DEFAULT_OUTPUT_SUBFOLDER_NAME,
                    cps.DEFAULT_INPUT_SUBFOLDER_NAME], doc="""
            <i>(Used only when creating dose/response plots)</i><br>
            This setting lets you choose the folder for the output
            files. %(IO_FOLDER_CHOICE_HELP_TEXT)s

            <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 of 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()))

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

        group.append("remover", cps.RemoveSettingButton("", "Remove this dose measurement",
                                                        self.dose_values,
                                                        group))
        self.dose_values.append(group)
Example #29
0
    def create_settings(self):
        self.x_object = cps.ObjectNameSubscriber(
            'Select the object to display on the X-axis',
            'None',
            doc='''
                            Choose the name of objects identified by some previous 
                            module (such as <b>IdentifyPrimaryObjects</b> or 
                            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the X-axis.'''
        )

        self.x_axis = cps.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 = cps.ObjectNameSubscriber(
            'Select the object to display on the Y-axis',
            'None',
            doc=''' 
                            Choose the name of objects identified by some previous 
                            module (such as <b>IdentifyPrimaryObjects</b> or 
                            <b>IdentifySecondaryObjects</b>) whose measurements are to be displayed on the Y-axis.'''
        )

        self.y_axis = cps.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 = cps.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 = cps.Choice('How should the X-axis be scaled?',
                                 ['linear', 'log'],
                                 None,
                                 doc='''
                            The X-axis can be scaled either with a <i>linear</i> 
                            scale or with a <i>log</i> (base 10) scaling. 
                            <p>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.</p>''')

        self.yscale = cps.Choice('How should the Y-axis be scaled?',
                                 ['linear', 'log'],
                                 None,
                                 doc='''
                            The Y-axis can be scaled either with a <i>linear</i> 
                            scale or with a <i>log</i> (base 10) scaling. 
                            <p>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.</p>''')

        self.bins = cps.Choice('How should the colorbar be scaled?',
                               ['linear', 'log'],
                               None,
                               doc='''
                            The colorbar can be scaled either with a <i>linear</i> 
                            scale or with a <i>log</i> (base 10) scaling.
                            <p>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 matplotlib.cm.datad.keys() if not m.endswith('_r')]
        maps.sort()

        self.colormap = cps.Choice('Select the color map',
                                   maps,
                                   'jet',
                                   doc='''
                            Select the color map for the density plot. See this 
                            <a href="http://www.astro.princeton.edu/~msshin/science/code/matplotlib_cm/">
                            page</a> for pictures of the available colormaps.'''
                                   )

        self.title = cps.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 <i>(cycle N)</i> where <i>N</i> is the current image 
                            cycle being executed.''')
Example #30
0
    def create_settings(self):
        self.orig_image_name = cps.ImageNameSubscriber(
            "Select the input images", "None",
            doc="""Select the images to display on the web page.""")
        
        self.wants_thumbnails = cps.Binary(
            "Use thumbnail images?", False,
            doc="""Check this option to display thumbnail images (small versions of the 
            images) on the web page that link to the full images. Leave it 
            unchecked to display the full image directly on the web page.
            <p>If you are going to use thumbnails, you will need to load
            them using <b>LoadImages</b> or <b>LoadData</b>; you can run a separate 
            pipeline prior to this one to create thumbnails from your originals  
            using the <b>Resize</b> and <b>SaveImages</b> modules. For some high-content
            screening systems, thumbnail files are automatically created and have
            the text "thumb" in the name.</p>""")
        
        self.thumbnail_image_name = cps.ImageNameSubscriber(
            "Select the thumbnail images", "None",
            doc="""
            <i>(Used only if using thumbnails)</i><br>
            Select the name of the images to use for thumbnails.""")
        
        self.web_page_file_name = cps.Text(
            "Webpage file name", "images1",
            metadata= True,
            doc="""Enter the desired file name for the web page. <b>CreateWebPage</b>
            will add the .html extension if no extension is specified.
            If you have metadata associated with your images, you can name the 
            file using metadata tags. %(USING_METADATA_TAGS_REF)s<br>
            For instance, if you have metadata tags named "Plate" and 
            "Well", you can create separate per-plate, per-well web pages based on
            your metadata by inserting the tags "Plate_Well" to specify the 
            name. %(USING_METADATA_HELP_REF)s."""%globals())
        
        self.directory_choice = cps.Choice(
            "Select the folder for the .html file",
            [ DIR_SAME, DIR_ABOVE],
            doc="""This setting determines how <b>CreateWebPage</b> selects the 
            folder for the .html file(s) it creates. 
            <ul>
            <li><i>%(DIR_SAME)s</i>: Place the .html file(s) in the same folder as 
            the files.</li>
            <li><i>%(DIR_ABOVE)s</i>: Place the .html file(s) in the
            image files' parent folder.</li>
            </ul>""" % globals())
        
        self.title = cps.Text(
            "Webpage title", "Image", metadata = True,
            doc = """This is the title that appears at the top of the browser
            window. If you have metadata associated with your images, you can name the 
            file using metadata tags. %(USING_METADATA_TAGS_REF)sFor instance, if you 
            have a metadata tag named "Plate", you can type "Plate: " and then insert 
            the metadata tag "Plate" to display the plate metadata item. %(USING_METADATA_HELP_REF)s."""
            %globals())
        
        self.background_color = cps.Color(
            "Webpage background color", "White",
            doc = """This setting controls the background color for the web page.""")
        
        self.columns = cps.Integer(
            "Number of columns", 1, minval = 1,
            doc = """This setting determines how many images are displayed
            in each row.""")
        
        self.table_border_width = cps.Integer(
            "Table border width", 1, minval = 0,
            doc = """The table border width determines the width of the border
            around the entire grid of displayed images (i.e., the "table" of images) and is measured in pixels. This value can be 
            set to zero, in which case you will not see the table border.""")
        
        self.table_border_color = cps.Color(
            "Table border color", "White")

        self.image_spacing = cps.Integer(
            "Image spacing", 1, minval = 0,
            doc = """The spacing between images ("table cells"), in pixels.""")
        
        self.image_border_width = cps.Integer(
            "Image border width", 1, minval = 0,
            doc = """The image border width determines the width of
            the border around each image and is measured in pixels.
            This value can be set to zero, in which case you will not see the 
            image border.""")
        
        self.create_new_window = cps.Choice(
            "Open new window when viewing full image?",
            [OPEN_ONCE, OPEN_EACH, OPEN_NO],
            doc = """This controls the behavior of the thumbnail links. If
            you select, <i>%(OPEN_ONCE)s</i>, your browser will open a new window
            when you click on the first thumbnail and will display subsequent
            images in the newly opened window. If you select <i>
            %(OPEN_EACH)s</i>, the browser will open a new window each time
            you click on a link. If you select, <i>%(OPEN_NO)s</i>, the
            browser will reuse the current window to display the image"""% globals())
        
        self.wants_zip_file = cps.Binary(
            "Make a ZIP file containing the full-size images?", False,doc="""
            ZIP files are a common archive and data compression file format, making it convenient to download all of the images represented on the web page with a single click.
            Check this box to create a ZIP file that contains all your images, 
            compressed to reduce file size.""")
        
        self.zipfile_name = cps.Text(
            "Enter the ZIP file name", "Images.zip",
            metadata = True,
            doc="""
            <i>(Used only if creating a ZIP file)</i><br>
            Specify the name for the ZIP file.""")