def age_specific_rate_function_sparkplot(request, id_str, format='png'):
    asrfs = view_utils.id_str_to_objects(id_str, AgeSpecificRateFunction)

    width = 1
    height = .5
    
    fig = view_utils.clear_plot(width,height)
    pl.subplot(1, 1, 1, frameon=False)
    ax = None
    for ii, rf in enumerate(asrfs):
        plot_truth(rf)
        plot_mcmc_fit(rf)
        #plot_fit(rf, 'mcmc_mean', color='#000000')

        #plot_map_fit(rf)
        #plot_mcmc_fit(rf)
        #plot_prior(rf)
        pl.xticks([])
        pl.yticks([])
        #pl.delaxes()
    pl.subplots_adjust(left=-.1, bottom=0, right=1, top=1.1,
                    wspace=0, hspace=0)

    return HttpResponse(view_utils.figure_data(format),
                        view_utils.MIMETYPE[format])
def age_specific_rate_function_redirect(request, id_str, action):
    asrfs = view_utils.id_str_to_objects(id_str, AgeSpecificRateFunction)

    if action == 'edit':
        url = '/admin/dismod3/agespecificratefunction/%d' % asrfs[0].id
    elif action in view_utils.command_list['move']:
        url = reverse('dismod3.views.age_specific_rate_function_show', args=(asrfs[0].id+view_utils.id_delta[action],))
    elif action in view_utils.command_list['sex']:
        url = AgeSpecificRateFunction.objects.filter(disease=asrfs[0].disease, region=asrfs[0].region, rate_type=asrfs[0].rate_type, sex=action)[0].get_absolute_url()
    elif action in view_utils.command_list['format']:
        url = '%s.%s' % (asrfs[0].get_absolute_url(), action)
    else:
        raise Http404
    
    return HttpResponseRedirect(url)
def age_specific_rate_function_compare(request, id_str, format='html'):
    """
    display information for comparing multiple age specific rate functions
    
    id_str is a comma separate list of asrf ids, and format can be html
    or a graphics format that is recognized by matplotlib
    """
    asrfs = view_utils.id_str_to_objects(id_str, AgeSpecificRateFunction)
    if format == 'html':
        return render_to_response('age_specific_rate_function/compare.html', {'id_str': id_str, 'asrfs': asrfs})

    size = request.GET.get('size', default='normal')
    style = request.GET.get('style', default='overlay')

    if size == 'small':
        width = 3
        height = 2
    elif size == 'full_page':
        width = 11
        height = 8.5
    else:
        width = 6
        height = 4

    max_rate = .0001

    view_utils.clear_plot(width=width,height=height)
    try:
        if style == 'overlay':
            for ii, rf in enumerate(asrfs):
                plot_fit(rf, 'map', alpha=.75, linewidth=5, label='asrf %d'%rf.id)
                max_rate = np.max([max_rate] + rf.fit['map'])
            pl.axis([0, 100, 0, 1.25*max_rate])

        elif style == 'scatter':
            x, y = [ [ asrfs[ii].fit[fit_type] for fit_type in ['mcmc_mean', 'mcmc_lower_cl', 'mcmc_upper_cl'] ] for ii in [0,1] ]

            max_x = np.max(x[2])
            max_y = np.max(y[2])
            max_t = max(max_x, max_y, .00001)

            xerr = np.abs(np.array(x[1:]) - np.array(x[0]))
            yerr = np.abs(np.array(y[1:]) - np.array(y[0]))

            pl.plot([probabilistic_utils.NEARLY_ZERO,1.], [probabilistic_utils.NEARLY_ZERO,1.], linestyle='dashed', linewidth=2, color='black', alpha=.75)
            pl.errorbar(x=x[0], xerr=xerr, y=y[0], yerr=yerr, fmt='bo')
            pl.axis([0,max_t,0,max_t])

        elif style == 'stack':
            n = asrfs.count()
            max_t = probabilistic_utils.NEARLY_ZERO
            for ii in range(n):
                x = asrfs[ii].fit['mcmc_mean']
                max_t = max(np.max(x), max_t)

                pl.subplot(n, 1, ii+1, frameon=False)
                pl.plot(x, linewidth=3)
                if size != 'small':
                    pl.title(asrfs[ii])
                pl.axis([0, 100, 0, max_t*1.1])
                pl.xticks([])
                pl.yticks([])
            pl.subplots_adjust(left=0, right=1)

        elif style == 'parallel':
            for xx in zip(*[ rf.fit['mcmc_mean'] for rf in asrfs ]):
                pl.plot(xx, linewidth=2, color='blue', alpha=.5)
            xmin, xmax, ymin, ymax = pl.axis()
            pl.vlines(range(len(asrfs)), ymin, ymax, color='black', linestyles='dashed',
                      alpha=.5, linewidth=2)
            pl.xticks(range(len(asrfs)), [ 'asrf %d' % rf.id for rf in asrfs ])
    except KeyError:
        pass
        #pl.figtext(0.4,0.2, 'No MCMC Fit Found')

    if size == 'small':
        pl.xticks([])
        pl.yticks([])
    else:
        if style != 'stack' and style != 'parallel':
            pl.legend()
            view_utils.label_plot('Comparison of Age-Specific Rate Functions')

    return HttpResponse(view_utils.figure_data(format),
                        view_utils.MIMETYPE[format])
def age_specific_rate_function_show(request, id_str, format='html'):
    asrfs = view_utils.id_str_to_objects(id_str, AgeSpecificRateFunction)

    if format == 'html':
        return render_to_response('age_specific_rate_function/show.html',
                                  view_utils.template_params(asrfs[0], asrfs=asrfs, id_str=id_str, query_str=request.META['QUERY_STRING']))

    # handle json & csv formats
    if format in ['json', 'csv']:
        if format == 'json':
            data_str = json.dumps([[rf.id, rf.fit] for rf in asrfs])
        elif format == 'csv':
            headings = {}
            rows = {}
            data_str = ''

            for rf in asrfs:
                headings[rf] = ['Age (years)', 'MAP Rate (per 1.0)']
                rows[rf] = [[a, p] for a,p in zip(rf.fit['out_age_mesh'], rf.fit['map'])]
                data_str += view_utils.csv_str(headings[rf], rows[rf])
        return HttpResponse(data_str, view_utils.MIMETYPE[format])

    # handle graphics formats
    cnt = asrfs.count()
    cols = 2
    rows = int(np.ceil(float(cnt) / float(cols)))

    subplot_width = 6
    subplot_height = 4
    
    view_utils.clear_plot(width=subplot_width*cols,height=subplot_height*rows)
    for ii, rf in enumerate(asrfs):
        pl.subplot(rows,cols,ii+1)
        if request.GET.get('bars'):
            bars_mcmc_fit(rf)
            #plot_map_fit(rf, alpha=.3)
            plot_truth(rf)
        else:
            plot_intervals(rf, rf.rates.all(), fontsize=12, alpha=.5)
            plot_intervals(rf, rf.rates.filter(params_json__contains='Rural'), fontsize=12, alpha=.5, color='brown')
            #plot_normal_approx(rf)
            plot_map_fit(rf)
            plot_mcmc_fit(rf)
            plot_truth(rf)
            plot_prior(rf)
            pl.text(0,0,rf.fit.get('priors',''), color='black', family='monospace', alpha=.75)
        view_utils.label_plot('%s (id=%d)' % (rf, rf.id), fontsize=10)
        
        max_rate = np.max([.0001] + [r.rate for r in rf.rates.all()] + rf.fit.get('mcmc_upper_cl', []))
        xmin = float(request.GET.get('xmin', default=0.))
        xmax = float(request.GET.get('xmax', default=100.))
        ymin = float(request.GET.get('ymin', default=0.))
        ymax = float(request.GET.get('ymax', default=1.25*max_rate))
        pl.axis([xmin, xmax, ymin, ymax])

        if ii % cols != 0:
            pl.ylabel('')
        #pl.yticks([])
        if (ii + cols) < cnt:
            pl.xlabel('')
        #pl.xticks([])
    
    
    return HttpResponse(view_utils.figure_data(format),
                        view_utils.MIMETYPE[format])