<!DOCTYPE html>


<html>

<head>
{% load static %}
{% load custom_tags %}
{% load crispy_forms_tags %}


{% include "chlamdb/header.html" %}
</head>


<body>
    <div class="container-fluid" id="main_container">
      <div class="row">
        <div id="wrapper">
          <div id="page-content-wrapper">
            <div class="row">
              <div class="col-lg-12">

                {% include "chlamdb/menu.html" %}
				{% include "chlamdb/extract_nav_tabs_template.html" with type="COG" active_tab="det" %}

                <br>
                <p class="page-title"><b>COGs shared by the selected genomes </b><a href="https://zdb.readthedocs.io/en/latest/tutorial/website.html#comparisons" id="show-option" target="_blank"  title="Get the list of COG categories shared between genomes (selected in panel A) and absent in others (selected in panel B)"><i class="fab fa-info-circle " style="size: 5em;" ></i></a></p></center>

               <div id="extract_form">

                  {% block content %}
				  {% csrf_token %}
				  {% crispy form %}
                  {% endblock %}
              </div>

                {% if wrong_n_missing%}

                <div class="panel panel-warning" style="width:500px ; top: 200px; margin: 10px 10px 10px 10px">
                    <div class="panel-heading" style="width:100%">
                        <h3 class="panel-title">Help</h3>
                    </div>
                    <p style="margin: 10px 10px 10px 10px">You cannot set a number of missing data bigger than the number of included genomes</p>
                </div>

                {% elif no_match%}

                <div class="panel panel-warning" style="width:500px ; top: 200px; margin: 10px 10px 10px 10px">
                    <div class="panel-heading" style="width:100%">
                        <h3 class="panel-title"></h3>
                    </div>
                    <p style="margin: 10px 10px 10px 10px">No match</p>
                </div>

                {% endif %}
               

                {% if envoi_extract %}

                <div class="row" style="background-color: rgba(245, 245, 245, 0.986)">
                    <div class="col-lg-12">
                      <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
                  <br>
                  <div class="panel panel-success" style="width:60%; top: 200px; margin: 10px 10px 10px 10px; float: left;">
                    <div class="panel-heading" style="width:100%">
                      <h3 class="panel-title">Help to interpret the results</h3>
                    </div>
                    <p style="margin: 10px 10px 10px 10px; line-height: 180%">Three outputs have been generated:
                      <br> <b>COGs</b> table:  it contains the list of COG categories shared among the selected genomes.
                      For each category the most frequent annotations and the number of occurences in the whole set database and in the selected genomes are reported.
                    <br><b> COG categories barchart</b>: this plot displays for each COG category in <span style="color: rgb(135, 186, 245)"><b>light-blue</b></span> the number of genes shared by the selected genomes, while in <span style="color: rgb(16, 76, 145)"><b>blue</b></span> , the total number of genes annotated with that COG in the selected genomes (shared and unique to each selected genome). Next to the light-blue barcharts there is a percentage value as the result of the number of reported COGs for each category divided by the number of shared COG in all categories, while next to the blue barcharts the value represents COGs count are divided by the total COGs unique and shared in the selected genomes.
                    <br>A longer light-blue bar can be interpreted as an enrichment of that shared COG category in the selected genomes compared to their complete COG profiles.
                    <br> <b>Locus list reference</b>            
                    </p>
                  </div>
                  <ul style="list-style-type:square">
                    <div style="padding-top:10px">

                       <table class="table" style="width:600px">
                           <tr>
                               <th>Number of included genomes</th>
                               <td> {{ include|length }} </td>
                           </tr>

                           <tr>
                               <th>Number of excluded genomes</th>
                               <td> {{ exclude|length }} </td>
                           </tr>

                            <tr>
                               <th>Number of accepted missing data</th>
                               <td> {{ n_missing }} </td>
                           </tr>
                             <tr>
                               <th>Number of COGs identified</th>
                               <td> {{ sum_group }}  </td>
                           </tr>

                       </table>
               
        
            
                <div class="col-lg-12">

                    <ul id="tabs" class="nav nav-tabs" data-tabs="tabs">
                        <li class="active"><a href="#red" data-toggle="tab">COGs</a></li>
						<li><a data-toggle="tab" href="#tab66">COG categories barchart</a></li>
                    </ul>


                    <div id="my-tab-content" class="tab-content">

                        <div class="tab-pane active" id="red">


                            <ul style="list-style-type:square">
                             <div style="padding-top:10px">

                              


                                <table class="display" id="cog_table">

                                    <thead>
                                        <tr>
                                            <th>COG</th>
                                            <th>Category</th>
                                            <th>Name</th>
                                            <th>present in (/{{include|length}})</th>
                                            <th>freq complete database (max: {{max_n}})</th>
                                        </tr>
                                    </thead>

                                    {% for value in cog_data %}
                                        <tr>
                                            <td><a href="{% url 'fam_cog' value.0 %}">{{value.0}}</a></td>
                                            <td>{{value.1|safe}}</td>
                                            <td>{{value.2}}</td>
                                            <td>{{value.3}}</td>
                                            <td>{{value.4}}</td>
                                        </tr>
                                    {% endfor %}
                                </table>
                            </div>

                        </div>


						<div class="tab-pane" id="tab66" style="margin-top: 2em;"> 
						<div id="content">

							<style>

							/*
							.chart rect {
							  fill: steelblue;
							}
							*/
							.chart .legend {
							  fill: black;
							  font: 14px sans-serif;
							  text-anchor: start;
							  font-size: 12px;
							}

							.chart text {
							  fill: black;
							  font: 10px sans-serif;
							  text-anchor: end;
							}

							.chart .label:hover {
							  fill: red;
							}

							.chart .label {
							  fill: black;
							  font: 10px sans-serif;
							  text-anchor: end;
							}


							.bar:hover {
							  fill: brown;
							}

							.axis path,
							.axis line {
							  fill: none;
							  stroke: #000;
							  shape-rendering: crispEdges;
							}


							</style>


							<div id="mydiv" style="float: left"></div>
							<svg class="chart" id="cog_cat_barchart"></svg>

							<script>

							var data = {
							  labels: {{labels|safe}},
							  series: {{series|safe}}
							};

							{{category_map|safe}}
							{{category_count_complete|safe}}

							var chartWidth       = 380,
								barHeight        = 10,
								groupHeight      = barHeight * data.series.length,
								gapBetweenGroups = 10,
								spaceForLabels   = 370,
								spaceForLegend   = 180;

							// Zip the series data together (first values, second values, etc.)
							var zippedData = [];
							for (var i=0; i<data.labels.length; i++) {
							  for (var j=0; j<data.series.length; j++) {
								zippedData.push(data.series[j].values[i]);
							  }
							}

							// Color scale
							var color = d3.scale.category20();
							var chartHeight = barHeight * zippedData.length + gapBetweenGroups * data.labels.length;

							var x = d3.scale.linear()
								.domain([0, d3.max(zippedData)])
								.range([0, chartWidth]);

							var y = d3.scale.linear()
								.range([chartHeight + gapBetweenGroups, 0]);

							var yAxis = d3.svg.axis()
								.scale(y)
								.tickFormat('')
								.tickSize(0)
								.orient("left");

							// Specify the chart area and dimensions
							var chart = d3.select(".chart")
								.attr("width", spaceForLabels + chartWidth + spaceForLegend)
								.attr("height", chartHeight);

							// Create bars
							var bar = chart.selectAll("g")
								.data(zippedData)
								.enter().append("g")
								.attr("transform", function(d, i) {
								  return "translate(" + spaceForLabels + "," + (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i/data.series.length))) + ")";
								}
								)
								 //   Math.floor(i/data.series.length)
								.attr("taxon_id", function(d,i) { return (i % data.series.length) ; })
								.attr("category_id", function(d,i) { return (Math.floor(i/data.series.length)) ; });


							// Create rectangles of the correct width
							bar.append("rect")
								.attr("fill", function(d,i) { return color(i % data.series.length); })
								.attr("class", "bar")
								.attr("width", x)
								.attr("height", barHeight - 1)
								.on("click",drill);


							// Add text label in bar
							bar.append("text")
								.attr("x", function(d) { return x(0); })
								.attr("y", barHeight / 2)
								.attr("fill", "red")
								.attr("dy", ".35em")
								.text(function(d) { return d; });

							bar.append("text")
								.attr("x", function(d) { return x(d); })
								.attr("y", barHeight / 2)
								.attr("fill", "red")
								.attr("dy", ".35em")
								.text(function(d, i) { return category_count_complete[data.labels[Math.floor(i/data.series.length)]][i % data.series.length]; }); // category_count_complete[data.labels[Math.floor(i/data.series.length)]]

							// Draw labels
							bar.append("text")
								.attr("class", "label")
								.attr("x", function(d) { return - 40; })
								.attr("y", groupHeight / 2)
								.attr("dy", ".35em")
								.text(function(d,i) {
								  if (i % data.series.length === 0)
									return (category_description[data.labels[Math.floor(i/data.series.length)]] + " (" +data.labels[Math.floor(i/data.series.length)] + ")");
								  else
									return ""});

							function drill(d, i) {

								var category = data.labels[d3.select(this.parentNode).attr("category_id")]; //data object
								console.log(category);
								window.open("/chlamdb/get_cog_multiple/" + category + "/{{accessions}}/{{taxons_in_url|safe}}" + "{{taxon_out_url|safe}}");
							}

							chart.append("g")
								  .attr("class", "y axis")
								  .attr("transform", "translate(" + spaceForLabels + ", " + -gapBetweenGroups/2 + ")")
								  .call(yAxis);

							// Draw legend
							var legendRectSize = 18,
								legendSpacing  = 4;

							var legend = chart.selectAll('.legend')
								.data(data.series)
								.enter()
								.append('g')
								.attr('transform', function (d, i) {
									var height = legendRectSize + legendSpacing;
									var offset = -gapBetweenGroups/2;
									var horz = spaceForLabels + chartWidth + 40 - legendRectSize;
									var vert = i * height - offset;
									return 'translate(' + horz + ',' + vert + ')';
								});

							legend.append('rect')
								.attr('width', legendRectSize)
								.attr('height', legendRectSize)
								.style('fill', function (d, i) { return color(i); })
								.style('stroke', function (d, i) { return color(i); });

							legend.append('text')
								.attr('class', 'legend')
								.attr('x', legendRectSize + legendSpacing)
								.attr('y', legendRectSize - legendSpacing)
								.text(function (d) { return d.labels; });

							d3.select("#mydiv").append("button")
									.attr("type","button")
									.attr("class", "btn btn-primary btn-sm")
									.text("Download SVG")
									.on("click", function() {
										var svg_elem = document.querySelector("#cog_cat_barchart");
										svgExport.downloadSvg(svg_elem, "cog_bar_plot");
									});

							</script>
						</div>


						</div>
                    </div>
                {% endif %}
            </div>
        </div>
      </div>
    </div>
  </div>
</div>

</body>

{% include "chlamdb/style_menu.html" %}
{% include "chlamdb/show_hide_plasmid_accessions.html" %}

<style>

#div_id_checkbox_single_copy{
  display: none;
}

</style>

<script>

$(document).ready(function() {
$('#cog_table').DataTable( {
	 dom: 'Bfrtip',   
	"paging":   true,
	"ordering": true,
	"info":     false,
	buttons: [{ extend: 'excel', title: 'cog_table'},
			  {extend: 'csv', title: 'cog_table'}]});
});

</script>
</html>
