def drawMatrix(data):
    panel = markup.page()
    helper.link_css_and_js(panel)
    full_names = {'dom': 'Domesticus', 'mus': 'Musculus', 'cas': 'Castaneus', 'unk': 'Unknown'}
    panel.table()
    panel.tr()
    panel.td('')
    panel.td("Distal interval: Chromosome {}: {:,} - {:,}".format(*tuple(data['Intervals'][1])))
    panel.tr.close()
    panel.tr()
    panel.td("Proximal interval: Chromosome {}: {:,} - {:,}".format(*tuple(data['Intervals'][0])))
    panel.td()
    panel.table(_class="table table-striped")
    panel.tr()
    panel.th('')
    for subspecies in data['Key']:
        panel.th(full_names[subspecies])
    panel.tr.close()
    for subspecies, samples in zip(data['Key'], data['Samples']):
        panel.tr()
        panel.th(full_names[subspecies])
        for sample_set in samples:
            panel.td(', '.join(sample_set) or '-')
        panel.tr.close()
    panel.table.close()
    panel.td.close()
    panel.tr.close()
    panel.table.close()
    return panel
def indexPage(form):
    tl = twolocus.TwoLocus("/csbiodata/public/www.csbio.unc.edu/htdocs/sgreens/pairwise_origins/")
    panel = markup.page()
    helper.link_css_and_js(panel)
    panel.div(style="padding:20px 20px;")
    user, permissionLevel, date, time, elapsed = cgAdmin.getCompgenCookie(form)
    editFlag = form.getvalue("edit") == "True"
    if permissionLevel >= 80:
        panel.add(WikiApp.editTag("%s" % this_file, not editFlag))
    panel.add(
        WikiApp.getWikiContent(
            "%s" % this_file, editInPlace=(permissionLevel >= 80) and editFlag, returnPage="./?run=%s" % this_file
        )
    )
    panel.br()
    panel.form(_class="form-horizontal", action="", method="POST", enctype="multipart/form-data")
    panel.div(_class="control-group")
    panel.h3("Set of Samples")
    has_strains = helper.strain_set_selector(panel, tl)
    panel.script(type="text/javascript")
    panel.add("""$(".chosen").chosen()""")
    panel.script.close()
    helper.select_all_buttons(panel)
    panel.br()
    panel.input(type="hidden", name="target", value="%s.originsVisualization" % this_file)
    panel.input(type="submit", name="submit", value="Submit")
    panel.div.close()  # control group
    panel.form.close()
    panel.div.close()
    panel.script("""$("form").submit(function(event) {return %s(event);});""" % has_strains, type="text/javascript")
    return panel
def uniqueCombosResponse(form):
    # print "content-type: text/json\n"
    tl = twolocus.TwoLocus("/csbiodata/public/www.csbio.unc.edu/htdocs/sgreens/pairwise_origins/")
    strains = [[], []]
    for set_num, set_id in enumerate(["background", "foreground"]):
        for _, _, value, _ in helper.STRAIN_SETS:
            new_strains = form.getvalue(value + set_id)
            if type(new_strains) is list:
                strains[set_num] += new_strains
            elif new_strains is not None:
                strains[set_num].append(new_strains)
    # print '\n'.join(hex(line[0]) + ' ' + ' '.join(map(str, line[1:])) for line in tl.unique_combos(strains[0], strains[1]))
    data = json.dumps(tl.unique_combos(strains[0], strains[1]), cls=helper.NumpyEncoder)
    # with open('unique.json', "w+") as fp:
    # with open('unique.json', "r") as fp:
    # json.dump(tl.unique_combos(strains[0], strains[1]), fp, cls=helper.NumpyEncoder)
    # data = json.load(fp)
    # data = '0'
    # panel = markup.page()
    # panel.iframe(src='../sgreens/pairwise_origins/pairwiseGenome.html', chartWidth="100%", chartHeight="1000px")
    # return panel
    # print "content-type: text/html\n"
    # with open('../sgreens/pairwise_origins/pairwiseGenome.html') as fp:
    #     print fp.read()<!DOCTYPE html>
    helper.visualize_genome(data, tl)
def indexPage(form):
    tl = twolocus.TwoLocus('/csbiodata/public/www.csbio.unc.edu/htdocs/sgreens/pairwise_origins/')
    panel = markup.page()
    helper.link_css_and_js(panel)
    panel.div(style="padding:20px 20px;")
    user, permissionLevel, date, time, elapsed = cgAdmin.getCompgenCookie(form)
    editFlag = (form.getvalue("edit") == "True")
    if permissionLevel >= 80:
        panel.add(WikiApp.editTag("%s" % this_file, not editFlag))
    panel.add(WikiApp.getWikiContent("%s" % this_file, editInPlace=(permissionLevel >= 80) and editFlag,
                                     returnPage="./?run=%s" % this_file))
    panel.br()
    panel.form(_class="form-horizontal", action="", method="POST", enctype="multipart/form-data")
    panel.div(_class="control-group")
    panel.h3('Set of Samples')
    has_strains = helper.strain_set_selector(panel, tl)
    for pos_num in ('1', '2'):
        panel.h3('Position ' + pos_num)
        helper.open_control(panel, 'Chromosome')
        panel.select(_class="medium", name="chrom" + pos_num)
        for chrom_num in xrange(1, 19):
            panel.option(chrom_num)
        panel.option('X', value='X')
        panel.select.close()
        helper.close_control(panel)
        helper.open_control(panel, 'Position')
        panel.add('''<input class="input-medium" name="pos%s" required pattern="\d+[\d,]*\.?\d*[mMkK]*">'''
                  % pos_num)
        panel.add("""<p class="help-block">3000000 = 3,000,000 = 3m = 3M = 3000k = 3KK</p>""")
        helper.close_control(panel)
    panel.script(type="text/javascript")
    panel.add("""$(".chosen").chosen()""")
    panel.script.close()
    helper.select_all_buttons(panel)
    panel.br()
    panel.input(type="hidden", name="target", value="%s.countMatrix" % this_file)
    panel.input(type="submit", name="submit", value="Submit")
    panel.div.close()  # control group
    panel.form.close()
    panel.div.close()
    chromo_sizes = {}
    for string, integer in twolocus.CHROMO_TO_INT.iteritems():
        chromo_sizes[string] = tl.sizes[integer-1]
    panel.script('''
    var chromoSizes = %s;
    ''' % json.dumps(chromo_sizes), type="text/javascript")
    panel.script('''
    function parsePosition(string) {
        string = string.replace(',','').toLowerCase();
        var pos = parseFloat(string);
        var units = '';
        var char
        for (var i = 0; i < string.length; i++) {
            char = string[i];
            if (char == 'm' || char == 'k') {
                pos = parseFloat(string.substring(0, i));
                units = string.substring(i);
                break;
            }
        }
        for (i = 0; i < units.length; i++) {
            char = units[i];
            if (char == 'k') {
                pos *= 1000;
            }
            if (char == 'm') {
                pos *= 1000000;
            }
        }
        return Math.floor(pos);
    }

    function isValidIndex(chromosome, position) {
        return (chromosome in chromoSizes) && (0 <= position) && (position <= chromoSizes[chromosome]);
    }

    $("form").submit(function(event) {
        var chrom, pos;
        isValidInput = true;
        for (var i = 1; i <= 2; i++) {
            chrom = document.getElementsByName('chrom' + i)[0].value;
            pos = parsePosition(document.getElementsByName('pos' + i)[0].value);
            if (!isValidIndex(chrom, pos)) {
                alert("Position " + i + " exceeds chromosome length");
                isValidInput = false;
            }
        }
        return %s(event) && isValidInput;
    });
    ''' % has_strains, type="text/javascript")
    return panel
def originsVisualizationResponse(form):
    # print "content-type: text/json\n"
    coarse_cutoff = 1e7
    panel = markup.page()
    plot_file = "ss_origins.html"
    bokeh.plotting.output_file(plot_file)
    tl = twolocus.TwoLocus("/csbiodata/public/www.csbio.unc.edu/htdocs/sgreens/pairwise_origins/")
    strains = []
    for _, _, value, _ in helper.STRAIN_SETS:
        new_strains = form.getvalue(value)
        if type(new_strains) is list:
            strains += new_strains
        elif new_strains is not None:
            strains.append(new_strains)
    data, colors = tl.pairwise_frequencies(strains)
    absent_regions = tl.absent_regions(strains)
    plot = bokeh.plotting.figure(
        y_range=bokeh.models.Range1d(start=tl.offsets[-1] + 10e7, end=0),
        height=750,
        width=750,
        background_fill_color="black",
        tools=[
            "tap",
            "resize",
            bokeh.models.HoverTool(names=["chroms"], tooltips=[("Proximal", "@proximal"), ("Distal", "@distal")]),
        ],
    )
    plot.axis.visible = False
    plot.grid.grid_line_color = None
    for combo_regions, color in zip(data, colors):
        region_widths = np.subtract(combo_regions[1], combo_regions[0])
        region_heights = np.subtract(combo_regions[3], combo_regions[2])
        coarse_indices = np.logical_or(region_widths > coarse_cutoff, region_heights > coarse_cutoff)
        region_widths = region_widths[coarse_indices]
        region_heights = region_heights[coarse_indices]
        x_positions = np.add(np.array(combo_regions[0])[coarse_indices], region_widths / 2)
        y_positions = np.add(np.array(combo_regions[2])[coarse_indices], region_heights / 2)
        plot.rect(
            x_positions,
            y_positions,
            region_widths,
            region_heights,
            color="#" + hex(color)[2:].zfill(6),
            fill_alpha=1.0 / len(strains),
            line_alpha=0,
        )
        break
    for combo_regions in absent_regions:
        region_widths = np.subtract(combo_regions[1], combo_regions[0])
        region_heights = np.subtract(combo_regions[3], combo_regions[2])
        coarse_indices = np.logical_or(region_widths > coarse_cutoff, region_heights > coarse_cutoff)
        region_widths = region_widths[coarse_indices]
        region_heights = region_heights[coarse_indices]
        x_positions = np.add(np.array(combo_regions[0])[coarse_indices], region_widths / 2)
        y_positions = np.add(np.array(combo_regions[2])[coarse_indices], region_heights / 2)
        plot.rect(x_positions, y_positions, region_widths, region_heights, color="white")
        break
    chrom_data = dict(x=[], y=[], width=[], height=[], proximal=[], distal=[])
    for i in xrange(len(tl.sizes)):
        for j in xrange(i, len(tl.sizes)):
            chrom_data["x"].append(tl.offsets[i] + tl.sizes[i] / 2)
            chrom_data["y"].append(tl.offsets[j] + tl.sizes[j] / 2)
            chrom_data["width"].append(tl.sizes[i])
            chrom_data["height"].append(tl.sizes[j])
            chrom_data["proximal"].append(twolocus.INT_TO_CHROMO[i + 1])
            chrom_data["distal"].append(twolocus.INT_TO_CHROMO[j + 1])
    chrom_data_source = bokeh.models.ColumnDataSource(data=chrom_data)
    plot.rect(
        x="x",
        y="y",
        width="width",
        height="height",
        fill_alpha=0,
        line_color="grey",
        hover_alpha=0.5,
        name="chroms",
        source=chrom_data_source,
    )
    text_offsets = tl.offsets.copy()[:-1]
    text_offsets[-3] += 5e7
    plot.text(
        x=-15e7,
        y=[offset + 10e7 for offset in text_offsets],
        text=twolocus.INT_TO_CHROMO[1:],
        text_color="white",
        text_font_size="10pt",
    )
    plot.text(
        x=text_offsets,
        y=tl.offsets[-1] + 10e7,
        text=twolocus.INT_TO_CHROMO[1:],
        text_color="white",
        text_font_size="8pt",
    )
    inset_plot = bokeh.plotting.figure()
    inset_plot.x_range.bounds = "auto"
    inset_plot.y_range.bounds = "auto"
    inset_data_source = bokeh.models.ColumnDataSource(data=dict(x=[], y=[], width=[], height=[]))
    inset_plot.rect("x", "y", "width", "height", color="black")
    bokeh.plotting.show(bokeh.io.hplot(plot, inset_plot))
    with open(plot_file) as fp:
        panel.add(fp.read())
    return panel
    helper.visualize_genome(data, tl, len(strains))