Exemple #1
0
    def render(self, t = 'png'):
        canvas = FigureCanvas(self.fig)
        output = StringIO.StringIO()

        with Timer() as duration:
            if t == 'svg':
                canvas.print_svg(output)
            if t == 'pdf':
                canvas.print_pdf(output)
            else:
                canvas.print_png(output)

        app.logger.debug("Generating %s took %d ms", t.upper(), duration.miliseconds())

        return output.getvalue()
Exemple #2
0
def plot_3d(request):

    fig = Figure(figsize=(12, 7), edgecolor='white', facecolor='white')
    fig.subplots_adjust(top=0.95)
    fig.subplots_adjust(bottom=0.07)
    fig.subplots_adjust(left=0.06)
    fig.subplots_adjust(right=0.98)

    plot_type = request.GET.get('plot_type', 'png')

    available_types = []
    available_measurement_types = measurement_type.objects.all()
    for item in available_measurement_types:
        if item.data_type == 'FLOAT':
            type_row = []
            type_row.append(item.measurement_type_id)
            type_row.append(item.measurement_type_name)
            available_types.append(type_row)

    type_id_01 = request.GET.get('type_id_01', available_types[0][1])
    type_id_02 = request.GET.get('type_id_02', available_types[1][1])

    #import pdb; pdb.set_trace() # debugging code

    measurement_type_item1 = measurement_type.objects.filter(measurement_type_name = type_id_01)
    measurement_type_item2 = measurement_type.objects.filter(measurement_type_name = type_id_02)
    unit1 = measurement_type_item1[0].units
    unit2 = measurement_type_item2[0].units

    # This is the grb subset that passes all the user cuts...
    #grb_table = measurement.objects.filter(date__range = (x_min, x_max)) # there can be duplicates here...need to fix this later

    grb_set, parameters = get_grb_sample(request)

    # both measurements must have same number of rows...
    # if one item is missing then the other item should be ignored...
    x_log = request.GET.get('x_log', 'False')
    y_log = request.GET.get('y_log', 'False')

    x = []
    y = []
    for grb_item in grb_set:
        measurement_value1 = grb_item[type_id_01]
        measurement_value2 = grb_item[type_id_02]
        if (measurement_value1 != '-') and (measurement_value2 != '-'):
            if (measurement_value1 > 0) and (x_log == 'True'):
                x.append(math.log10(measurement_value1))
            else:
                x.append(measurement_value1)
            if (measurement_value2 > 0) and (y_log == 'True'):
                y.append(math.log10(measurement_value2))
            else:
                y.append(measurement_value2)

    #print x
    #print y
    #import pdb; pdb.set_trace() # debugging code
    #import numpy as np
    #x = np.random.randn(1000)

    if x_log == 'True':
        if len(unit1) > 1:
            if unit1 != 'None':
                x_label = 'log ' + request.GET.get('x_label', type_id_01) + ' (' + unit1 + ')'
            else:
                x_label = 'log ' + request.GET.get('x_label', type_id_01)
        else:
            x_label = 'log ' + request.GET.get('x_label', type_id_01)

    else:
        if len(unit1) > 1:
            if unit1 != 'None':
                x_label = request.GET.get('x_label', type_id_01) + ' (' + unit1 + ')'
            else:
                x_label = request.GET.get('x_label', type_id_01)
        else:
            x_label = request.GET.get('x_label', type_id_01)

    if y_log == 'True':
        if len(unit2) > 1:
            if unit2 != 'None':
                y_label = 'log ' + request.GET.get('y_label', type_id_02) + ' (' + unit2 + ')'
            else:
                y_label = 'log ' + request.GET.get('y_label', type_id_02)
        else:
            y_label = 'log ' + request.GET.get('y_label', type_id_02)

    else:
        if len(unit2) > 1:
            if unit2 != 'None':
                y_label = request.GET.get('y_label', type_id_02) + ' (' + unit2 + ')'
            else:
                y_label = request.GET.get('y_label', type_id_02)
        else:
            y_label = request.GET.get('y_label', type_id_02)

    num_points = len(x)
    sample_size_str = " (Number of GRB: " + str(num_points) + ")"

    title = request.GET.get('title', 'Correlation Plot') + sample_size_str

    ax=fig.add_subplot(111)
    ax.plot(x, y, 'ro')

    #n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
    #if (y_log == 'True'):
    #    n, bins, patches = ax.hist(x, bin_num, facecolor='green', alpha=0.75, log=True)
    #else:
    #    n, bins, patches = ax.hist(x, bin_num, facecolor='green', alpha=0.75)

    #import pdb; pdb.set_trace() # debugging code

    x_scale_min = int(request.GET.get('x_min', 0))
    x_scale_max = int(request.GET.get('x_max', 0))
    y_scale_min = int(request.GET.get('y_min', 0))
    y_scale_max = int(request.GET.get('y_max', 0))

    if (x_scale_min <  x_scale_max) and (y_scale_min <  y_scale_max):
        #import pdb; pdb.set_trace() # debugging code
        ax.axis([x_scale_min, x_scale_max, y_scale_min, y_scale_max])


    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
    ax.set_title(title)

    #import ipdb; ipdb.set_trace() # debugging code
    statistics_str = "Correlation Coefficient : {0:.3}".format(ds.corr(x, y))
    #print statistics_str
    ax.text(0.05, 0.9, statistics_str,
        fontsize=15,
        #color='blue',
        bbox={'facecolor':'yellow', 'pad':10, 'alpha':0.65},
        horizontalalignment='left',
        verticalalignment='center',
        transform = ax.transAxes)

    canvas=FigureCanvas(fig)

    if plot_type == 'png':
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

    if plot_type == 'pdf':
        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="histo.pdf"'
        #response=django.http.HttpResponse(content_type='image/pdf')
        #response=['Content-Disposition'] = 'attachment; filename=plot.pdf'
        canvas.print_pdf(response)


    if plot_type == 'text':
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename="plot.csv"'
        writer = csv.writer(response)
        if num_points > 0:
            writer.writerow(['X Values'])
            for i in range(num_points):
                writer.writerow([x[i]])
            writer.writerow(['Y Values'])
            for i in range(num_points):
                writer.writerow([y[i]])
        else:
            writer.writerow(["No data!"])

    return response
Exemple #3
0
def histo(request):

    fig = Figure(figsize=(12, 7), edgecolor='white', facecolor='white')
    fig.subplots_adjust(top=0.95)
    fig.subplots_adjust(bottom=0.07)
    fig.subplots_adjust(left=0.06)
    fig.subplots_adjust(right=0.98)

    plot_type = request.GET.get('plot_type', 'png')
    bin_num = int(request.GET.get('bin_num', '25'))
    m_type = str(request.GET.get('measurement_type', 'T90'))

    grb_set, parameters = get_grb_sample(request)

    #import ipdb; ipdb.set_trace() # debugging code

    # following code will improve the plotting speed...
    measurement_type_item = measurement_type.objects.filter(measurement_type_name = m_type)
    unit = measurement_type_item[0].units

    #measurement_table = measurement.objects.filter(measurement_type=measurement_type_item[0])
    #import pdb; pdb.set_trace() # debugging code

    x_log = request.GET.get('x_log', 'False')
    y_log = request.GET.get('y_log', 'False')

    x = []
    for item in grb_set:
        measurement_value = item[m_type]
        if measurement_value != '-':
            if (measurement_value > 0) and (x_log == 'True'):
                x.append(math.log10(measurement_value))
            else:
                x.append(measurement_value)
    #print x
    #import ipdb; ipdb.set_trace() # debugging code
    #import numpy as np
    #x = np.random.randn(1000)
    num_points = len(x)
    sample_size_str = " (Number of GRBs: " + str(num_points) + ")"

    if (x_log == 'True'):
        if len(unit) > 1:
            if unit != 'None':
                x_label = 'log ' + request.GET.get('x_label', m_type) + ' (' + unit + ')'
            else:
                x_label = 'log ' + request.GET.get('x_label', m_type)
        else:
            x_label = 'log ' + request.GET.get('x_label', m_type)
    else:
        if len(unit) > 1:
            if unit != 'None':
                x_label = request.GET.get('x_label', m_type) + ' (' + unit + ')'
            else:
                x_label = request.GET.get('x_label', m_type)
        else:
            x_label = request.GET.get('x_label', m_type)
    y_label = request.GET.get('y_label', 'Counts')
    title = request.GET.get('title', 'Histogram') + sample_size_str

    ax=fig.add_subplot(111)
    #ax.plot(x, y, 'r', linewidth=2.0)

    #n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)
    if (y_log == 'True'):
        n, bins, patches = ax.hist(x, bin_num, facecolor='green', alpha=0.75, log=True)
    else:
        n, bins, patches = ax.hist(x, bin_num, facecolor='green', alpha=0.75)

    x_scale_min = int(request.GET.get('x_min', 0))
    x_scale_max = int(request.GET.get('x_max', 0))
    y_scale_min = int(request.GET.get('y_min', 0))
    y_scale_max = int(request.GET.get('y_max', 0))

    if (x_scale_min <  x_scale_max) and (y_scale_min <  y_scale_max):
        #import pdb; pdb.set_trace() # debugging code
        ax.axis([x_scale_min, x_scale_max, y_scale_min, y_scale_max])


    ax.set_xlabel(x_label)
    ax.set_ylabel(y_label)
    ax.set_title(title)

    #import ipdb; ipdb.set_trace() # debugging code
    statistics_str = "Mean : {0:.3} \nStd. Deviation : {1:.3}".format(ds.mean(x), ds.std(x))
    #print statistics_str
    ax.text(0.05, 0.9, statistics_str,
        fontsize=15,
        #color='blue',
        bbox={'facecolor':'yellow', 'pad':10, 'alpha':0.65},
        horizontalalignment='left',
        verticalalignment='center',
        transform = ax.transAxes)

    canvas=FigureCanvas(fig)

    if plot_type == 'png':
        response=HttpResponse(content_type='image/png')
        canvas.print_png(response)

    if plot_type == 'pdf':
        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="histo.pdf"'
        #response=django.http.HttpResponse(content_type='image/pdf')
        #response=['Content-Disposition'] = 'attachment; filename=plot.pdf'
        canvas.print_pdf(response)


    if plot_type == 'text':
        response = HttpResponse(mimetype='text/csv')
        response['Content-Disposition'] = 'attachment; filename="histo.csv"'
        writer = csv.writer(response)
        if len(n) > 0:
            writer.writerow(['Counts'])
            for i in range(len(n)):
                writer.writerow([n[i]])
            writer.writerow(['Bins'])
            for i in range(len(bins)):
                writer.writerow([bins[i]])
        else:
            writer.writerow(["No data!"])

    return response
Exemple #4
0
    def produce(self,local_options=None):
        global panel_j
        global _ACCOUNTING        

        _trn = {
            'figsize' : (tuple_of_floats, tuple),
            'dpi' : int,
            'facecolor' : str,
            'edgecolor' : str,
            'linewidth' : float,
            'frameon' :  (boolean, int)
        }
        
        # Get Local Defaults
        l_defaults = self.get_defaults(local_options)

        # logdict(LOGGER.debug,'{PRODUCE} FIGURE LOCAL OPTIONS',l_defaults)
        # logdict(LOGGER.debug,'{PRODUCE} self keys',self)

        figure_options = extract_dict_from_key('OPTIONS',
                                               self,
                                               self._genspec,
                                               l_defaults,
                                               klass=ldict)
        figure_options['frameon']=True

        # reduce vertical size if footnote are present
        # 
        if self._footnote_text_len()>0:            
            lines = int((self._footnote_text_len() / 180)+1)
            w,h = tuple_of_floats(figure_options['figsize'])
            h-=.19*lines
            figure_options['figsize']=u"(%f,%f)"%(w,h)
            
        ex = cast_dict(figure_options,_trn)[0]
        # logdict(LOGGER.debug,'{PRODUCE} FIGURE with OPTIONS',ex)
        _ACCOUNTING['figure_options']=ex
        # fig = plt.figure(**ex)
        # fig = plt.figure()
        # fig = plt.figure(dpi=300,figsize=(12,7))
        # fig =  mpl.figure.Figure(**ex)
        # backend_name = 'matplotlib.backends.backend_pdf'
        # self.backend_mod = __import__(backend_name,
        #                              globals(),locals(),
        #                              [backend_name])
        # self.new_figure_manager = self.backend_mod.new_figure_manager
        from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
        from matplotlib.figure import Figure
        fig = Figure(**ex)
        cvs = FigureCanvas(fig)

        # Create panels
        for j,vb in enumerate(self._elems):
            p_j = int(vb.spec.xget('POS',j+1)) # panel id [1->...]
            panel_j = p_j
            fig = self.produce_panel(fig,
                                     vb,
                                     p_j,
                                     { 'OPTIONS': figure_options })


        # Save fig
        _format = 'pdf'
        
        # plt.subplots_adjust(left=0.1, right=0.1, top=0.1, bottom=0.1)
        if fig:
            LOGGER.debug('Salvataggio della figura %s',self._imgfile)
            cvs.print_pdf(self._imgfile)
            fig.savefig(self._imgfile,format=_format,
                        orientation='landscape',                       
                        trasparent=True,
                        bbox_inches='tight')

        return self._unplotted