Example #1
0
def mpld3_enable_notebook():
    """Change the default plugins, enable ipython notebook mode and return mpld3 module."""
    import mpld3
    from mpld3 import plugins as plugs
    plugs.DEFAULT_PLUGINS = [plugs.Reset(), plugs.Zoom(), plugs.BoxZoom(), plugs.MousePosition()]
    mpld3.enable_notebook()
    return mpld3
Example #2
0
def plot_vdot_race(data):
    #CSS element for the tooltip label
    css = """
div
{
  font-family: Avenir, Helvetica, sans-serif;
  border: 1px solid black;
  padding-left: 5px;
  padding-right: 5px;
  text-align: center;
  color: #000000;
  background-color: #ffffff;
}
"""
    #plt.style.use('seaborn-poster') #sets the size of the charts
    plt.style.use('ggplot')
    x_axis = []
    y_axis = []

    label = []
    #print (data)
    for key in data:
        label.append("Race: " + str(data[key][1]) + "<br/>" + "VDOT: " +
                     str(data[key][3]))

        y_axis.append(data[key][3])
        datetime_obj = datetime.strptime(data[key][4],
                                         '%Y-%m-%d %H:%M:%S+00:00')
        x_axis.append(datetime_obj)

    dates = matplotlib.dates.date2num(x_axis)

    fig, ax = plt.subplots()

    plt.xlabel("Race dates", fontsize=20)
    plt.ylabel("VDOT Scores", fontsize=20)
    plt.title("VDOT Score Over Time", fontsize=25)

    line = plt.plot_date(dates,
                         y_axis,
                         linestyle='solid',
                         marker='.',
                         markersize=14)

    plugins.clear(fig)  # clear all plugins from the figure

    tooltip = plugins.PointHTMLTooltip(line[0],
                                       label,
                                       hoffset=-60,
                                       voffset=-70,
                                       css=css)

    plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom(),
                    tooltip)

    return mpld3.fig_to_html(fig)
Example #3
0
def plotConPlugins(fig):#, plot=None):
    #debugPrint("El parametro plot contiene " + str(plot[0]))
    plugins.connect(fig, plugins.BoxZoom(button = False))#, plugins.PointLabelTooltip(plot[0]))
    debugPrint("Se logro conectar el plugin BoxZoom")
    plot_url = fig_to_html(fig)

    debugPrint("A punto de cerrar la figura")
    pyplt.close(fig)

    return plot_url
Example #4
0
def make_html_plot_for_file(filename, my_title):
    my_fontsize = 20

    # read in csv file
    if os.stat(filename).st_size:
        data = np.genfromtxt(filename, delimiter=',')
    else:
        # empty data file
        data = np.zeros([2, 2])

    if len(data.shape) == 1:
        return "<h2> " + my_title + " has no data </h2>"

    x = data[:, 0]
    fig, ax = plt.subplots(figsize=(10, 5))

    for k in range(1, data.shape[1]):
        y = data[:, k]

        # sort data
        x_sorted = [x1 for (x1, y1) in sorted(zip(x, y))]
        y_sorted = [y1 for (x1, y1) in sorted(zip(x, y))]

        lines = ax.plot(x_sorted,
                        y_sorted,
                        '.-',
                        markersize=15,
                        label='ion ' + str(k - 1))

    plt.legend(fontsize=my_fontsize, loc='best')
    plt.title(my_title, fontsize=my_fontsize)
    ax.grid()
    plt.xticks(fontsize=my_fontsize)
    plt.yticks(fontsize=my_fontsize)
    plt.xlim([np.min(x), np.max(x)])

    #90% of the time that this function takes is taken up after this line
    plugins.clear(fig)
    plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(),
                    plugins.Zoom(enabled=True),
                    plugins.MousePosition(fontsize=my_fontsize))
    java_txt = mpld3.fig_to_html(fig)
    plt.close()

    return java_txt
Example #5
0
def plot_beats_per_mile(data):
    #divide meters by this factor to get in terms of miles
    convert_meters_to_miles = 1609.344

    #plt.style.use('seaborn-poster') #sets the size of the charts
    plt.style.use('ggplot')

    #Data is dictionary mapping id to (activity_name, start_date_local, average_hr, distance, total_elevation_gain)

    data_by_week = {}

    for key in data:
        datetime_obj = datetime.strptime(data[key][1], '%Y-%m-%d %H:%M:%S')
        year_week_val = datetime_obj.isocalendar()[:-1]

        if year_week_val not in data_by_week:
            #Storing average_hr, distance, total_elevation_gain
            data_by_week[year_week_val] = [(data[key][2], data[key][3],
                                            data[key][4])]
        else:
            data_by_week[year_week_val].append(
                (data[key][2], data[key][3], data[key][4]))

    x_axis = []
    x_label = []
    y_axis = []
    for key in data_by_week:
        print(key)
        total_hr_each_week = 0
        distance_week = 0
        for activity in data_by_week[key]:
            total_hr_each_week += activity[0] * (activity[1] /
                                                 convert_meters_to_miles)
            distance_week += activity[1] / convert_meters_to_miles
        avg_hr_per_mile = total_hr_each_week / distance_week

        x_label.append(str(key[0]) + "-" + str(key[1]))
        x_axis.append(key[0] * 52 + key[1])
        y_axis.append(avg_hr_per_mile)
        total_hr_each_week = 0
        distance_week = 0

    fig, ax = plt.subplots()

    plt.xlabel("Weeks", fontsize=20)
    plt.ylabel("Average Heartrate Per Mile", fontsize=20)
    plt.title("Average Heartrate Per Mile Sorted by Week", fontsize=25)

    line = plt.plot(x_axis,
                    y_axis,
                    linestyle='solid',
                    marker='.',
                    markersize=14)

    x = np.asarray(x_axis)
    y = np.asarray(y_axis)

    b, m = polyfit(x, y, 1)
    #Plots regression line
    plt.plot(x, b + m * x, linestyle='solid')

    plugins.clear(fig)  # clear all plugins from the figure

    #tooltip = plugins.PointHTMLTooltip(line[0], label,
    #hoffset = -60, voffset = -70, css = css)

    plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(), plugins.Zoom())

    return mpld3.fig_to_html(fig)
Example #6
0
plot_rest = jitter(
    reduced[rest["Membership"]]["PC1"],
    reduced[rest["Membership"]]["PC2"],
    c="b",
    alpha=0.4,
    label="Non-WMC"
)

plot_wmc = jitter(
    reduced[wmc["Membership"]]["PC1"],
    reduced[wmc["Membership"]]["PC2"],
    c="g",
    alpha=0.4,
    label="WMC"
)

plt.xlabel("PC1")
plt.ylabel("PC2")

tooltip_rest = plugins.PointHTMLTooltip(plot_rest, reduced[rest["Membership"]].index.tolist())
tooltip_wmc = plugins.PointHTMLTooltip(plot_wmc, reduced[wmc["Membership"]].index.tolist())

zoom = plugins.Zoom(button=False, enabled=True)
box_zoom = plugins.BoxZoom(button=False, enabled=True)


plugins.connect(plt.gcf(), tooltip_rest)
plugins.connect(plt.gcf(), tooltip_wmc)

mpld3.save_html(plt.gcf(), "pca-2017.html")
Example #7
0
def result():
    try:
        g.conn = sqlite3.connect('case_data.db')
        g.curr = g.conn.cursor()
        g.curr.execute("SELECT country_name FROM interval_tb")
        country = g.curr.fetchone()[0]
        g.curr.execute("SELECT duration FROM interval_tb")
        period = g.curr.fetchall()
        g.curr.execute("SELECT restriction FROM interval_tb")
        restrictions = g.curr.fetchall()
        g.curr.execute("SELECT * FROM cases_tb WHERE country_name=?",
                       (country, ))
        country_statistics = g.curr.fetchone()
        g.conn.commit()
        g.conn.close()

        plt.rcParams.update({'font.size': 12})

        def differential(initial, time, *args):

            # Holds initial conditions for the population
            susceptible, exposed, infected, recovered = initial

            # System of differential equations
            # Represents changes in the susceptible, exposed, infected, and recovered population
            dSdt = -(beta * susceptible * infected) / POPULATION_SIZE
            dEdt = beta * susceptible * infected / POPULATION_SIZE - SIGMA * exposed
            dIdt = SIGMA * exposed - GAMMA * infected
            dRdt = GAMMA * infected

            return dSdt, dEdt, dIdt, dRdt

        POPULATION_SIZE = country_statistics[3]
        BETA = 0.956
        SIGMA = 1 / 5.2
        GAMMA = 1 / 2.3
        REPRODUCTION_NUMBER = BETA / GAMMA

        period = list(period)
        time = [0]
        restrictions = list(restrictions)
        contact_state = []

        for i in range(len(period)):
            period[i] = period[i][0]

        for i in range(len(restrictions)):
            restrictions[i] = restrictions[i][0]

        time += list(accumulate(period))

        for j in range(len(period)):
            if restrictions[j] == "Lockdown":
                contact_state.append(0.26)
            elif restrictions[j] == "Vacation":
                contact_state.append(0.46)
            elif restrictions[j] == "School closure":
                contact_state.append(0.8)
            else:
                contact_state.append(1)

        susceptible_initial = POPULATION_SIZE - \
            country_statistics[2] - country_statistics[1]
        exposed_initial = 0
        infected_initial = country_statistics[2]
        recovered_initial = country_statistics[1]

        infected_population = 0
        current_maximum = 0

        fig, ax = plt.subplots()

        for graph in range(len(period)):

            beta = BETA * contact_state[graph]

            duration = np.linspace(time[graph], time[graph + 1],
                                   period[graph] * 2 + 1)

            solution = odeint(differential,
                              (susceptible_initial, exposed_initial,
                               infected_initial, recovered_initial),
                              duration,
                              args=(beta, SIGMA, GAMMA, POPULATION_SIZE))

            susceptible_initial = solution[period[graph] * 2, 0]
            exposed_initial = solution[period[graph] * 2, 1]
            infected_initial = solution[period[graph] * 2, 2]
            recovered_initial = solution[period[graph] * 2, 3]

            current_maximum = max(solution[:, 2])
            if current_maximum > infected_population:
                infected_population = current_maximum

            if graph == 0:
                ax.plot(duration, solution[:, 0], 'r', label='Susceptible')
                ax.plot(duration, solution[:, 1], 'g', label='Exposed')
                ax.plot(duration, solution[:, 2], 'b', label='Infectious')
                ax.plot(duration, solution[:, 3], 'y', label='Recovered')

            else:
                ax.plot(duration, solution[:, 0], 'r')
                ax.plot(duration, solution[:, 1], 'g')
                ax.plot(duration, solution[:, 2], 'b')
                ax.plot(duration, solution[:, 3], 'y')

        ax.set_xlim(0, time[-1])
        ax.set_ylim(0, POPULATION_SIZE + POPULATION_SIZE * 0.01)

        ax.legend(loc='best')

        ax.set_xlabel('Time (days)')
        ax.set_ylabel('Population', rotation='horizontal')

        fig.set_size_inches(8, 6)
        ax.yaxis.set_label_coords(-0.1, 1.02)

        plugins.clear(fig)
        plugins.connect(fig, plugins.Reset())
        plugins.connect(fig, plugins.BoxZoom(enabled=True))
        plugins.connect(fig, plugins.Zoom())

        seir_graph = mpld3.fig_to_html(fig)
        plt.close()

        effective_reproduction_number = REPRODUCTION_NUMBER * \
            susceptible_initial/POPULATION_SIZE
        effective_reproduction_number = float(
            "{:0.3f}".format(effective_reproduction_number))

        return {
            'graph': seir_graph,
            'r0': REPRODUCTION_NUMBER,
            'rt': effective_reproduction_number,
            'susceptible_state': int(susceptible_initial),
            'exposed_state': int(exposed_initial),
            'infected_state': int(infected_initial),
            'recovered_state': int(recovered_initial),
            'max_active_cases': int(infected_population)
        }
    except:
        return jsonify(0)
Example #8
0
def problem_view(request, problem_id):
    user = request.user
    problem = get_object_or_404(Problem, id=problem_id)
    if problem.user_id != user and not user.is_superuser:
        raise PermissionDenied

    parse_error = False
    a = None
    b = None
    c = None
    a_copy = None
    b_copy = None
    result = None
    figure = None
    parse_result = parse_problem(problem.problem_text)
    print parse_result
    if parse_result is not None:
        a, b, c, x = parse_result
        if a and b and c and x:
            result = simple_simplex(copy.deepcopy(a), copy.deepcopy(b),
                                    copy.deepcopy(c))
            b.pop(0)
            a_copy = copy.deepcopy(a)
            b_copy = copy.deepcopy(b)

            if len(x) is 2:
                tmp = [0, 0]
                tmp[1] = 1
                a.insert(0, copy.deepcopy(tmp))
                tmp[0] = 1
                tmp[1] = 0
                a.insert(0, copy.deepcopy(tmp))
                b.insert(0, 0)
                b.insert(0, 0)
                dots = []
                for i in range(len(b)):
                    dots.append([])
                shape_x = []
                for i in xrange(0, len(b)):
                    for j in xrange(i + 1, len(b)):
                        if a[i][0] == a[j][0] and a[i][1] == a[j][1]:
                            continue
                        shape_a = np.array([[a[i][0], a[i][1]],
                                            [a[j][0], a[j][1]]])
                        shape_b = np.array([b[i], b[j]])
                        res = np.linalg.solve(shape_a, shape_b)
                        dots[i].append(res)
                        dots[j].append(res)
                # fig, ax = plt.subplots()
                fig = plt.figure()
                ax = fig.add_subplot(111)
                for dot in dots:
                    ax.plot(
                        [float(dot[0][0]), float(dot[1][0])],
                        [float(dot[0][1]), float(dot[1][1])],
                        ls='-',
                        color='green',
                        marker='o',
                        lw=2)
                    # print([dot[0], dot[1]])
                ax.set_xlabel('X axis')
                ax.set_ylabel('Y axis')
                ax.set_title('Plot of 2D Problem!', size=14)
                plugins.clear(fig)
                plugins.connect(fig, plugins.Reset(),
                                plugins.Zoom(enabled=True), plugins.BoxZoom())
                figure = fig_to_html(fig,
                                     d3_url=STATIC_URL + 'js/d3.min.js',
                                     mpld3_url=STATIC_URL + 'js/mpld3.v0.2.js',
                                     use_http=True)
            else:
                figure = 'Larger than 2D!'
    else:
        parse_error = True

    return render_to_response(
        'problems/view.html', {
            'user': user,
            'problem': problem,
            'parse_error': parse_error,
            'figure': figure,
            'a': a_copy,
            'b': b_copy,
            'c': c,
            'result': result,
            'view_name': 'Problem - %s' % problem.id,
        })
Example #9
0
    def render(self, idf, filename='output.html'):
        progress_inst = helpers.Progress(idf.opt)
        self.progress = progress_inst.progress

        if idf.opt['outputFilename']:
            filename = idf.opt['outputFilename']

        if idf.opt['outputAs'] == 'html':
            # write matplotlib/d3 plots to html file
            import matplotlib
            import matplotlib.pyplot as plt, mpld3
            import matplotlib.axes

            from mpld3 import plugins
            from jinja2 import Environment, FileSystemLoader
        elif idf.opt['outputAs'] in ['pdf', 'interactive', 'tikz']:
            # show plots in separate matplotlib windows
            import matplotlib
            if idf.opt['outputAs'] == 'pdf':
                from matplotlib.backends.backend_pdf import PdfPages
                pp = PdfPages(filename)
            import matplotlib.pyplot as plt
            import matplotlib.axes
        else:
            print("No proper output method given. Not plotting.")
            return

        font_size = 10
        if idf.opt['outputAs'] in ['pdf', 'tikz']:
            if idf.opt['plotPerJoint']:
                font_size = 30
            else:
                font_size = 12
            matplotlib.rcParams.update({'font.size': font_size})
            matplotlib.rcParams.update({'axes.labelsize': font_size - 5})
            matplotlib.rcParams.update({'axes.linewidth': font_size / 15.})
            matplotlib.rcParams.update({'axes.titlesize': font_size - 2})
            matplotlib.rcParams.update({'legend.fontsize': font_size - 2})
            matplotlib.rcParams.update({'xtick.labelsize': font_size - 5})
            matplotlib.rcParams.update({'ytick.labelsize': font_size - 5})
            matplotlib.rcParams.update({'lines.linewidth': font_size / 15.})
            matplotlib.rcParams.update({'patch.linewidth': font_size / 15.})
            matplotlib.rcParams.update({'grid.linewidth': font_size / 20.})

        # skip some samples so graphs don't get too large/detailed TODO: change skip so that some
        # maximum number of points is plotted (determined by screen etc.)
        skip = 5

        #create figures and plots
        figures = list()
        for ds in self.progress(range(len(self.datasets))):
            group = self.datasets[ds]
            fig, axes = plt.subplots(len(group['dataset']),
                                     sharex=True,
                                     sharey=True)
            # scale unified scaling figures to same ranges and add some margin
            if group['unified_scaling']:
                ymin = 0
                ymax = 0
                for i in range(len(group['dataset'])):
                    ymin = np.min(
                        (np.min(group['dataset'][i]['data']), ymin)) * 1.05
                    ymax = np.max(
                        (np.max(group['dataset'][i]['data']), ymax)) * 1.05

            #plot each group of data
            for d_i in range(len(group['dataset'])):
                d = group['dataset'][d_i]
                if not issubclass(type(axes), matplotlib.axes.SubplotBase):
                    ax = axes[d_i]
                else:
                    ax = axes
                    axes = [axes]
                if idf.opt['outputAs'] != 'tikz':
                    ax.set_title(d['title'])
                if group['unified_scaling']:
                    ax.set_ylim([ymin, ymax])
                for data_i in range(0, len(d['data'])):
                    if len(d['data'][data_i].shape) > 1:
                        #data matrices
                        for i in range(0, d['data'][data_i].shape[1]):
                            l = group['labels'][i] if data_i == 0 else ''
                            if i < 6 and 'contains_base' in group and group[
                                    'contains_base']:
                                ls = 'dashed'
                            else:
                                ls = '-'
                            dashes = ()  # type: Tuple
                            if idf.opt['plotErrors']:
                                if idf.opt['plotPrioriTorques']:
                                    n = 3
                                else:
                                    n = 2
                                if i == n:
                                    ls = 'dashed'
                                    dashes = (3, 0.5)
                            ax.plot(d['time'][::skip],
                                    d['data'][data_i][::skip, i],
                                    label=l,
                                    color=colors[i],
                                    alpha=1 - (data_i / 2.0),
                                    linestyle=ls,
                                    dashes=dashes)
                    else:
                        #data vector
                        ax.plot(d['time'][::skip],
                                d['data'][data_i][::skip],
                                label=group['labels'][d_i],
                                color=colors[0],
                                alpha=1 - (data_i / 2.0))

                ax.grid(which='both', linestyle="dotted", alpha=0.8)
                if 'y_label' in group:
                    ax.set_ylabel(group['y_label'])

            if idf.opt['outputAs'] != 'tikz':
                ax.set_xlabel("Time (s)")

            plt.setp([a.get_xticklabels() for a in axes[:-1]], visible=False)
            #plt.setp([a.get_yticklabels() for a in axes], fontsize=8)

            if idf.opt['plotLegend']:
                handles, labels = ax.get_legend_handles_labels()
                if idf.opt['outputAs'] == 'html':
                    #TODO: show legend properly (see mpld3 bug #274)
                    #leg = fig.legend(handles, labels, loc='upper right', fancybox=True, fontsize=10, title='')
                    leg = axes[0].legend(handles,
                                         labels,
                                         loc='upper right',
                                         fancybox=True,
                                         fontsize=10,
                                         title='',
                                         prop={'size': 8})
                else:
                    leg = plt.figlegend(handles,
                                        labels,
                                        loc='upper right',
                                        fancybox=True,
                                        fontsize=font_size,
                                        title='',
                                        prop={'size': font_size - 3})
                    leg.draggable()

            fig.subplots_adjust(hspace=2)
            fig.set_tight_layout(True)

            if idf.opt['outputAs'] == 'html':
                plugins.clear(fig)
                plugins.connect(fig, plugins.Reset(), plugins.BoxZoom(),
                                plugins.Zoom(enabled=False),
                                plugins.MousePosition(fontsize=14, fmt=".5g"))
                figures.append(mpld3.fig_to_html(fig))
            elif idf.opt['outputAs'] == 'interactive':
                plt.show(block=False)
            elif idf.opt['outputAs'] == 'pdf':
                pp.savefig(plt.gcf())
            elif idf.opt['outputAs'] == 'tikz':
                from matplotlib2tikz import save as tikz_save
                tikz_save('{}_{}_{}.tex'.format(
                    filename, group['dataset'][0]['title'].replace('_', '-'),
                    ds // idf.model.num_dofs),
                          figureheight='\\figureheight',
                          figurewidth='\\figurewidth',
                          show_info=False)

        if idf.opt['outputAs'] == 'html':
            path = os.path.dirname(os.path.abspath(__file__))
            template_environment = Environment(
                autoescape=False,
                loader=FileSystemLoader(os.path.join(path, '../output')),
                trim_blocks=False)

            context = {'figures': figures, 'text': self.text}
            outfile = os.path.join(path, '..', 'output', filename)
            import codecs
            with codecs.open(outfile, 'w', 'utf-8') as f:
                html = template_environment.get_template(
                    "templates/index.html").render(context)
                f.write(html)

            print("Saved output at file://{}".format(outfile))
        elif idf.opt['outputAs'] == 'interactive':
            #keep non-blocking plot windows open
            plt.show()
        elif idf.opt['outputAs'] == 'pdf':
            pp.close()