Beispiel #1
0
def main(argv=None):
    """script main.

    parses command line options in sys.argv, unless *argv* is given.
    """

    if argv is None:
        argv = sys.argv

    parser = E.OptionParser(version="%prog version: $Id$",
                            usage=globals()["__doc__"])

    parser.add_option("-d",
                      "--pattern-output",
                      dest="pattern_output",
                      type="string",
                      help="filename pattern for output multiple "
                      "alignment files.")

    parser.add_option("-f",
                      "--filename-filter",
                      dest="filename_filter",
                      type="string",
                      help="filename with strings to filter by.")

    parser.add_option("--list-filter",
                      dest="list_filter",
                      type="string",
                      help="list of strings to filter by.")

    parser.set_defaults(
        pattern_output="%s.mali",
        methods="",
        parameters="",
        filename_filter=None,
        list_filter=None,
    )

    Malis.addOptions(parser)

    (options, args) = E.Start(parser)

    options.methods = options.methods.split(",")
    options.parameters = options.parameters.split(",")

    if not options.pattern_mali:
        raise "Please specifiy a pattern to find the malis using --pattern-mali"

    ####################################################################
    ####################################################################
    ####################################################################
    # Read components
    ####################################################################
    map_seq_id2component, map_component2seq_id, map_component2input_id = \
        Malis.readComponents(options)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read filtering information
    ####################################################################
    if options.filename_filter:
        id_filter, nerrors = IOTools.ReadList(
            open(options.filename_filter, "r"))
        if options.loglevel >= 1:
            options.stdlog.write(
                "# read %i identifiers to filter each multiple alignment with.\n"
                % len(id_filter))
            options.stdlog.flush()
    elif options.list_filter:
        id_filter = options.list_filter.split(",")
    else:
        id_filter = None

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to mask
    ####################################################################
    map_component2masks = Malis.readMasks(options, map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to extract
    ####################################################################
    map_component2extracts = Malis.readExtracts(options,
                                                map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to annotate
    ####################################################################
    map_component2annotations = Malis.readAnnotations(options,
                                                      map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Prepare for run
    ####################################################################
    component_ids = map_component2seq_id.keys()
    component_ids.sort()

    if options.loglevel >= 1:
        options.stdlog.write("# %i component ids to start with.\n" %
                             (len(component_ids)))

    component_ids, map_sample2reference = Malis.selectComponents(
        component_ids, map_component2seq_id, map_component2input_id, id_filter,
        options)

    if options.test:
        component_ids = component_ids[:options.test]

    if options.loglevel >= 1:
        options.stdlog.write("# %i component ids selected for output.\n" %
                             (len(component_ids)))

    ninput = 0
    noutput = 0
    nskipped = 0
    nskipped_length = 0

    for component_id in component_ids:

        ninput += 1

        if options.loglevel >= 3:
            options.stdlog.write("# processing component %s\n" %
                                 (component_id))

        mali = Malis.getMali(component_id, map_component2seq_id,
                             map_component2input_id, id_filter, options)

        if mali is None:
            E.warn("empty mali returned for component %s" % (component_id))
            nskipped += 1
            continue

        if mali.getNumColumns() == 0:
            E.warn("skipping output of empty alignment for component %s" %
                   (component_id))
            nskipped += 1
            continue

        mali.setName(str(component_id))

        ###############################################################
        # add annotations
        if map_component2annotations is not None:
            Malis.annotateAlignment(mali, map_component2annotations, options)

        ###############################################################
        # mask the alignment
        Malis.maskAlignment(mali, map_component2masks, map_component2extracts,
                            map_sample2reference, options)

        if mali.getNumColumns() < options.minimum_mali_length:
            nskipped_length += 1
            if options.loglevel >= 1:
                options.stdlog.write(
                    "# component %s: skipped, because length %i less than threshold.\n"
                    % (component_id, mali.getNumColumns()))
            continue

        ###############################################################
        # prepare the mali for output
        if "%s" not in options.pattern_output:
            append = True
        else:
            append = False

        output_filename = re.sub("%s", component_id, options.pattern_output)
        input_id = map_component2input_id[component_id]

        if options.loglevel >= 2:
            options.stdlog.write(
                "# component %s: input from %s, goes to %s\n" %
                (component_id, input_id, output_filename))

        dirname = os.path.dirname(output_filename)

        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)

        if not os.path.exists(output_filename):
            mali.writeToFile(open(output_filename, "w"),
                             format=options.output_format)
            noutput += 1
        else:
            if append:
                mali.writeToFile(open(output_filename, "a"),
                                 format=options.output_format)
                noutput += 1
            else:
                if options.loglevel >= 1:
                    options.stdlog.write(
                        "# skipping because output for component %s already exists: %s\n"
                        % (component_id, output_filename))
                nskipped += 1

        # if we only sample, stop if you have reached
        # the desired number
        if options.sample and noutput == options.sample:
            break

    E.info("ninput=%i, noutput=%i, nskipped=%i, nskipped_length=%i" %
           (ninput, noutput, nskipped, nskipped_length))

    E.Stop()
Beispiel #2
0
def main(argv=None):
    """script main.

    parses command line options in sys.argv, unless *argv* is given.
    """

    if argv is None:
        argv = sys.argv

    parser = E.OptionParser(version="%prog version: $Id$",
                            usage=globals()["__doc__"])

    Malis.addOptions(parser)

    parser.add_option("--filename-coordinates",
                      dest="filename_coordinates",
                      type="string",
                      help="filename of coordinates that constitute "
                      "the multiple alignment.")

    parser.add_option("--filename-identifiers",
                      dest="filename_identifiers",
                      type="string",
                      help="filename with list of identifiers to use.")

    parser.add_option("-x",
                      "--pattern-identifier",
                      dest="pattern_identifier",
                      type="string",
                      help="pattern to extract identifier from a sequence "
                      "header.")

    parser.add_option("-w",
                      "--width",
                      dest="width",
                      type="int",
                      help="width of an alignment column "
                      "(choose 3 for codon alignments) "
                      "[default=%default].")

    parser.add_option("-m",
                      "--method",
                      dest="methods",
                      type="choice",
                      choices=("filter-variants", ),
                      help="methods to apply")

    parser.add_option("-p",
                      "--parameters",
                      dest="parameters",
                      type="string",
                      help="parameter stack for methods that require one.")

    parser.add_option("--mask-acgtn",
                      dest="mask_actgn",
                      action="store_true",
                      help="mask. Anything not [ACGTN] will be N.")

    parser.set_defaults(
        pattern_identifier="(^\S+)",
        methods=[],
        parameters="",
        filename_identifiers=None,
        filename_coordinates=None,
        mask_acgtn=False,
    )

    (options, args) = E.Start(parser)

    options.parameters = options.parameters.split(",")

    if not options.pattern_mali:
        raise ValueError(
            "Please specifiy a pattern to find the malis using --pattern-mali")

    ####################################################################
    ####################################################################
    ####################################################################
    # Read components
    ####################################################################
    map_seq_id2component, map_component2seq_id, map_component2input_id = \
        Malis.readComponents(options)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to mask
    ####################################################################
    map_component2masks = Malis.readMasks(options, map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to extract
    ####################################################################
    map_component2extracts = Malis.readExtracts(options,
                                                map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # read identifiers
    ####################################################################
    if options.filename_identifiers:
        identifiers, nerrors = IOTools.ReadList(
            open(options.filename_identifiers, "r"))
        identifiers_set = set(identifiers)
    else:
        identifiers = None
        identifiers_set = None

    ####################################################################
    ####################################################################
    ####################################################################
    # Prepare for run
    ####################################################################

    rx_identifier = re.compile(options.pattern_identifier)

    # build list of concatenated malis
    sequences = {}
    if identifiers:
        for id in identifiers_set:
            sequences[id] = []
    else:
        identifiers_set = set()
        for seq_id in map_seq_id2component.keys():
            id = rx_identifier.search(seq_id).groups()[0]
            sequences[id] = []
            identifiers_set.add(id)
        identifiers = list(identifiers_set)
        identifiers.sort()

    component_ids = map_component2seq_id.keys()
    component_ids.sort()

    if options.test:
        component_ids = component_ids[:options.test]

    ####################################################################
    ####################################################################
    ####################################################################
    # Build list of components to output.
    ####################################################################
    component_ids, map_sample2reference = \
        Malis.selectComponents(component_ids,
                               map_component2seq_id,
                               map_component2input_id,
                               None,
                               options)

    nskipped = 0
    new_component_ids = []

    for component_id in component_ids:

        try:
            mali = Malis.getMali(component_id, map_component2seq_id,
                                 map_component2input_id, None, options)
        except OSError, msg:
            E.warn("could not find mali %s: %s" % (component_id, msg))
            nskipped += 1
            continue

        ###############################################################
        ###############################################################
        ###############################################################
        # check if all identifiers in component are present in mali
        # and build a temporary alignment with all of those found
        component_set = set(map_component2seq_id[component_id])
        if len(component_set.difference(set(mali.getIdentifiers()))) != 0:
            nskipped += 1
            continue

        found = {}
        is_double = None
        temp_mali = Mali.Mali()
        temp_mali.setName(str(component_id))

        for seq_id in map_component2seq_id[component_id]:
            id = rx_identifier.search(seq_id).groups()[0]
            if id not in identifiers_set:
                continue
            if id in found:

                if options.skip_doubles:
                    E.infor("component %s: removed double entry %s\n" %
                            (component_id, seq_id))
                    continue
                else:
                    is_double = id
                    break

            if options.output_format == "codeml":
                if len(mali[seq_id]) % 3 != 0:
                    raise ValueError(
                        "length of sequence %s is not a multiple of 3: %i" %
                        (seq_id, len(mali[seq_id])))

            # change identifier to id
            found[id] = True
            entry = mali.getEntry(seq_id)
            temp_mali.addSequence(id, entry.mFrom, entry.mTo, entry.mString)

        if is_double:
            nskipped += 1
            E.info(("component %s: skipped because it "
                    "contains double entry %s") % (component_id, is_double))
            continue

        if set(found.keys()) != identifiers_set:
            nskipped += 1
            E.info("component %s: skipped because incomplete: %s" %
                   (component_id, str(found.keys())))
            continue

        ###############################################################
        ###############################################################
        ###############################################################
        # mask the temporary alignment
        Malis.maskAlignment(temp_mali, map_component2masks,
                            map_component2extracts, map_sample2reference,
                            options)

        for id, o in temp_mali.items():
            if options.mask_acgtn:
                s = re.sub("[^ACGTNactgn]", "N", o.mString)
            else:
                s = o.mString
            sequences[id].append(s)

        new_component_ids.append(component_id)

        # if we only sample, stop if you have reached
        # the desired number
        if options.sample and len(new_component_ids) == options.sample:
            break
Beispiel #3
0
def main(argv=None):
    """script main.

    parses command line options in sys.argv, unless *argv* is given.
    """

    if argv is None:
        argv = sys.argv

    parser = E.OptionParser(
        version="%prog version: $Id$",
        usage=globals()["__doc__"])

    Malis.addOptions(parser)

    parser.add_option("--coordinates-tsv-file",
                      dest="filename_coordinates",
                      type="string",
                      help="filename of coordinates that constitute "
                      "the multiple alignment.")

    parser.add_option("--identifiers-tsv-file",
                      dest="filename_identifiers",
                      type="string",
                      help="filename with list of identifiers to use.")

    parser.add_option("-x",
                      "--pattern-identifier",
                      dest="pattern_identifier",
                      type="string",
                      help="pattern to extract identifier from a sequence "
                      "header.")

    parser.add_option("-w", "--width", dest="width", type="int",
                      help="width of an alignment column "
                      "(choose 3 for codon alignments) "
                      "[default=%default].")

    parser.add_option("-m", "--method", dest="methods", type="choice",
                      choices=("filter-variants", ),
                      help="methods to apply")

    parser.add_option("-p", "--parameters", dest="parameters", type="string",
                      help="parameter stack for methods that require one.")

    parser.add_option("--mask-acgtn", dest="mask_actgn", action="store_true",
                      help="mask. Anything not [ACGTN] will be N.")

    parser.set_defaults(
        pattern_identifier="(^\S+)",
        methods=[],
        parameters="",
        filename_identifiers=None,
        filename_coordinates=None,
        mask_acgtn=False,
    )

    (options, args) = E.Start(parser)

    options.parameters = options.parameters.split(",")

    if not options.pattern_mali:
        raise ValueError(
            "Please specifiy a pattern to find the malis using --pattern-mali")

    ####################################################################
    ####################################################################
    ####################################################################
    # Read components
    ####################################################################
    map_seq_id2component, map_component2seq_id, map_component2input_id = \
        Malis.readComponents(options)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to mask
    ####################################################################
    map_component2masks = Malis.readMasks(options,
                                          map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to extract
    ####################################################################
    map_component2extracts = Malis.readExtracts(options,
                                                map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # read identifiers
    ####################################################################
    if options.filename_identifiers:
        identifiers, nerrors = IOTools.ReadList(
            open(options.filename_identifiers, "r"))
        identifiers_set = set(identifiers)
    else:
        identifiers = None
        identifiers_set = None

    ####################################################################
    ####################################################################
    ####################################################################
    # Prepare for run
    ####################################################################

    rx_identifier = re.compile(options.pattern_identifier)

    # build list of concatenated malis
    sequences = {}
    if identifiers:
        for id in identifiers_set:
            sequences[id] = []
    else:
        identifiers_set = set()
        for seq_id in map_seq_id2component.keys():
            id = rx_identifier.search(seq_id).groups()[0]
            sequences[id] = []
            identifiers_set.add(id)
        identifiers = list(identifiers_set)
        identifiers.sort()

    component_ids = map_component2seq_id.keys()
    component_ids.sort()

    if options.test:
        component_ids = component_ids[:options.test]

    ####################################################################
    ####################################################################
    ####################################################################
    # Build list of components to output.
    ####################################################################
    component_ids, map_sample2reference = \
        Malis.selectComponents(component_ids,
                               map_component2seq_id,
                               map_component2input_id,
                               None,
                               options)

    nskipped = 0
    new_component_ids = []

    for component_id in component_ids:

        try:
            mali = Malis.getMali(component_id,
                                 map_component2seq_id,
                                 map_component2input_id,
                                 None,
                                 options)
        except OSError, msg:
            E.warn("could not find mali %s: %s" % (component_id, msg))
            nskipped += 1
            continue

        ###############################################################
        ###############################################################
        ###############################################################
        # check if all identifiers in component are present in mali
        # and build a temporary alignment with all of those found
        component_set = set(map_component2seq_id[component_id])
        if len(component_set.difference(set(mali.getIdentifiers()))) != 0:
            nskipped += 1
            continue

        found = {}
        is_double = None
        temp_mali = Mali.Mali()
        temp_mali.setName(str(component_id))

        for seq_id in map_component2seq_id[component_id]:
            id = rx_identifier.search(seq_id).groups()[0]
            if id not in identifiers_set:
                continue
            if id in found:

                if options.skip_doubles:
                    E.infor("component %s: removed double entry %s\n" %
                            (component_id, seq_id))
                    continue
                else:
                    is_double = id
                    break

            if options.output_format == "codeml":
                if len(mali[seq_id]) % 3 != 0:
                    raise ValueError(
                        "length of sequence %s is not a multiple of 3: %i" %
                        (seq_id, len(mali[seq_id])))

            # change identifier to id
            found[id] = True
            entry = mali.getEntry(seq_id)
            temp_mali.addSequence(id, entry.mFrom, entry.mTo, entry.mString)

        if is_double:
            nskipped += 1
            E.info(("component %s: skipped because it "
                    "contains double entry %s") %
                   (component_id, is_double))
            continue

        if set(found.keys()) != identifiers_set:
            nskipped += 1
            E.info("component %s: skipped because incomplete: %s" %
                   (component_id, str(found.keys())))
            continue

        ###############################################################
        ###############################################################
        ###############################################################
        # mask the temporary alignment
        Malis.maskAlignment(temp_mali,
                            map_component2masks,
                            map_component2extracts,
                            map_sample2reference,
                            options)

        for id, o in temp_mali.items():
            if options.mask_acgtn:
                s = re.sub("[^ACGTNactgn]", "N", o.mString)
            else:
                s = o.mString
            sequences[id].append(s)

        new_component_ids.append(component_id)

        # if we only sample, stop if you have reached
        # the desired number
        if options.sample and len(new_component_ids) == options.sample:
            break
Beispiel #4
0
def main(argv=None):
    """script main.

    parses command line options in sys.argv, unless *argv* is given.
    """

    if argv is None:
        argv = sys.argv

    parser = E.OptionParser(
        version="%prog version: $Id$",
        usage=globals()["__doc__"])

    parser.add_option("-d", "--pattern-output",
                      dest="pattern_output",
                      type="string",
                      help="filename pattern for output multiple "
                      "alignment files.")

    parser.add_option("-f", "--filename-filter",
                      dest="filename_filter",
                      type="string",
                      help="filename with strings to filter by.")

    parser.add_option("--list-filter", dest="list_filter", type="string",
                      help="list of strings to filter by.")

    parser.set_defaults(
        pattern_output="%s.mali",
        methods="",
        parameters="",
        filename_filter=None,
        list_filter=None,
    )

    Malis.addOptions(parser)

    (options, args) = E.Start(parser)

    options.methods = options.methods.split(",")
    options.parameters = options.parameters.split(",")

    if not options.pattern_mali:
        raise "Please specifiy a pattern to find the malis using --pattern-mali"

    ####################################################################
    ####################################################################
    ####################################################################
    # Read components
    ####################################################################
    map_seq_id2component, map_component2seq_id, map_component2input_id = \
        Malis.readComponents(options)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read filtering information
    ####################################################################
    if options.filename_filter:
        id_filter, nerrors = IOTools.ReadList(
            open(options.filename_filter, "r"))
        if options.loglevel >= 1:
            options.stdlog.write(
                "# read %i identifiers to filter each multiple alignment with.\n" %
                len(id_filter))
            options.stdlog.flush()
    elif options.list_filter:
        id_filter = options.list_filter.split(",")
    else:
        id_filter = None

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to mask
    ####################################################################
    map_component2masks = Malis.readMasks(options, map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to extract
    ####################################################################
    map_component2extracts = Malis.readExtracts(
        options, map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Read regions to annotate
    ####################################################################
    map_component2annotations = Malis.readAnnotations(
        options, map_component2input_id)

    ####################################################################
    ####################################################################
    ####################################################################
    # Prepare for run
    ####################################################################
    component_ids = map_component2seq_id.keys()
    component_ids.sort()

    if options.loglevel >= 1:
        options.stdlog.write(
            "# %i component ids to start with.\n" % (len(component_ids)))

    component_ids, map_sample2reference = Malis.selectComponents(
        component_ids,
        map_component2seq_id,
        map_component2input_id,
        id_filter,
        options)

    if options.test:
        component_ids = component_ids[:options.test]

    if options.loglevel >= 1:
        options.stdlog.write(
            "# %i component ids selected for output.\n" % (len(component_ids)))

    ninput = 0
    noutput = 0
    nskipped = 0
    nskipped_length = 0

    for component_id in component_ids:

        ninput += 1

        if options.loglevel >= 3:
            options.stdlog.write(
                "# processing component %s\n" % (component_id))

        mali = Malis.getMali(component_id,
                             map_component2seq_id,
                             map_component2input_id,
                             id_filter,
                             options)

        if mali is None:
            E.warn("empty mali returned for component %s" % (component_id))
            nskipped += 1
            continue

        if mali.getNumColumns() == 0:
            E.warn("skipping output of empty alignment for component %s" %
                   (component_id))
            nskipped += 1
            continue

        mali.setName(str(component_id))

        ###############################################################
        # add annotations
        if map_component2annotations is not None:
            Malis.annotateAlignment(mali,
                                    map_component2annotations,
                                    options)

        ###############################################################
        # mask the alignment
        Malis.maskAlignment(mali,
                            map_component2masks,
                            map_component2extracts,
                            map_sample2reference,
                            options)

        if mali.getNumColumns() < options.minimum_mali_length:
            nskipped_length += 1
            if options.loglevel >= 1:
                options.stdlog.write("# component %s: skipped, because length %i less than threshold.\n" % (
                    component_id, mali.getNumColumns()))
            continue

        ###############################################################
        # prepare the mali for output
        if "%s" not in options.pattern_output:
            append = True
        else:
            append = False

        output_filename = re.sub("%s", component_id, options.pattern_output)
        input_id = map_component2input_id[component_id]

        if options.loglevel >= 2:
            options.stdlog.write("# component %s: input from %s, goes to %s\n" % (
                component_id, input_id, output_filename))

        dirname = os.path.dirname(output_filename)

        if dirname and not os.path.exists(dirname):
            os.makedirs(dirname)

        if not os.path.exists(output_filename):
            mali.writeToFile(
                open(output_filename, "w"), format=options.output_format)
            noutput += 1
        else:
            if append:
                mali.writeToFile(
                    open(output_filename, "a"), format=options.output_format)
                noutput += 1
            else:
                if options.loglevel >= 1:
                    options.stdlog.write("# skipping because output for component %s already exists: %s\n" % (
                        component_id, output_filename))
                nskipped += 1

        # if we only sample, stop if you have reached
        # the desired number
        if options.sample and noutput == options.sample:
            break

    E.info("ninput=%i, noutput=%i, nskipped=%i, nskipped_length=%i" %
           (ninput, noutput, nskipped, nskipped_length))

    E.Stop()