vis.py 16.1 KB
Newer Older
jhoogenboom's avatar
jhoogenboom committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/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.

16 17 18 19 20
Vega supports generating visualisations on the command line.  By
default, FDSTools produces a full-featured HTML file.  Specify the
-V/--vega option if you wish to obtain a bare Vega graph specification
(a JSON file) instead.  You can pass this file through Vega to generate
a PNG or SVG image file.
jhoogenboom's avatar
jhoogenboom committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48

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.
49 50 51 52 53 54
_DEF_THRESHOLD_PCT_OF_MAX = 0.5

# Default minimum amount of reads to require, as a percentage of the
# total number of reads each marker.
# This value can be overridden by the -S command line option.
_DEF_THRESHOLD_PCT_OF_SUM = 0.0
jhoogenboom's avatar
jhoogenboom committed
55

56 57 58 59
# Default minimum number of reads per orientation to require.
# This value can be overridden by the -s command line option.
_DEF_THRESHOLD_ORIENTATION = 0

60 61 62
# Default percentage of reads on one strand to mark as bias.
# This value can be overridden by the -B command line option.
_DEF_THRESHOLD_BIAS = 25.0
63

jhoogenboom's avatar
jhoogenboom committed
64 65 66 67 68 69 70 71
# 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

72 73 74 75
# Default maximum length of sequences to display.
# This value can be overridden by the -x command line option.
_DEF_MAX_SEQ_LEN = 70

76 77 78 79
# Default graph width in pixels.
# This value can be overridden by the -w command line option.
_DEF_WIDTH = 600

jhoogenboom's avatar
jhoogenboom committed
80 81 82 83
# Default graph height in pixels.
# This value can be overridden by the -H command line option.
_DEF_HEIGHT = 400

84 85
# Default marker name matching regular expression.
# This value can be overridden by the -M command line option.
86
_DEF_MARKER_NAME = ""
87

jhoogenboom's avatar
jhoogenboom committed
88 89
# Default repeat unit matching regular expression.
# This value can be overridden by the -U command line option.
90
_DEF_UNIT = ""
jhoogenboom's avatar
jhoogenboom committed
91

jhoogenboom's avatar
jhoogenboom committed
92 93 94 95 96 97 98 99 100
# 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_LIBRARIES = re.compile("<!--\s*BEGIN_LIBRARIES\s*-->\s*(.*?)\s*"
                            "<!--\s*END_LIBRARIES\s*-->", flags=re.DOTALL)
101 102
_PAT_LOAD_SCRIPT = re.compile("<!--\s*BEGIN_LOAD_SCRIPT\s*-->\s*(.*?)\s*"
                              "<!--\s*END_LOAD_SCRIPT\s*-->", flags=re.DOTALL)
jhoogenboom's avatar
jhoogenboom committed
103 104 105 106 107 108 109 110

_SCRIPT_BEGIN = '<script type="text/javascript">'
_SCRIPT_END = '</script>'

_EXTERNAL_LIBRARIES = ("vis/d3.min.js", "vis/vega.min.js")



111 112 113 114 115 116 117
def set_signal_value(spec, signalname, value):
    if "signals" not in spec:
        return False
    for signal in spec["signals"]:
        if signal["name"] == signalname:
            signal["init"] = value
            return True
jhoogenboom's avatar
jhoogenboom committed
118
    return False
119
#set_signal_value
jhoogenboom's avatar
jhoogenboom committed
120 121


jhoogenboom's avatar
jhoogenboom committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
def set_axis_scale(spec, scalename, value):
    success = False
    for marks in spec["marks"]:
        if "scales" not in marks:
            continue
        for scale in marks["scales"]:
            if scale["name"] != scalename:
                continue
            scale["type"] = value;
            success = True
    return success
#set_axis_scale


def create_visualisation(vistype, infile, outfile, vega, online, tidy, min_abs,
137 138
                         min_pct_of_max, min_pct_of_sum, min_per_strand,
                         bias_threshold, bar_width, padding, marker, width,
139
                         height, log_scale, repeat_unit, no_alldata,
140
                         no_aggregate, no_ce_length_sort, max_seq_len, title):
jhoogenboom's avatar
jhoogenboom committed
141 142 143 144 145 146 147 148 149 150 151
    # 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

jhoogenboom's avatar
jhoogenboom committed
152
    # Apply width, height, and padding settings.
153
    spec["width"] = width
jhoogenboom's avatar
jhoogenboom committed
154
    if vistype == "stuttermodel":
155
        set_signal_value(spec, "graphheight", height)
156 157
    elif vistype == "allele":
        spec["height"] = height
jhoogenboom's avatar
jhoogenboom committed
158
    else:
159
        set_signal_value(spec, "barwidth", bar_width)
160 161 162
    if vistype != "allele":
        set_signal_value(spec, "subgraphoffset", padding)
        set_signal_value(spec, "filter_marker", marker)
jhoogenboom's avatar
jhoogenboom committed
163 164 165

    # Apply type-specific settings.
    if vistype == "stuttermodel":
166 167
        set_signal_value(spec, "filter_unit", repeat_unit)
        set_signal_value(spec, "show_all_data", False if no_alldata else True)
jhoogenboom's avatar
jhoogenboom committed
168
    elif vistype == "sample" or vistype == "bgraw":
169
        set_signal_value(spec, "amplitude_threshold", min_abs)
170
        set_signal_value(spec, "amplitude_pct_threshold", min_pct_of_max)
171
    elif vistype == "profile":
172
        set_signal_value(spec, "filter_threshold", min_pct_of_max)
173
        set_signal_value(spec, "low", 0.001 if log_scale else 0)
174
    if vistype == "sample":
175 176
        set_signal_value(spec, "orientation_threshold", min_per_strand)
        set_signal_value(spec, "bias_threshold", bias_threshold)
177
        set_signal_value(spec, "amplitude_markerpct_threshold", min_pct_of_sum)
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
178 179
        set_signal_value(spec, "show_other", not no_aggregate)
        set_signal_value(spec, "sort_str_by_length", not no_ce_length_sort)
180
        set_signal_value(spec, "max_seq_len", max_seq_len)
jhoogenboom's avatar
jhoogenboom committed
181 182

    # Apply axis scale settings.
183
    if vistype != "stuttermodel" and vistype != "allele":
jhoogenboom's avatar
jhoogenboom committed
184 185 186 187 188 189
        if not log_scale:
            set_axis_scale(spec, "x", "linear")
        elif vistype == "sample":
            set_axis_scale(spec, "x", "sqrt")
        else:
            set_axis_scale(spec, "x", "log")
jhoogenboom's avatar
jhoogenboom committed
190

191 192 193 194 195 196 197 198 199
    # Add title if available.
    if title is None and infile is not None and infile != sys.stdin:
        try:
            title = os.path.splitext(os.path.basename(infile.name))[0]
        except AttributeError:
            pass
    if title:
        spec["data"][0]["fdstools_filename"] = title;

jhoogenboom's avatar
jhoogenboom committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
    # 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)

237
    outfile.write(html)
jhoogenboom's avatar
jhoogenboom committed
238 239 240 241
#create_visualisation


def add_arguments(parser):
jhoogenboom's avatar
jhoogenboom committed
242
    parser.add_argument('type', metavar="TYPE",
243
        choices=("sample", "profile", "bgraw", "stuttermodel", "allele"),
244
        help="the type of data to visualise; use 'sample' to visualise "
jhoogenboom's avatar
jhoogenboom committed
245 246 247 248 249
             "sample data files and bgcorrect output; use 'profile' to "
             "visualise background noise profiles obtained with bgestimate, "
             "bghomstats, and bgpredict; use 'bgraw' to visualise raw "
             "background noise data obtained with bghomraw; use "
             "'stuttermodel' to visualise models of stutter obtained from "
250 251
             "stuttermodel; use 'allele' to visualise the allele list "
             "obtained from allelefinder")
jhoogenboom's avatar
jhoogenboom committed
252 253 254 255 256 257 258 259 260 261
    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",
262 263 264
        help="by default, a full-featured HTML file offering an interactive "
             "visualisation is created; if this option is specified, only a "
             "bare Vega graph specification (JSON file) is produced instead")
jhoogenboom's avatar
jhoogenboom committed
265 266 267 268 269 270 271 272
    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")
273 274 275
    parser.add_argument('-T', '--title',
        help="prepend the given value to the title of HTML visualisations "
             "(default: prepend name of data file if given)")
jhoogenboom's avatar
jhoogenboom committed
276

277 278 279 280
    visgroup = parser.add_argument_group("visualisation options",
        description="words in [brackets] indicate applicable visualisation "
                    "types")
    visgroup.add_argument('-n', '--min-abs', metavar="N", type=pos_int_arg,
jhoogenboom's avatar
jhoogenboom committed
281
        default=_DEF_THRESHOLD_ABS,
jhoogenboom's avatar
jhoogenboom committed
282 283
        help="[sample, bgraw] only show sequences with this minimum number of "
             "reads (default: %(default)s)")
284 285
    visgroup.add_argument('-m', '--min-pct-of-max', metavar="PCT", type=float,
        default=_DEF_THRESHOLD_PCT_OF_MAX,
jhoogenboom's avatar
jhoogenboom committed
286 287 288 289
        help="[sample, profile, bgraw] for sample: only show sequences with "
             "at least this percentage of the number of reads of the highest "
             "allele of a marker; for profile and bgraw: at least this "
             "percentage of the true allele (default: %(default)s)")
290 291 292 293
    visgroup.add_argument('-S', '--min-pct-of-sum', metavar="PCT", type=float,
        default=_DEF_THRESHOLD_PCT_OF_SUM,
        help="[sample] only show sequences with at least this percentage of "
             "the total number of reads of a marker (default: %(default)s)")
294 295 296 297
    visgroup.add_argument('-s', '--min-per-strand', metavar="N",
        type=pos_int_arg, default=_DEF_THRESHOLD_ORIENTATION,
        help="[sample] only show sequences with this minimum number of reads "
             "for both orientations (forward/reverse) (default: %(default)s)")
298 299 300 301
    visgroup.add_argument('-B', '--bias-threshold', metavar="N", type=float,
        default=_DEF_THRESHOLD_BIAS,
        help="[sample] mark sequences that have less than this percentage of "
             "reads on one strand (default: %(default)s)")
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
302 303
    visgroup.add_argument('-c', '--no-ce-length-sort', action="store_true",
        help="[sample] if specified, do not sort STR alleles by length")
304 305
    visgroup.add_argument('-M', '--marker', metavar="MARKER",
        default=_DEF_MARKER_NAME,
jhoogenboom's avatar
jhoogenboom committed
306
        help="[sample, profile, bgraw, stuttermodel] only show graphs for the "
307 308 309 310 311 312 313 314 315
             "markers that contain the given value in their name; separate "
             "multiple values with spaces; prepend any value with '=' for an "
             "exact match (default: show all markers)")
    visgroup.add_argument('-U', '--repeat-unit', metavar="UNIT",
        default=_DEF_UNIT,
        help="[stuttermodel] only show graphs for the repeat units that "
             "contain the given value; separate multiple values with spaces; "
             "prepend any value with '=' for an exact match (default: show "
             "all repeat units)")
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
316 317 318 319 320
    visgroup.add_argument('-A', '--no-alldata', action="store_true",
        help="[stuttermodel] if specified, show only marker-specific fits")
    visgroup.add_argument('-a', '--no-aggregate', action="store_true",
        help="[sample] if specified, do not replace filtered sequences with a"
             "per-marker aggregate 'Other sequences' entry")
jhoogenboom's avatar
jhoogenboom committed
321 322 323
    visgroup.add_argument('-L', '--log-scale', action="store_true",
        help="[sample, profile, bgraw] use logarithmic scale (for sample: "
             "square root scale) instead of linear scale")
324
    visgroup.add_argument('-b', '--bar-width', metavar="N", type=pos_int_arg,
jhoogenboom's avatar
jhoogenboom committed
325
        default=_DEF_BAR_WIDTH,
jhoogenboom's avatar
jhoogenboom committed
326
        help="[sample, profile, bgraw] width of the bars in pixels (default: "
327 328
             "%(default)s)")
    visgroup.add_argument('-p', '--padding', metavar="N", type=pos_int_arg,
jhoogenboom's avatar
jhoogenboom committed
329
        default=_DEF_SUBGRAPH_PADDING,
jhoogenboom's avatar
jhoogenboom committed
330 331 332
        help="[sample, profile, bgraw, stuttermodel] amount of padding (in "
             "pixels) between graphs of different markers/alleles (default: "
             "%(default)s)")
333 334
    visgroup.add_argument('-w', '--width', metavar="N", type=pos_int_arg,
        default=_DEF_WIDTH,
335 336
        help="[sample, profile, bgraw, stuttermodel, allele] width of the "
             "graph area in pixels (default: %(default)s)")
jhoogenboom's avatar
jhoogenboom committed
337 338
    visgroup.add_argument('-H', '--height', metavar="N", type=pos_int_arg,
        default=_DEF_HEIGHT,
339 340
        help="[stuttermodel, allele] height of the graph area in pixels "
             "(default: %(default)s)")
341 342 343 344
    visgroup.add_argument('-x', '--max-seq-len', type=pos_int_arg,
        default=_DEF_MAX_SEQ_LEN,
        help="[sample] truncate long sequences to this number of characters "
             "(default: %(default)s)")
jhoogenboom's avatar
jhoogenboom committed
345 346 347 348
#add_arguments


def run(args):
349 350
    if args.infile == "-":
        args.infile = None if sys.stdin.isatty() else sys.stdin
jhoogenboom's avatar
jhoogenboom committed
351 352 353 354 355 356
    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

357 358 359 360 361
    if args.outfile.isatty():
        raise ValueError("Please specify a file name to write the %s to." %
                         ("Vega graph specification (JSON format)" if args.vega
                          else "HTML document"))

jhoogenboom's avatar
jhoogenboom committed
362 363 364 365 366
    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,
367 368
                         args.online, args.tidy, args.min_abs,
                         args.min_pct_of_max, args.min_pct_of_sum,
369 370 371
                         args.min_per_strand, args.bias_threshold,
                         args.bar_width, args.padding, args.marker, args.width,
                         args.height, args.log_scale, args.repeat_unit,
Hoogenboom, Jerry's avatar
Hoogenboom, Jerry committed
372
                         args.no_alldata, args.no_aggregate,
373
                         args.no_ce_length_sort, args.max_seq_len, args.title)
jhoogenboom's avatar
jhoogenboom committed
374
#run