Commit 2c96971b authored by jhoogenboom's avatar jhoogenboom
Browse files

Introducing Vis

* New tool Vis creates an interactive visualisation in HTML format,
  or a bare Vega graph spec (JSON format). The user can choose to
  supply a data file that will be embedded in the visualisation
  file. If no data file is given, the HTML visualisation will offer
  a file selection element, or the bare JSON output will refer to a
  file called 'data.csv'.
* Changes to Samplevis:
  * The Options box can now be opened/closed.
  * Added options to change the width of the bars and the space
    between subgraphs (markers).
  * Added options to filter by read count or percentage vs the
    highest allele of the marker.
  * Replaced deprecated 'zip' data transforms in the Vega spec with
    the new 'lookup' transform.
* Updated bundled Vega to v2.1.1.
parent 300549e0
#!/usr/bin/env python
"""
Create a data visualisation web page or Vega graph specification.
With no optional arguments specified, a self-contained web page (HTML
file) is produced. You can open this file in a web browser to view
interactive visualisations of your data. The web page contains a file
selection element which can be used to select the data to be visualised.
Visualisations make use of the Vega JavaScript library
(https://vega.github.io). The required JavaScript libraries (Vega and
D3) are embedded in the generated HTML file. With the -O/--online
option specified, the HTML file will instead link to the latest version
of these libraries on the Internet.
Vega also supports generating visualisations on the command line, which
is useful if you wish to generate graphs automatically in your analysis
pipeline. Specify the -V/--vega option to obtain a bare Vega graph
specification (a JSON file) instead of the full-featured HTML file. You
can pass this file through Vega to generate a PNG or SVG image file.
If an input file is specified, the visualisation will be set up
specifically to visualise the contents of this file. To this end, the
entire file contents are embedded in the generated visualisation.
"""
import argparse
import sys
import json
import re
import os
import cgi
from pkg_resources import resource_stream, resource_string
from ..lib import pos_int_arg
__version__ = "0.1dev"
# Default values for parameters are specified below.
# Default minimum number of reads to require.
# This value can be overridden by the -n command line option.
_DEF_THRESHOLD_ABS = 15
# Default minimum amount of reads to require, as a percentage of the
# highest allele of each marker.
# This value can be overridden by the -m command line option.
_DEF_THRESHOLD_PCT = 0.5
# Default width of bars in bar graphs, in pixels.
# This value can be overridden by the -b command line option.
_DEF_BAR_WIDTH = 15
# Default amount of padding between subgraphs, in pixels.
# This value can be overridden by the -p command line option.
_DEF_SUBGRAPH_PADDING = 70
# Default data file that Vega will read when -V/--vega is specified
# without providing data to embed in the file.
# It is currently impossible to override this value.
_DEF_DATA_FILENAME = "data.csv"
_PAT_LOAD_SCRIPT = re.compile("<!--\s*BEGIN_LOAD_SCRIPT\s*-->\s*(.*?)\s*"
"<!--\s*END_LOAD_SCRIPT\s*-->", flags=re.DOTALL)
_PAT_LIBRARIES = re.compile("<!--\s*BEGIN_LIBRARIES\s*-->\s*(.*?)\s*"
"<!--\s*END_LIBRARIES\s*-->", flags=re.DOTALL)
_SCRIPT_BEGIN = '<script type="text/javascript">'
_SCRIPT_END = '</script>'
_EXTERNAL_LIBRARIES = ("vis/d3.min.js", "vis/vega.min.js")
def set_data_formula_transform_value(spec, dataname, fieldname, value):
for data in spec["data"]:
if data["name"] != dataname:
continue
if "transform" not in data:
return False
for transform in data["transform"]:
if (transform["type"] == "formula" and
transform["field"] == fieldname):
transform["expr"] = str(value)
return True
return False
#set_data_formula_transform_value
def create_visualisation(vistype, infile, outfile, vega, online, tidy,
min_abs, min_pct, bar_width, padding):
# Get graph spec.
spec = json.load(resource_stream(
"fdstools", "vis/%svis/%svis.json" % (vistype, vistype)))
if infile is not None:
# Embed the given data file.
spec["data"][0]["values"] = infile.read()
elif vega:
# Vega should load data from somewhere in headless mode.
del spec["data"][0]["values"]
spec["data"][0]["url"] = _DEF_DATA_FILENAME
# Apply settings.
if vistype == "sample":
set_data_formula_transform_value(
spec, "yscale", "barwidth", bar_width)
set_data_formula_transform_value(
spec, "yscale", "markeroffset", padding)
set_data_formula_transform_value(
spec, "table", "amplitude_threshold", min_abs)
set_data_formula_transform_value(
spec, "table", "amplitude_pct_threshold", min_pct)
# Stringify spec.
if tidy:
spec = json.dumps(spec, indent=2, separators=(",", ": "))
else:
spec = json.dumps(spec, separators=(",", ":"))
if vega:
# Vega graph spec is all that we were asked for.
outfile.write(spec)
return
# Creating a fully self-contained HTML visualisation instead.
html = resource_string("fdstools", "vis/%svis/index.html" % vistype)
match = _PAT_LOAD_SCRIPT.search(html)
if match:
html = "".join([html[:match.start(1)],
_SCRIPT_BEGIN,
"var graph_spec=",
spec,
";onLoadSpec(",
"true" if infile is not None else "false",
");",
_SCRIPT_END,
html[match.end(1):]])
if not online:
# Replace external libraries with inline libraries.
match = _PAT_LIBRARIES.search(html)
if match:
parts = [html[:match.start(1)]]
for library in _EXTERNAL_LIBRARIES:
parts += [_SCRIPT_BEGIN,
resource_string("fdstools", library),
_SCRIPT_END]
parts.append(html[match.end(1):])
html = "".join(parts)
outfile.write(html)
#create_visualisation
def add_arguments(parser):
parser.add_argument('type', metavar="TYPE", choices=("sample",),
help="the type of data to visualise: one of %(choices)s")
parser.add_argument('infile', metavar="IN", nargs="?",
help="file containing the data to embed in the visualisation file; if "
"not specified, HTML visualisation files will contain a file "
"selection control, and Vega visualisation files will load data "
"from a file called '%s'" % _DEF_DATA_FILENAME)
parser.add_argument('outfile', metavar="OUT", nargs="?",
type=argparse.FileType('w'),
default=sys.stdout,
help="file to write output to (default: write to stdout)")
parser.add_argument('-V', '--vega', action="store_true",
help="an HTML file containing an interactive visualisation is created "
"by default; if this option is specified, a Vega graph "
"specification (JSON file) is produced instead")
parser.add_argument('-O', '--online', action="store_true",
help="when generating an HTML visualisation file, required JavaScript "
"libraries (D3 and Vega) are embedded in the file; if this "
"option is specified, the HTML file will instead link to these "
"libraries on the Internet, thereby always using the latest "
"versions of D3 and Vega")
parser.add_argument('-t', '--tidy', action="store_true",
help="tidily indent the generated JSON")
samplevis = parser.add_argument_group("sample visualisation options",
description="used when TYPE=sample")
samplevis.add_argument('-n', '--min-abs', metavar="N", type=pos_int_arg,
default=_DEF_THRESHOLD_ABS,
help="only show alleles with this minimum number of reads (default: "
"%(default)s)")
samplevis.add_argument('-m', '--min-pct', metavar="PCT", type=float,
default=_DEF_THRESHOLD_PCT,
help="only show alleles with at least this percentage of the number "
"of reads of the highest allele of a marker (default: "
"%(default)s)")
samplevis.add_argument('-b', '--bar-width', metavar="N", type=pos_int_arg,
default=_DEF_BAR_WIDTH,
help="width of the bars in pixels (default: %(default)s)")
samplevis.add_argument('-p', '--padding', metavar="N", type=pos_int_arg,
default=_DEF_SUBGRAPH_PADDING,
help="amount of padding (in pixels) between graphs of different "
"markers (default: %(default)s)")
#add_arguments
def run(args):
if args.infile == "-" and not sys.stdin.isatty():
# User appears to want to pipe data in.
args.infile = sys.stdin
if (args.infile is not None and args.outfile == sys.stdout
and not os.path.exists(args.infile)):
# One filename given, and it does not exist. Assume outfile.
args.outfile = open(args.infile, 'w')
args.infile = None
if args.infile is not None and args.infile != sys.stdin:
# Open the specified input file.
args.infile = open(args.infile, 'r')
create_visualisation(args.type, args.infile, args.outfile, args.vega,
args.online, args.tidy, args.min_abs, args.min_pct,
args.bar_width, args.padding)
#run
def main():
"""
Main entry point.
"""
parser = argparse.ArgumentParser(
description=__doc__)
try:
add_arguments(parser)
run(parser.parse_args())
except OSError as error:
parser.error(error)
#main
if __name__ == "__main__":
main()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Sample Visualisation</title/>
<!-- BEGIN_EXTERNAL_SCRIPTS -->
<script src="http://vega.github.io/vega-editor/vendor/d3.min.js"></script>
<script src="http://vega.github.io/vega/vega.min.js"></script>
<script type="text/javascript">
var graph_spec = false;
vg.util.load({url: "samplevis.json"}, function(err, result){
graph_spec = JSON.parse(result);
})
</script>
<!-- END_EXTERNAL_SCRIPTS -->
<style>
* {
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
}
body {
margin: 0px
}
div.options {
position: absolute;
margin: 5px;
background-color: rgba(128, 128, 255, 0.5);
z-index: 10;
}
div.view {
position: absolute;
overflow: auto;
bottom: 0px;
top: 0px;
padding-top: 150px;
left: 0px;
right: 0px;
text-align: right;
}
</style>
</head>
<body>
<div class="options">
<strong>Options</strong><br>
Open sample data file: <input id="fileselect" type="file"> (or drag a file onto this page)<br>
<head>
<meta charset="UTF-8">
<title>Sample Visualisation - FDSTools</title/>
<!-- BEGIN_LIBRARIES -->
<script src="http://vega.github.io/vega-editor/vendor/d3.min.js"></script>
<script src="http://vega.github.io/vega/vega.min.js"></script>
<!-- END_LIBRARIES -->
<style>
* {
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
}
body {
margin: 0px
}
div.options {
position: absolute;
margin: 5px;
background-color: rgba(128, 128, 255, 0.5);
z-index: 10;
}
#optionsheader{
cursor: pointer;
}
#optionsheader:hover{
border-bottom: 1px dashed black;
}
div#vis {
position: absolute;
overflow: auto;
bottom: 0px;
top: 0px;
right: 0px;
left: 0px;
text-align: right;
}
</style>
</head>
<body>
<div class="options">
<strong id="optionsheader">Options</strong><br>
<div id="options">
<span id="fileselectspan" style="display: none">
Open sample data file (or drag a file onto this page): <input id="fileselect" type="file"><br>
</span>
Display options: bar width <input type="text" value="15" id="barwidth" size="2">px; marker spacing <input type="text" value="70" id="markeroffset" size="3">px<br>
Filtering: require at least <input type="text" value="15" id="minN" size="3"> reads and at least <input type="text" value="0.5" id="minP" size="3">% of highest allele per marker<br>
Axis scale: <input type="radio" name="scale" value="linear" id="scaleLinear" checked> Linear
<input type="radio" name="scale" value="sqrt" id="scaleLog"> Square root<br>
Render as: <input type="radio" name="renderer" value="canvas" id="renderCanvas"> Canvas
<input type="radio" name="renderer" value="svg" id="renderSVG" checked> SVG<br>
<a id="saveLink" href="javascript:void(saveImage())" style="display: none">Save image</a>
</div>
<div id="vis" class="view"></div>
</body>
</div>
<div id="vis"></div>
<script type="text/javascript">
var graph = false;
function parse(){
vg.parse.spec(graph_spec, function(chart){
var rendererName = "canvas";
if(document.getElementById("renderSVG").checked)
rendererName="svg";
graph = chart({el:"#vis",renderer:rendererName});
graph = chart({el: "#vis", renderer: rendererName});
graph.update();
document.getElementById("saveLink").style.display = "inline";
......@@ -78,7 +83,37 @@
if(graph)
parse();
return;
}
function setDataFormulaTransformValue(dataname, fieldname, value){
if(!graph_spec)
return false;
for(i in graph_spec["data"]){
if(graph_spec["data"][i]["name"] == dataname){
for(j in graph_spec["data"][i]["transform"]){
if(graph_spec["data"][i]["transform"][j]["type"] == "formula" && graph_spec["data"][i]["transform"][j]["field"] == fieldname){
graph_spec["data"][i]["transform"][j]["expr"] = "" + value;
return true;
}
}
}
}
return false;
}
function getDataFormulaTransformValue(dataname, fieldname){
if(!graph_spec)
return false;
for(i in graph_spec["data"]){
if(graph_spec["data"][i]["name"] == dataname){
for(j in graph_spec["data"][i]["transform"]){
if(graph_spec["data"][i]["transform"][j]["type"] == "formula" && graph_spec["data"][i]["transform"][j]["field"] == fieldname){
return graph_spec["data"][i]["transform"][j]["expr"];
}
}
}
}
return false;
}
function setRenderer(value){
......@@ -98,36 +133,6 @@
reader.readAsText(fileList[0]);
}
//Allow files to be dragged onto the page.
document.addEventListener('dragover', function(evt){
evt.stopPropagation();
evt.preventDefault();
}, false);
document.addEventListener('drop', function(evt){
evt.stopPropagation();
evt.preventDefault();
loadDataset(evt.dataTransfer.files);
}, false);
//Handle files from the file input.
document.getElementById("fileselect").addEventListener('change', function(){
loadDataset(document.getElementById("fileselect").files);
}, false);
//Update graph when rendering mode or axis scale is changed.
document.getElementById("renderCanvas").addEventListener('change', function(){
setRenderer(this.value);
}, false);
document.getElementById("renderSVG").addEventListener('change', function(){
setRenderer(this.value);
}, false);
document.getElementById("scaleLinear").addEventListener('change', function(){
setScale(this.value);
}, false);
document.getElementById("scaleLog").addEventListener('change', function(){
setScale(this.value);
}, false);
//Save image function.
function saveImage(){
var link = document.getElementById("saveLink");
......@@ -146,12 +151,100 @@
return false;
}
//Apply current values to graph_spec.
if(graph_spec){
function onLoadSpec(single_sample){
//Allow files to be dragged onto the page.
if(!single_sample){
document.addEventListener('dragover', function(evt){
evt.stopPropagation();
evt.preventDefault();
}, false);
document.addEventListener('drop', function(evt){
evt.stopPropagation();
evt.preventDefault();
loadDataset(evt.dataTransfer.files);
}, false);
//Handle files from the file input.
document.getElementById("fileselect").addEventListener('change', function(){
loadDataset(document.getElementById("fileselect").files);
}, false);
document.getElementById("fileselectspan").style.display = "inline";
}
//Update graph when rendering mode or axis scale is changed.
document.getElementById("renderCanvas").addEventListener('change', function(){
setRenderer(this.value);
}, false);
document.getElementById("renderSVG").addEventListener('change', function(){
setRenderer(this.value);
}, false);
document.getElementById("scaleLinear").addEventListener('change', function(){
setScale(this.value);
}, false);
document.getElementById("scaleLog").addEventListener('change', function(){
setScale(this.value);
}, false);
document.getElementById("barwidth").addEventListener('keyup', function(){
var value = parseFloat(this.value);
if(isNaN(value))
return;
if(setDataFormulaTransformValue("yscale", "barwidth", value) && graph)
parse();
}, false);
document.getElementById("markeroffset").addEventListener('keyup', function(){
var value = parseFloat(this.value);
if(isNaN(value))
return;
if(setDataFormulaTransformValue("yscale", "markeroffset", value) && graph)
parse();
}, false);
document.getElementById("minN").addEventListener('keyup', function(){
var value = parseFloat(this.value);
if(isNaN(value))
return;
if(setDataFormulaTransformValue("table", "amplitude_threshold", value) && graph)
parse();
}, false);
document.getElementById("minP").addEventListener('keyup', function(){
var value = parseFloat(this.value);
if(isNaN(value))
return;
if(setDataFormulaTransformValue("table", "amplitude_pct_threshold", value) && graph)
parse();
}, false);
//Toggle options visibility.
document.getElementById("optionsheader").addEventListener('click', function(){
var opts = document.getElementById("options");
if(opts.style.display == "none")
document.getElementById("options").style.display = "block";
else
document.getElementById("options").style.display = "none";
}, false);
//Sync graph_spec and display.
if(document.getElementById("scaleLinear").checked)
setScale(document.getElementById("scaleLinear").value);
else
setScale(document.getElementById("scaleLog").value);
document.getElementById("barwidth").value = getDataFormulaTransformValue("yscale", "barwidth");
document.getElementById("markeroffset").value = getDataFormulaTransformValue("yscale", "markeroffset");
document.getElementById("minN").value = getDataFormulaTransformValue("table", "amplitude_threshold");
document.getElementById("minP").value = getDataFormulaTransformValue("table", "amplitude_pct_threshold");
if(single_sample){
document.getElementById("options").style.display = "none";
parse();
}
}
</script>
<!-- BEGIN_LOAD_SCRIPT -->
<script type="text/javascript">
var graph_spec = false;
vg.util.load({url: "samplevis.json"}, function(err, result){
graph_spec = JSON.parse(result);
onLoadSpec(false);
});
</script>
<!-- END_LOAD_SCRIPT -->
</body>
</html>
......@@ -3,7 +3,7 @@
"height": 10,
"data": [
{
"name": "table",
"name": "raw",
"values": "sample_data_file_contents_here",
"format": {
"type": "tsv",
......@@ -25,9 +25,54 @@
"field": "total_add",
"expr": "datum.total_add? datum.total_corr+datum.total_add : datum.total_corr"
},
{
"type": "formula",
"field": "amplitude",
"expr": "max(abs(datum.total), abs(datum.total_add))"
}
]
},
{
"name": "maxima",
"source": "raw",
"transform": [
{
"type": "aggregate",
"groupby": ["name"],
"summarize": {"amplitude": "max"}
}
]
},
{
"name": "table",
"source": "raw",
"transform": [
{
"type": "lookup",
"on": "maxima",
"onKey": "name",
"keys": ["name"],
"as": ["aggr"],
"default": {"max_amplitude": 0}
},
{
"type": "formula",
"field": "amplitude_threshold",
"expr": "5"
},
{
"type": "formula",
"field": "amplitude_pct_threshold",
"expr": "0.5"
},
{
"type": "formula",
"field": "amplitude_pct",
"expr": "datum.aggr.max_amplitude? (datum.amplitude/datum.aggr.max_amplitude*100) : 100"
},
{
"type": "filter",
"test": "max(datum.total, datum.total_add) > 15"
"test": "datum.amplitude > datum.amplitude_threshold && datum.amplitude_pct > datum.amplitude_pct_threshold"
},
{
"type": "formula",
......@@ -124,24 +169,24 @@
"source": "markercounts",
"transform": [
{
"type": "zip",
"with": "markerpadding",
"as": "paddingobj",
"key": "name",
"withKey": "name",
"type": "lookup",
"on": "markerpadding",