def run_as_program():
    """
    Testing function to allow the script to be called outside of the OMERO
    scripting environment. The connection details and image ID must be valid.
    """
    import getpass
    HOST = 'localhost'
    PORT = 4064
    USERNAME = raw_input("OMERO username: "******"OMERO password: "******"OMERO host (%s): " % HOST)
    if h:
        HOST = h
    p = raw_input("OMERO port (%d): " % PORT)
    if p:
        PORT = p

    conn = BlitzGateway(USERNAME, PASSWORD, host=HOST, port=PORT)
    conn.connect()
    conn.keepAlive()

    params = create_script_defaults()
    params[PARAM_DATATYPE] = 'Image'
    params[PARAM_IDS] = [51]
    # params[PARAM_DATATYPE] = 'Dataset'
    # params[PARAM_IDS] = [2]
    params[PARAM_UPLOAD_RESULTS] = True
    params[PARAM_EMAIL_RESULTS] = True
    params[PARAM_EMAIL] = ADMIN_EMAIL

    count = run(conn, params)

    if count >= 0:
        print ("Processed %d image%s" %
               (count, count != 1 and 's' or ''))
def run_as_script():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """
    params = create_script_defaults()
    methods = []
    for m in ["Li", "MaxEntropy", "Mean", "MinError(I)",
              "Moments", "None", "Otsu", "Percentile", "RenyiEntropy",
              "Triangle", "Yen"]:
        methods.append(rstring(m))
    dataTypes = [rstring('Dataset'), rstring('Image')]

    client = scripts.client('Colocalisation_Analyser.py', """\
Perform colocalisation analysis on the image channels.

Analysis is done using the Confined Displacement Algorithm (CDA). Images are
displaced a random amount and the colocalisation metric computed. A
distribution is constructed for the metric using multiple displacements and
used to assess the significance of the native result.

Processes a stack image with multiple channels. Each frame is processed
separately. Extracts the channels (collating z-stacks) and performs:

- (1). Thresholding to create a mask for each channel
- (2). CDA analysis of channel 1 vs channel 2, optionally within the region
  defined by channel 3

Results are appended to the image as a file attachment and/or e-mailed
to you. Messages use your e-mail address from your OMERO profile (or the
address specified).

See: http://www.sussex.ac.uk/gdsc/intranet/microscopy/omero/scripts/colocalisation""",  # noqa

    scripts.String(PARAM_DATATYPE, optional=False, grouping="1",
        description="Choose Images via their 'Dataset' or directly by "
                    "'Image' IDs.",
        values=dataTypes, default="Image"),

    scripts.List(PARAM_IDS, optional=False, grouping="2",
        description="List of Image IDs").ofType(rlong(0)),

    scripts.String(PARAM_CHANNEL1, optional=False, grouping="3",
        default=params[PARAM_CHANNEL1],
        description="Select the first channel"),
    scripts.String(PARAM_CHANNEL2, optional=False, grouping="4",
        default=params[PARAM_CHANNEL2],
        description="Select the second channel"),
    scripts.String(PARAM_CHANNEL3, grouping="5",
        default=params[PARAM_CHANNEL3],
        description="Select the third channel"),

    scripts.String(PARAM_METHOD, optional=False, grouping="6",
        values=methods,
        default=params[PARAM_METHOD],
        description="Select the thresholding method"),

    scripts.Int(PARAM_PERMUTATIONS, optional=False, grouping="7.1",
        default=params[PARAM_PERMUTATIONS], min=1,
        description="The number of permutations to calculate"),
    scripts.Int(PARAM_MIN_SHIFT, optional=False, grouping="7.2",
        default=params[PARAM_MIN_SHIFT], min=1,
        description="The minimum shift for random displacements"),
    scripts.Int(PARAM_MAX_SHIFT, optional=False, grouping="7.3",
        default=params[PARAM_MAX_SHIFT], min=2,
        description="The maximum shift for random displacements"),
    scripts.Float(PARAM_SIGNIFICANCE, optional=False, grouping="7.4",
        default=params[PARAM_SIGNIFICANCE], min=0, max=1,
        description="The p-value for significance"),

    scripts.Bool(PARAM_UPLOAD_RESULTS, grouping="8",
        default=params[PARAM_UPLOAD_RESULTS],
        description="Attach the results to each image"),
    scripts.Bool(PARAM_EMAIL_RESULTS, grouping="9",
        default=params[PARAM_EMAIL_RESULTS],
        description="E-mail the results"),
    scripts.String(PARAM_EMAIL, grouping="9.1", default=params[PARAM_EMAIL],
        description="Specify e-mail address"),

    version="1.0",
    authors=["Alex Herbert", "GDSC"],
    institutions=["University of Sussex"],
    contact="*****@*****.**",
    )  # noqa

    try:
        conn = BlitzGateway(client_obj=client)
        conn.keepAlive()

        # Process the list of args above.
        for key in client.getInputKeys():
            if client.getInput(key):
                params[key] = client.getInput(key, unwrap=True)

        if params[PARAM_EMAIL_RESULTS] and not validate_email(conn, params):
            client.setOutput("Message", rstring("No valid email address"))
            return

        # Call the main script - returns the number of images processed
        count = run(conn, params)

        if count >= 0:
            client.setOutput("Message",
                             rstring("Processed %d image%s" %
                                     (count, count != 1 and 's' or '')))
        else:
            client.setOutput("Message",
                             rstring("Errors found in the input parameters. "
                                     "Check the Info file."))

    finally:
        client.closeSession()
def run_as_script():
    """
    The main entry point of the script, as called by the client via the
    scripting service, passing the required parameters.
    """
    params = create_script_defaults()
    methods = []
    for m in ["Li", "MaxEntropy", "Mean", "MinError(I)",
              "Moments", "None", "Otsu", "Percentile", "RenyiEntropy",
              "Triangle", "Yen"]:
        methods.append(rstring(m))
    dataTypes = [rstring('Dataset'), rstring('Image')]

    client = scripts.client('Correlation_Analyser.py', """\
Perform correlation analysis on the image channels.

Each time-frame in the image is analysed. Optionally the z-stack for the frame
can be combined into a single result or analysed as separate slices.

- Each channel is thresholded to produce a foreground region (mask)
- All-vs-all correlation is computed using the mask of each channel
- Analysis is performed using the union or intersect of the mask overlap

Results are appended to the image as a file attachment and/or e-mailed
to you. Messages use your e-mail address from your OMERO profile (or the
address specified).

See: http://www.sussex.ac.uk/gdsc/intranet/microscopy/omero/scripts/correlation""",  # noqa

    scripts.String(PARAM_DATATYPE, optional=False, grouping="1",
        description="Choose Images via their 'Dataset' or directly by "
                    "'Image' IDs.",
        values=dataTypes, default="Image"),

    scripts.List(PARAM_IDS, optional=False, grouping="2",
        description="List of Image IDs").ofType(rlong(0)),

    scripts.String(PARAM_METHOD, grouping="3",
        values=methods,
        default=params[PARAM_METHOD],
        description="Select the thresholding method"),
    scripts.Bool(PARAM_INTERSECT, grouping="4",
        default=params[PARAM_INTERSECT],
        description="Use the intersect of the mask regions"),
    scripts.Bool(PARAM_AGGREGATE_STACK, grouping="5",
        default=params[PARAM_AGGREGATE_STACK],
        description="Aggregate z-stack"),

    scripts.Bool(PARAM_UPLOAD_RESULTS, grouping="6",
        default=params[PARAM_UPLOAD_RESULTS],
        description="Attach the results to each image"),
    scripts.Bool(PARAM_EMAIL_RESULTS, grouping="7",
        default=params[PARAM_EMAIL_RESULTS],
        description="E-mail the results"),
    scripts.String(PARAM_EMAIL, grouping="7.1", default=params[PARAM_EMAIL],
        description="Specify e-mail address"),

    version="1.0",
    authors=["Alex Herbert", "GDSC"],
    institutions=["University of Sussex"],
    contact="*****@*****.**",
    )  # noqa

    try:
        conn = BlitzGateway(client_obj=client)
        conn.keepAlive()

        # Process the list of args above.
        for key in client.getInputKeys():
            if client.getInput(key):
                params[key] = client.getInput(key, unwrap=True)

        if params[PARAM_EMAIL_RESULTS] and not validate_email(conn, params):
            client.setOutput("Message", rstring("No valid email address"))
            return

        # Call the main script - returns the number of images processed
        count = run(conn, params)

        if count >= 0:
            client.setOutput("Message",
                             rstring("Processed %d image%s" %
                                     (count, count != 1 and 's' or '')))
        else:
            client.setOutput("Message",
                             rstring("Errors found in the input parameters. "
                                     "Check the Info file."))

    finally:
        client.closeSession()