#!/opt/gensoft/exe/iCLIPro/0.1.1/venv/bin/python2.7

import getopt, sys, os
import iCLIPro

BIN_SIZE = 300 # genomic bin size
BIN_SIZE_MIN = 100
BIN_SIZE_MAX = 1000

BIN_MIN_READS = 50 # minimum number of reads for bin to be considered
BIN_MIN_READS_MIN = 20
BIN_MIN_READS_MAX = 500

OVERLAP_RATIO_FLANK = 5
OVERLAP_RATIO_FLANK_MIN = 3
OVERLAP_RATIO_FLANK_MAX = 15

MAPQ_TH = 10
MAPQ_TH_MIN = 0
MAPQ_TH_MAX = 100

READ_LEN_GROUPS = "A:16-39,A1:16-25,A2:26-32,A3:33-39,L:20,B:42"
GROUP_COMPARISONS = "A1-A3,A2-A3,A1-B,A2-B,A3-B,L-B,A-B"
GROUP_COMPARISONS_FLANK = 50

cur_dir = os.getcwd()

def usage(longer=False):
    if longer:
        print "iCLIPro usage"
        print "============="
        print

    print "Usage: iCLIPro [options] in.bam"
    print
    print "Options:"
    print "    -o FOLDER  output folder (default is cwd - current working directory)"
    print "    -b INT     genomic bin size (%s..%s, default: %s)" % (
          BIN_SIZE_MIN, BIN_SIZE_MAX, BIN_SIZE)
    print "    -r INT     number of reads required in bin (%s..%s, default: %s)" % (
          BIN_MIN_READS_MIN, BIN_MIN_READS_MAX, BIN_MIN_READS)
    print "    -s INT     flanking distances when calculating start site overlap ratio (%s..%s, default: %s)" % (
          OVERLAP_RATIO_FLANK_MIN, OVERLAP_RATIO_FLANK_MAX, OVERLAP_RATIO_FLANK)
    print "    -q INT     use only reads with minimum mapping quality (mapq) (%s..%s, default: %s)" % (
          MAPQ_TH_MIN, MAPQ_TH_MAX, MAPQ_TH)
    print "    -g LIST    read len groups (e.g.: \"%s\")" % READ_LEN_GROUPS
    print "    -p LIST    generate read overlap maps based on these\n"
    print "               comparisons (e.g.: \"%s\")" % GROUP_COMPARISONS
    print "    -f INT     flanking region for read overlap maps (default: %s)" % GROUP_COMPARISONS_FLANK
    print "    -h         longer help"
    print

    if longer:
        print """\
For given input BAM file [in.bam] the script will generate
a number of output files that can be used to check for and diagnose
systematic misassignments in iCLIP data.

Main result is stored in file [in_report.txt], for given [in.bam] BAM file.

Read (query template) names in BAM files should include a record
of form expressed with this regular expression: ``:rbc[ATCGN]+:``.
The ending colon can be omitted if random barcode record is placed
at the end of the name. Some valid examples::

   D3FCO8P1:206:C2M53ACXX:8:1207:17086:80291:1:N:0:rbcTGTAC: 272     1       11861 ... 
   D3FCO8P1:206:C2M53ACXX:8:1101:6625:73240:1:N:0:rbcCCGCC   16      1       11976 ...
   D3FCO8P1:206:C2M53ACXX:8:1203:17298:81179:rbcCCGCC:1:N:0  16      1       11976 ...

Random barcodes can be specified at the end of the name but
must be preceded by colon, for example::

   D3FCO8P1:206:C2M53ACXX:8:1207:17086:80291:1:N:0:TGTAC     272     1       11861 ... 
   D3FCO8P1:206:C2M53ACXX:8:1101:6625:73240:1:N:0   :CCGCC   16      1       11976 ...
   D3FCO8P1:206:C2M53ACXX:8:1203:17298:81179:1:N:0 :CCGCC    16      1       11976 ...

If no random barcode information is available, then iCLIPro will
most likely be able to work with the original read names. In such
case, please check that the read names do not include any text
that conforms to the rules for specifying random barcode as it
may mislead iCLIPro.

The generated report file includes a list of random barcodes
identified by iCLIPro. You should check it first and make sure
that proper random barcode information is being used.

Parameters -b and -r:
  Specifies the bin size to use when segmenting the genome.
  Only bins with enough reads (parameter -r) are then considered
  in the read overlap testing.

Parameter -s:
  Flanking region when calculating the mean and the median start
  site overlap ratios.

Parameter -q:
  Consider only reads that pass the minimum mapping quality,
  ignore the rest.

Parameter -g:
  iCLIPro needs to group reads based on their length.
  Any number of (overlapping) groups can be specified. For each
  group, an interval (INT1-INT2) or single value (INT) of the
  read lengths in the group can be specified.

Parameter -p (read overlap maps):
  Specifies which groups of reads to compare. When performing a
  comparison (G1-G2), cross-linked sites identified based on
  group G2 are used as reference (zero position). The relative
  positioning of sites identified in G1 is the computed and
  shown in read overlap maps.

Parameter -f:
  Width of the flanking region relative to reference point
  shown in read overlap maps.


Method
^^^^^^

A typical (i)CLIP experiment may result in the detection of RNA
fragments of different lengths. Under the assumptions of
conventional iCLIP, the start sites of iCLIP fragments should
coincide at the cross-linking position in a fragment
length-independent fashion.

This interpretation may not hold for some iCLIP libraries (e.g.,
substantial read-through, binding to long RNA stretches etc). For
details, see associated paper by Hauer and coauthors. In summary,
we identified a previously unrecognized effect of iCLIP fragment
length on the position of fragment start sites and thus assigned
binding sites for some RBPs.

iCLIPro is a robust analysis approach that examines this effect
and thus can improve the assignment of binding sites from iCLIP
data.

iCLIPro's main function is to visualize coinciding and
non-coinciding fragment start sites in order to examine the best
way how to analyze iCLIP data.

With iCLIPro you can test test and compare the overlap of
different reference points in the iCLIP fragments:
   * one nucleotide before first mapped nucleotide (conventional assumption)
   * center of the read
   * end of the read

iCLIPro identifies regions (bins in genome, parameter -b) with a
sufficient number of reads (parameter -r) for an read overlap
test. Reads from each selected bin are processed separately.
Reads get grouped based on their length (parameter -g) and sites
from different groups are compared.

The main output of iCLIPro are read overlap heatmaps that
identify the best mode of analysis.


Read overlap heatmaps
^^^^^^^^^^^^^^^^^^^^^

Read overlap maps are generated by comparing fragment start,
center and end sites in the *test* and *reference* groups.

The data underlying the high-resolution overlap heatmaps is
used to calculate a ratio of overlapping and non-overlapping
start sites thus enabling the decision to be made as to whether
the start or the center of the fragments should be used as a
reference point for most accurately defining the binding site.
This overlap start site ratio is reported at the end of the
generated report file. When calculating the start site overlap
ratio a default flanking distance of 5 nt is used
(parameter -s, see paper).

A ratio well above 1 suggests to use the start sites of iCLIP
fragments to detect binding sites (e.g., mean overlap start
site ratio of 1.31 for U2AF65). A ratio below 1 favors the
use of the center position for binding site assignment
(e.g., mean overlap start site ratio of 0.88 for eIF4A3,
see paper for details).

Sites identified based on a reference group are used to define 
the reference (zero) position in the map. The regions (-50 to +50, 
x-axis on plots, parameter -f) relative to the reference positions
are then scanned and number of co-occuring sites in test group is recorded.

The x-axis shows the offset of the sites of the test group
(shorter reads) relative to the sites of the reference group
(usually longer reads). The y-axis shows the fragment length.
The color in the heatmap represents the number of fragments
that co-occur at a given offset relative to the longer reference
fragments. 

In case of the fragment start sites, a peak at the start reference
position 0 corresponds to coinciding start sites, whereas a
distribution downstream of the reference position 0 arises from
start sites of smaller fragments that occur at length-dependent
offsets from the reference start sites.


"""

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:b:r:s:q:g:p:f:", [])
    except getopt.GetoptError as err:
        usage()
        sys.exit(2)

    output_folder = cur_dir
    bin_size = BIN_SIZE
    bin_min_reads = BIN_MIN_READS
    overlap_ratio_flank = OVERLAP_RATIO_FLANK 
    mapq_th = MAPQ_TH
    readlen_groups = "" # READ_LEN_GROUPS
    group_comparisons = "" #GROUP_COMPARISONS
    group_comparisons_flank = GROUP_COMPARISONS_FLANK
    # TODO: check if parameter value is within range

    for opt, arg in opts:
        if opt == '-h':
            usage(True)
            sys.exit()
        elif opt in ("-o"):
            output_folder = arg
        elif opt in ("-b"):
            bin_size = int(arg)
        elif opt in ("-r"):
            bin_min_reads = int(arg)
        elif opt in ("-s"):
            overlap_ratio_flank = int(arg)
        elif opt in ("-q"):
            mapq_th = int(arg)
        elif opt in ("-g"):
            readlen_groups = arg
        elif opt in ("-p"):
            group_comparisons = arg
        elif opt in ("-f"):
            group_comparisons_flank = int(arg)

    in_bam_files = args
    if not in_bam_files:
        print "Error: no input BAM file specified."
        print
        usage()
        sys.exit(2)
    if len(in_bam_files) > 1:
        print "Error: only one input BAM file must be given."
        print
        usage()
        sys.exit(2)

    all_present = True
    for fn in in_bam_files:
        if not os.path.isfile(fn):
            print "Error: specified BAM file does not exist: '%s'" % fn
            all_present = False
    if not all_present:
        print
        usage()
        sys.exit(2)

    readlen2groups = iCLIPro.cmd_utils.parse_readlen_groups(readlen_groups)
    if readlen2groups is None:
        print "Error: specified read length groups cannot be parsed: \"%s\"" % (readlen_groups)
        print
        usage()
        sys.exit(2)

    group_comparisons_list = iCLIPro.cmd_utils.parse_group_comparisons(group_comparisons, readlen2groups)
    if group_comparisons_list is None:
        print "Error: specified group comparisons cannot be parsed: \"%s\"" % (group_comparisons)
        print
        usage()
        sys.exit(2)

    if not (OVERLAP_RATIO_FLANK_MIN <= overlap_ratio_flank <= OVERLAP_RATIO_FLANK_MAX):
        print "Error: parameter -c value (%s) not within range %s..%s" % (overlap_ratio_flank, OVERLAP_RATIO_FLANK_MIN, OVERLAP_RATIO_FLANK_MAX)
        print
        usage()
        sys.exit(2)

    print "Running iCLIP reads overlap test using following parameters:"
    print "    output_folder (-o) = '%s'" % output_folder
    print "    bin_size (-b) = %s" % bin_size
    print "    bin_min_reads (-r) = %s" % bin_min_reads
    print "    overlap_ratio_flank (-c) = %s" % overlap_ratio_flank
    print "    minimum mapq (-q) = %s" % mapq_th
    print "    read length to group(s) (-g):"
    grp2readlens = {}
    for readlen, grps in sorted(readlen2groups.iteritems()):
        for grp in grps:
            grp2readlens.setdefault(grp, []).append(readlen)
    for grp, readlens in sorted(grp2readlens.iteritems()):
        print "        %s: %s" % (grp, sorted(readlens))
    print "    groups to compare (-p) = %s" % group_comparisons_list
    print "    flanking region for comparisons graphs (-f) = %s" % group_comparisons_flank
    print

    for in_bam_file in in_bam_files:
        print "Processing file:", in_bam_file
        sys.stdout.flush()
        iCLIPro.overlap_test(in_bam_file, output_folder, bin_size, bin_min_reads,
                             overlap_ratio_flank, readlen2groups, group_comparisons_list,
                             mapq_th=mapq_th, group_comparisons_flank=group_comparisons_flank)
    print "DONE"

if __name__ == "__main__":
    main()

