view numerics/bar.py @ 148:279f5ae33564

this now generates something
author Jeff Hammel <k0scist@gmail.com>
date Sun, 12 Apr 2015 19:22:33 -0700
parents b8a7604adf6f
children dcedbe63d2c6
line wrap: on
line source

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
bar charts using bokeh

See:
- http://bokeh.pydata.org/tutorial/solutions/gallery/olympics.html
- http://bokeh.pydata.org/en/latest/tutorial/topical.html
- https://gist.github.com/mbostock/7322386
"""

# imports
import argparse
import json
import os
import sys
import tempita
from .manipulate import ManipulationParser
from collections import OrderedDict

__all__ = ['bar_chart', 'BarChartParser', 'main']

# template info
# TODO: own module
here = os.path.dirname(os.path.abspath(__file__))
templates = os.path.join(here, 'templates')
bar_template = os.path.join(templates, 'bar.d3.html')
with open(os.path.join(here, 'js', 'd3.v3.min.js')) as f:
    d3 = f.read()


def bar_chart(data, output, title=None):
    """
    create a bar chart

    See:
    - http://bokeh.pydata.org/en/latest/tutorial/solutions/gallery/olympics.html
    """
    # TODO:  abstract this to a plot class

    template = tempita.Template.from_filename(bar_template)
    bar_chart = template.substitute(title=title or '',
                                    d3=d3,
                                    data=json.dumps(data))
    return bar_chart

class BarChartParser(ManipulationParser):
    """command line options parser for bar charts"""
    # TODO: upstream to PlotParser

    def __init__(self, **kwargs):
        kwargs.setdefault('description', __doc__)
        ManipulationParser.__init__(self, **kwargs)
        self.add_argument('-t', '--title', dest='title',
                          help="plot title")

    def plot_filename(self):
        """determine the plot filename"""
        # this is a STUB
        # in reality, this should come from -o, --output
        # if applicable, or, should be determined from
        # the plot --title, or should be eg
        # '20150315203424.html'
        # we are doing this right nowe to work around the fact
        # that bokeh, in particular, will just cry if you
        # don't set this
        return 'foo.html'


def main(args=sys.argv[1:]):
    """CLI"""

    # parse command line
    parser = BarChartParser()
    options = parser.parse_args(args)

    # process data
    data = parser.typed_data()

    # ensure a mapping is given
    if len(data) != 1:
        raise NotImplementedError("TODO")
    else:
        data = data[0]

    # generate bar chart
    options.output.write(bar_chart(data, parser.plot_filename(), title=options.title))


if __name__ == '__main__':
    main()