Ejemplo n.º 1
0
def tricontouring_response(tri_subset, data, request, dpi=None):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x,
                                                  tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.tricontourf(tri_subset, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'contours':
        ax.tricontour(tri_subset, data, lvls, norm=norm, cmap=colormap)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    return figure_response(fig, request)
Ejemplo n.º 2
0
def quiver_response(lon, lat, dx, dy, request, dpi=None):

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    vectorscale = request.GET['vectorscale']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    unit_vectors = None  # We don't support requesting these yet, but wouldn't be hard

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=cmap, norm=norm, scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 3
0
def tricontouring_response(tri_subset, data, request, dpi=None):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x, tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax, clip=True)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.tricontourf(tri_subset, data, lvls, norm=norm, cmap=colormap, extend='both')
    elif request.GET['image_type'] == 'contours':
        ax.tricontour(tri_subset, data, lvls, norm=norm, cmap=colormap, extend='both')

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 4
0
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    request,
                    vectorscale,
                    unit_vectors=False,
                    dpi=80):

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)
    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    norm = None
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=cmap, scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 5
0
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    request,
                    vectorscale,
                    unit_vectors=False,
                    dpi=80):

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)
    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    norm = None
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=cmap, scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 6
0
def contouring_response(lon, lat, data, request, dpi=None):

    dpi = dpi or 80.

    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(request)
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin is not None and cmax is not None:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.contourf(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'contours':
        ax.contour(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'filledhatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x, y, data, lvls, norm=norm, cmap=colormap, hatches=hatches)
    elif request.GET['image_type'] == 'hatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x, y, data, lvls, norm=norm, colors='none', hatches=hatches)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 7
0
def tricontourf_response(tri_subset,
                         data,
                         request,
                         dpi=80.0,
                         nlvls=15):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """
    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x, tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(float(cmin), float(cmax), int(nlvls))
        ax.tricontourf(tri_subset, data, levels=lvls, cmap=colormap)
    else:
        ax.tricontourf(tri_subset, data, cmap=colormap)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 8
0
def tricontourf_response(tri_subset,
                         data,
                         request,
                         dpi=80.0,
                         nlvls=15):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """
    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    tri_subset.x, tri_subset.y = pyproj.transform(EPSG4326, crs, tri_subset.x, tri_subset.y)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(float(cmin), float(cmax), int(nlvls))
        ax.tricontourf(tri_subset, data, levels=lvls, cmap=colormap)
    else:
        ax.tricontourf(tri_subset, data, cmap=colormap)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 9
0
def contourf_response(lon,
                      lat,
                      data,
                      request,
                      dpi=80,
                      nlvls = 15):

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)

    width, height = wms_handler.get_width_height(request)

    colormap = wms_handler.get_colormap(request)

    cmin, cmax = wms_handler.get_climits(request)

    #proj = get_pyproj(request)
    #xcrs, ycrs = proj(lon.flatten(),lat.flatten())
    CRS = get_pyproj(request)
    xcrs, ycrs = pyproj.transform(EPSG4326, CRS, lon.flatten(),lat.flatten()) #TODO order for non-inverse?
    #logger.info("xcrs, ycrs: {0} {1}".format(xcrs, ycrs))

    xcrs = xcrs.reshape(data.shape)
    ycrs = ycrs.reshape(data.shape)

    sxcrs = np.argsort(xcrs[1,:])
    sycrs = np.argsort(ycrs[:,1])

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    lvls = np.linspace(cmin, cmax, nlvls)

    #ax.contourf(xcrs, ycrs, data, levels=lvls, cmap=colormap)
    ax.contourf(xcrs[sycrs,:][:,sxcrs], ycrs[sycrs,:][:,sxcrs], data[sycrs,:][:,sxcrs], levels=lvls, cmap=colormap)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0, 0, 1, 1])
    
    canvas = FigureCanvasAgg(fig)
    
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)

    return response
Ejemplo n.º 10
0
def create_projected_fig(lonmin, latmin, lonmax, latmax, projection, height, width):
    from mpl_toolkits.basemap import Basemap
    from matplotlib.figure import Figure
    fig = Figure(dpi=80, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height)
    fig.set_figwidth(width)
    m = Basemap(llcrnrlon=lonmin, llcrnrlat=latmin,
            urcrnrlon=lonmax, urcrnrlat=latmax, projection=projection,
            resolution=None,
            lat_ts = 0.0,
            suppress_ticks=True)
    m.ax = fig.add_axes([0, 0, 1, 1], xticks=[], yticks=[])
    return fig, m
Ejemplo n.º 11
0
def blank_figure(width, height, dpi=5):
    """
    return a transparent (blank) response
    used for tiles with no intersection with the current view or for some other error.
    """
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    ax = fig.add_axes([0, 0, 1, 1])
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0, 0, 1, 1])
    return fig
Ejemplo n.º 12
0
class canvas(FigureCanvas):
    def __init__(self, parent, double=False):

        # Se instancia el objeto figure
        self.fig = Figure()
        self.fig.set_alpha(0)
        self.fig.patch.set_facecolor('None')
        self.fig.patch.set_alpha(0.0)
        # Se define la grafica en coordenadas polares
        self.axes = self.fig.add_subplot(111)
        self.axes.set_facecolor('None')
        self.axes.set_alpha(0.0)
        # Se define una grilla
        self.axes.grid(color='xkcd:mint green',
                       linestyle='-',
                       linewidth=0.5,
                       visible=True)

        # se inicializa FigureCanvas
        super(canvas, self).__init__(self.fig)
        # se define el widget padre
        self.axes.tick_params(axis='x', colors='xkcd:mint green')
        self.axes.tick_params(axis='y', colors='xkcd:mint green')

        if double:
            self.ax2 = self.axes.twinx()
            self.ax2.tick_params('y', colors='xkcd:mint green')

        self.setParent(parent)
        self.fig.canvas.draw()

    def reload(self, double=False):
        self.axes.cla()
        # Se define una grilla
        self.axes.grid(True)

    def plot(self, x, y, y2=None, color1='r', color2='b', double=False):

        # Dibujar Curva
        self.reload()
        if double:
            self.axes.plot(x, y, color1)
            self.ax2.plot(x, y2, color2)
        else:
            if y2:
                self.axes.plot(x, y, y2, color1)
            else:
                self.axes.plot(x, y, color1)
        self.fig.canvas.draw()
Ejemplo n.º 13
0
def blank_canvas(width, height, dpi=5):
    """
    return a transparent (blank) response
    used for tiles with no intersection with the current view or for some other error.
    """
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    ax = fig.add_axes([0, 0, 1, 1])
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0, 0, 1, 1])
    canvas = FigureCanvasAgg(fig)
    return canvas
Ejemplo n.º 14
0
def pcolormesh_response(lon,
                        lat,
                        data,
                        request,
                        dpi=80):
    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(request)

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        norm = norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, norm=norm, cmap=colormap)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 15
0
def pcolormesh_response(lon, lat, data, request, dpi=None):

    dpi = dpi or 80.

    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(
        request)

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        norm = norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, norm=norm, cmap=colormap)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 16
0
def pcolormesh_response(lon,
                        lat,
                        data,
                        request,
                        dpi=80):
    params = _get_common_params(request)
    bbox, width, height, colormap, cmin, cmax, crs = params

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    cmap = mpl.cm.get_cmap(colormap)

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        bounds = np.linspace(cmin, cmax, 15)
    else:
        norm = None
    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, vmin=5, vmax=30, norm=norm)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 17
0
def pcolormesh_response(lon,
                        lat,
                        data,
                        request,
                        dpi=80):
    params = _get_common_params(request)
    bbox, width, height, colormap, cmin, cmax, crs = params

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)
    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    cmap = mpl.cm.get_cmap(colormap)

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
        bounds = np.linspace(cmin, cmax, 15)
    else:
        norm = None
    masked = np.ma.masked_invalid(data)
    ax.pcolormesh(x, y, masked, vmin=5, vmax=30, norm=norm)
    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 18
0
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    height,
                    width,
                    # request,
                    unit_vectors=False,
                    dpi=80):

    # bbox = request.GET['bbox']
    # width = request.GET['width']
    # height = request.GET['height']
    # colormap = request.GET['colormap']
    # colorscalerange = request.GET['colorscalerange']
    # cmin = colorscalerange.min
    # cmax = colorscalerange.max
    colormap = 'spectral'
    cmin = 1
    cmax = 9
    # crs = request.GET['crs']

    # EPSG4326 = pyproj.Proj(init='EPSG:4326')
    # x, y = pyproj.transform(EPSG4326, crs, lon, lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)
    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    norm = None
    if cmin and cmax:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        bounds = np.linspace(cmin, cmax, 15)
        norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    # plot unit vectors
    if unit_vectors:
        ax.quiver(lon, lat, dx/mags, dy/mags, mags, cmap=cmap)
    else:
        ax.quiver(lon, lat, dx, dy, mags, cmap=cmap, norm=norm)
        
    x_min = np.min(lon)
    x_max = np.max(lon)
    y_min = np.min(lat)
    y_max = np.max(lat)

    ax.set_xlim(x_min, x_max)
    ax.set_ylim(y_min, y_min)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    # response = HttpResponse(content_type='image/png')
    png_path = 'C:\\Users\\ayan\\Desktop\\tmp\\blah.png'
    canvas.print_png(png_path)
    return mags
Ejemplo n.º 19
0
def contouring_response(lon, lat, data, request, dpi=None):

    dpi = dpi or 80.

    bbox, width, height, colormap, cmin, cmax, crs = _get_common_params(
        request)
    nlvls = request.GET['numcontours']

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon, lat)

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    if cmin and cmax:
        data[data > cmax] = cmax
        data[data < cmin] = cmin
        lvls = np.linspace(cmin, cmax, nlvls)
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        lvls = nlvls
        norm = norm_func()

    if request.GET['image_type'] == 'filledcontours':
        ax.contourf(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'contours':
        ax.contour(x, y, data, lvls, norm=norm, cmap=colormap)
    elif request.GET['image_type'] == 'filledhatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x,
                    y,
                    data,
                    lvls,
                    norm=norm,
                    cmap=colormap,
                    hatches=hatches)
    elif request.GET['image_type'] == 'hatches':
        hatches = DEFAULT_HATCHES[:lvls]
        ax.contourf(x,
                    y,
                    data,
                    lvls,
                    norm=norm,
                    colors='none',
                    hatches=hatches)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 20
0
def quiver_response(lon, lat, dx, dy, request, dpi=None):

    dpi = dpi or 80.

    bbox = request.GET['bbox']
    width = request.GET['width']
    height = request.GET['height']
    colormap = request.GET['colormap']
    colorscalerange = request.GET['colorscalerange']
    vectorscale = request.GET['vectorscale']
    cmin = colorscalerange.min
    cmax = colorscalerange.max
    crs = request.GET['crs']
    unit_vectors = None  # We don't support requesting these yet, but wouldn't be hard

    EPSG4326 = pyproj.Proj(init='EPSG:4326')
    x, y = pyproj.transform(EPSG4326, crs, lon,
                            lat)  # TODO order for non-inverse?

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height / dpi)
    fig.set_figwidth(width / dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    mags = np.sqrt(dx**2 + dy**2)

    cmap = mpl.cm.get_cmap(colormap)

    if request.GET['logscale'] is True:
        norm_func = mpl.colors.LogNorm
    else:
        norm_func = mpl.colors.Normalize

    # Set out of bound data to NaN so it shows transparent?
    # Set to black like ncWMS?
    # Configurable by user?
    if cmin is not None and cmax is not None:
        mags[mags > cmax] = cmax
        mags[mags < cmin] = cmin
        norm = norm_func(vmin=cmin, vmax=cmax)
    else:
        norm = norm_func()

    # plot unit vectors
    if unit_vectors:
        ax.quiver(x,
                  y,
                  dx / mags,
                  dy / mags,
                  mags,
                  cmap=cmap,
                  norm=norm,
                  scale=vectorscale)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm, scale=vectorscale)

    ax.set_xlim(bbox.minx, bbox.maxx)
    ax.set_ylim(bbox.miny, bbox.maxy)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 21
0
def getLegendGraphic(request, dataset):
    """
    Parse parameters from request that looks like this:

    http://webserver.smast.umassd.edu:8000/wms/NecofsWave?
    ELEVATION=1
    &LAYERS=hs
    &TRANSPARENT=TRUE
    &STYLES=facets_average_jet_0_0.5_node_False
    &SERVICE=WMS
    &VERSION=1.1.1
    &REQUEST=GetLegendGraphic
    &FORMAT=image%2Fpng
    &TIME=2012-06-20T18%3A00%3A00
    &SRS=EPSG%3A3857
    &LAYER=hs
    """
    styles = request.GET["styles"].split("_")
    try:
        climits = (float(styles[3]), float(styles[4]))
    except:
        climits = (None, None)
    variables = request.GET["layer"].split(",")
    plot_type = styles[0]
    colormap = styles[2].replace('-', '_')

    # direct the service to the dataset
    # make changes to server_local_config.py
    if settings.LOCALDATASET:
        url = settings.LOCALDATASETPATH[dataset]
    else:
        url = Dataset.objects.get(name=dataset).path()
    nc = netCDF4.Dataset(url)

    """
    Create figure and axes for small legend image
    """
    #from matplotlib.figure import Figure
    from matplotlib.pylab import get_cmap
    fig = Figure(dpi=100., facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figwidth(1*1.3)
    fig.set_figheight(1.5*1.3)

    """
    Create the colorbar or legend and add to axis
    """
    v = cf.get_by_standard_name(nc, variables[0])

    try:
        units = v.units
    except:
        units = ''
    # vertical level label
    if v.ndim > 3:
        units = units + '\nvertical level: %s' % _get_vertical_level(nc, v)
    if climits[0] is None or climits[1] is None:  # TODO: NOT SUPPORTED RESPONSE
            #going to have to get the data here to figure out bounds
            #need elevation, bbox, time, magnitudebool
            CNorm = None
            ax = fig.add_axes([0, 0, 1, 1])
            ax.grid(False)
            ax.text(.5, .5, 'Error: No Legend\navailable for\nautoscaled\ncolor styles!', ha='center', va='center', transform=ax.transAxes, fontsize=8)
    elif plot_type not in ["contours", "filledcontours"]:
        #use limits described by the style
        ax = fig.add_axes([.01, .05, .2, .8])  # xticks=[], yticks=[])
        CNorm = matplotlib.colors.Normalize(vmin=climits[0],
                                            vmax=climits[1],
                                            clip=False,
                                            )
        cb = matplotlib.colorbar.ColorbarBase(ax,
                                              cmap=get_cmap(colormap),
                                              norm=CNorm,
                                              orientation='vertical',
                                              )
        cb.set_label(units, size=8)

    else:  # plot type somekind of contour
        if plot_type == "contours":
            #this should perhaps be a legend...
            #ax = fig.add_axes([0,0,1,1])
            fig_proxy = Figure(frameon=False, facecolor='none', edgecolor='none')
            ax_proxy = fig_proxy.add_axes([0, 0, 1, 1])
            CNorm = matplotlib.colors.Normalize(vmin=climits[0], vmax=climits[1], clip=True)
            #levs = numpy.arange(0, 12)*(climits[1]-climits[0])/10
            levs = numpy.linspace(climits[0], climits[1], 11)
            x, y = numpy.meshgrid(numpy.arange(10), numpy.arange(10))
            cs = ax_proxy.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(colormap))

            proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

            fig.legend(proxy, levs,
                       #bbox_to_anchor = (0, 0, 1, 1),
                       #bbox_transform = fig.transFigure,
                       loc = 6,
                       title = units,
                       prop = { 'size' : 8 },
                       frameon = False,
                       )
        elif plot_type == "filledcontours":
            #this should perhaps be a legend...
            #ax = fig.add_axes([0,0,1,1])
            fig_proxy = Figure(frameon=False, facecolor='none', edgecolor='none')
            ax_proxy = fig_proxy.add_axes([0, 0, 1, 1])
            CNorm = matplotlib.colors.Normalize(vmin=climits[0], vmax=climits[1], clip=False,)
            #levs = numpy.arange(1, 12)*(climits[1]-(climits[0]))/10
            levs = numpy.linspace(climits[0], climits[1], 10)
            levs = numpy.hstack(([-99999], levs, [99999]))

            x, y = numpy.meshgrid(numpy.arange(10), numpy.arange(10))
            cs = ax_proxy.contourf(x, y, x, levels=levs, norm=CNorm, cmap=get_cmap(colormap))

            proxy = [plt.Rectangle((0, 0), 0, 0, fc=pc.get_facecolor()[0]) for pc in cs.collections]

            levels = []
            for i, value in enumerate(levs):
                #if i == 0:
                #    levels[i] = "<" + str(value)
                if i == len(levs)-2 or i == len(levs)-1:
                    levels.append("> " + str(value))
                elif i == 0:
                    levels.append("< " + str(levs[i+1]))
                else:
                    #levels.append(str(value) + "-" + str(levs[i+1]))
                    text = '%.2f-%.2f' % (value, levs[i+1])
                    levels.append(text)
            fig.legend(proxy, levels,
                       #bbox_to_anchor = (0, 0, 1, 1),
                       #bbox_transform = fig.transFigure,
                       loc = 6,
                       title = units,
                       prop = { 'size' : 6 },
                       frameon = False,
                       )

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    nc.close()
    return response
Ejemplo n.º 22
0
class StylistTkinter(ttk.Frame):
    _WINDOW_TITLE = "Generic Title"
    opts = {}
    mplparams = {}

    """
    Present tool sytlization choices for a matplotlib plot.
    1. Create the plot required to build this up
    2. Create all of the appropriate widgets
    """

    def styleChange(self, name1, name2, op):
        """
        :param name1: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        :param name2: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        :param op: http://www.tcl.tk/man/tcl8.4/TclCmd/trace.htm#M14
        """
        logging.debug("styleChange detected with arguments (%s, %s, %s)" % (name1, name2, op))
        logging.debug("styleChange executing a change from to %s", self.mpl_global_style.get())
        plt.style.use(
            self.mpl_global_style.get()
        )  # TODO can you set this up to use name1 ? Yes, tk.StringVar() contains _name

        # clean up the existing stuff, deleting all of the components within the canvas
        self.canvas.get_tk_widget().delete("all")
        for child in self.mplframe.winfo_children():
            child.destroy()
        self.figure.clear()
        self.axes.clear()
        del self.line, self.axes, self.figure

        # recretae the plot, the frame it resides in is already created and useful
        self.createPlot()
        logging.debug("styleChange completed with new style changed to %s" % self.mpl_global_style.get())

    def loadOptions(self):
        logging.debug("loadOptions invocation")
        self.opts["mpl_style_idx"] = 0
        self.mplparams["styles"] = plt.style.available
        logging.debug('loadOptions set self.mplparams["styles"] = %s' % repr(self.mplparams["styles"]))
        optpath = os.path.join(os.getcwd(), "res", "stylist.opt")
        logging.debug("loading options: loading option file from %s" % (optpath))
        self.master.option_readfile(optpath)
        # fixme having some trouble with the namespaces of the options database

    def applyOptions(self):
        logging.debug("applyOptions invocation")
        plt.style.use(self.mplparams["styles"][self.opts["mpl_style_idx"]])
        for s in self.mplparams["styles"]:
            if self.opts["mpl_style_idx"] == s:
                self.mplparams["style_default"] = self.mplparams["styles"].index[s]

    def createPlot(self):
        logging.debug("createPlot invocation")
        self.figure = Figure(figsize=(5, 4), dpi=100)
        self.axes = self.figure.add_subplot(111)
        self.line, = self.axes.plot(self.x, self.y)
        self.canvas = FigureCanvasTkAgg(self.figure, master=self.mplframe)
        self.canvas.show()
        # add the mpl toolbar to the toolbar
        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.mplframe)
        self.toolbar.update()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def scaleFigAlpha(self, value):
        logging.debug("scaleFigAlpha called with alpha = %s" % value)
        self.figure.set_alpha(value)

    def createWidgets(self):
        logging.debug("createWidgets invocation")
        # todo add a menu region
        # a tk.DrawingArea containing the appropriate toolbars
        logging.debug("createWidgets building Matplotlib components for Tkinter integration")
        self.mplframe = ttk.Frame(class_="matplotstylist", name="mplframe")
        self.createPlot()
        self.mplframe.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # The following contains the right hand style configuration area
        self.styleframe = ttk.Frame(class_="matplotstylist", name="styleframe")
        self.styleframe.pack(side=tk.RIGHT, anchor=tk.NE, fill=tk.X, expand=1, ipadx=2, ipady=2, padx=2, pady=2)
        # todo evaluation if you should Add a listbox describing the potentially available styles, permits compositing
        # self.lbx_styles = tk.Listbox(self, activestyle='dotbox',
        #                              listvariable=tk.StringVar(value=" ".join(self.mplparams["styles"])
        #                                                        , name="mplparams.styles"),
        #                              selectmode=tk.SINGLE)
        # self.lbx_styles.activate(self.opts['mpl_style_idx'])
        # self.lbx_styles.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        # Add an OptionsMenu describing the potentially available styles
        self.mpl_global_style = tk.StringVar()
        self.mpl_global_style.set(self.mplparams["styles"][self.opts["mpl_style_idx"]])
        self.omu_styles = tk.OptionMenu(self.styleframe, self.mpl_global_style, *self.mplparams["styles"])
        self.omu_styles.pack(side=tk.TOP, fill=tk.X, expand=1)

        logging.debug("createWidgets creating and populating styleframe artist's notebook")
        self.artist_notebook = ArtistStyleBook(self.styleframe)

        # add one tab for each type of artist in the plot
        """ populate the artists notebook with the controls to set/get each and every setable property
        of the artists used by the figure and its children.  Each artist may be inspected interactively
        using matplotlib.artist.getp(object), which lists each property and their values.
        These same properties may be identified using "artists"
        """
        self.styletab_figure = FigureParametrics(self.artist_notebook, self.figure)
        self.styletab_axes = AxesParametrics(self.artist_notebook, self.axes)
        self.styletab_primitives = PrimitiveParametrics(self.artist_notebook, self.figure)
        self.artist_notebook.add(self.styletab_figure, sticky=tk.N + tk.E + tk.S + tk.W, text="Figure")
        self.artist_notebook.add(self.styletab_axes, sticky=tk.N + tk.E + tk.S + tk.W, text="Axes")
        self.artist_notebook.add(self.styletab_primitives, sticky=tk.N + tk.E + tk.S + tk.W, text="Primitives")

        # Lay it out
        self.artist_notebook.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        logging.debug("createWidgets creating options for master window")
        self.master.wm_title(self._WINDOW_TITLE)
        self.master.wm_minsize(width=1024, height=640)
        self.master.wm_iconbitmap()
        self.pack()

    def bindWidgetVariables(self):
        self.mpl_global_style.trace("w", self.styleChange)

    def bindWidgetEvents(self):
        pass

    def __init__(self, master=None):
        ttk.Frame.__init__(self, master, class_="matplotstylist")
        plt.ion()
        self.loadOptions()
        self.applyOptions()
        StylistTheme.configure()

        self.x = arange(0.0, pi, 0.01)
        self.y = sin(2 * pi * self.x)

        self.createWidgets()
        self.bindWidgetVariables()
        self.bindWidgetEvents()
        # TODO: can we change any master level features such as title and author for this frame

    @staticmethod
    def launch(style=None):
        logging.debug("%s launch invoked with style %s" % (repr(StylistTkinter), repr(style)))
        global app
        ttk.Style().theme_use(style)
        app = StylistTkinter()
        app.mainloop()
        try:
            app.destroy()
        except tk.TclError as terr:
            if not terr.message == 'can\'t invoke "destroy" command:  application has been destroyed':
                logging.error(repr(terr))
            else:
                logging.debug(terr.message)
Ejemplo n.º 23
0
class Plotter(IOTABasePanel):
    ''' Class with function to plot various PRIME charts (includes Table 1) '''
    def __init__(self,
                 parent,
                 info,
                 output_dir=None,
                 anomalous_flag=False,
                 *args,
                 **kwargs):
        IOTABasePanel.__init__(self, parent=parent, *args, **kwargs)
        self.target_anomalous_flag = anomalous_flag
        self.info = info
        self.output_dir = output_dir

    def initialize_figure(self, figsize=(8, 8)):
        self.figure = Figure(figsize=figsize)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.main_sizer.Add(self.canvas, 1, flag=wx.EXPAND)

    def table_one(self):
        ''' Constructs Table 1 for GUI or logging '''

        A = u'\N{ANGSTROM SIGN}'
        d = u'\N{DEGREE SIGN}'
        a = u'\N{GREEK SMALL LETTER ALPHA}'
        b = u'\N{GREEK SMALL LETTER BETA}'
        g = u'\N{GREEK SMALL LETTER GAMMA}'
        s = u'\N{GREEK SMALL LETTER SIGMA}'
        h = u'\u00BD'

        uc_edges = '{:4.2f}, {:4.2f}, {:4.2f}'.format(self.info['mean_a'][-1],
                                                      self.info['mean_b'][-1],
                                                      self.info['mean_c'][-1])
        uc_angles = '{:4.2f}, {:4.2f}, {:4.2f}'.format(
            self.info['mean_alpha'][-1], self.info['mean_beta'][-1],
            self.info['mean_gamma'][-1])
        res_total = '{:4.2f} - {:4.2f}'.format(self.info['total_res_max'][-1],
                                               self.info['total_res_min'][-1])
        res_last_shell = '{:4.2f} - {:4.2f}' \
                         ''.format(self.info['binned_resolution'][-1][-2],
                                   self.info['binned_resolution'][-1][-1])
        t1_rlabels = [
            u.to_unicode(u'No. of accepted images'),
            u.to_unicode(u'No. of rejected images'),
            u.to_unicode(u'Space Group'),
            u.to_unicode(u'Cell dimensions'),
            u.to_unicode(u'  a, b, c ({})  '.format(A)),
            u.to_unicode(u'  {}, {}, {} ({})    '.format(a, b, g, d)),
            u.to_unicode(u'Resolution ({})  '.format(A)),
            u.to_unicode(u'Completeness (%)'),
            u.to_unicode(u'Multiplicity'),
            u.to_unicode(u'I / {}(I) '.format(s)),
            u.to_unicode(u'CC{} '.format(h)),
            u.to_unicode(u'R_merge')
        ]

        n_frames_bad = self.info['n_frames_bad_cc'][-1]      + \
                       self.info['n_frames_bad_G'][-1]       + \
                       self.info['n_frames_bad_uc'][-1]      + \
                       self.info['n_frames_bad_gamma_e'][-1] + \
                       self.info['n_frames_bad_SE'][-1]
        t1_data = [
            ['{}'.format(self.info['n_frames_good'][-1])],
            ['{}'.format(n_frames_bad)],
            ['{}'.format(self.info['space_group_info'][-1])], [''],
            ['{}'.format(uc_edges)], ['{}'.format(uc_angles)],
            ['{} ({})'.format(res_total, res_last_shell)],
            [
                '{:4.2f} ({:4.2f})'.format(
                    self.info['total_completeness'][-1],
                    self.info['binned_completeness'][-1][-1])
            ],
            [
                '{:4.2f} ({:4.2f})'.format(self.info['total_n_obs'][-1],
                                           self.info['binned_n_obs'][-1][-1])
            ],
            [
                '{:4.2f} ({:4.2f})'.format(
                    self.info['total_i_o_sigi'][-1],
                    self.info['binned_i_o_sigi'][-1][-1])
            ],
            [
                '{:4.2f} ({:4.2f})'.format(
                    self.info['total_cc12'][-1],
                    self.info['binned_cc12'][-1][-1] * 100)
            ],
            [
                '{:4.2f} ({:4.2f})'.format(self.info['total_rmerge'][-1],
                                           self.info['binned_rmerge'][-1][-1])
            ]
        ]

        return t1_rlabels, t1_data

    def stat_charts(self):
        ''' Displays charts of CC1/2, Completeness, Multiplicity and I / sig(I)
        per resolution bin after the final cycle of post-refinement '''

        gsp = gridspec.GridSpec(2, 2)

        self.figure.set_alpha(0)
        rc('font', family='sans-serif', size=12)
        rc('mathtext', default='regular')

        x = self.info['binned_resolution'][-1]
        bins = np.arange(len(x))
        xlabels = ["{:.2f}".format(i) for i in x]
        sel_bins = bins[0::len(bins) // 6]
        sel_xlabels = [xlabels[t] for t in sel_bins]

        # Plot CC1/2 vs. resolution
        ax_cc12 = self.figure.add_subplot(gsp[0])
        reslabel = 'Resolution ({})'.format(r'$\AA$')
        ax_cc12.set_xlabel(reslabel, fontsize=15)
        ax_cc12.ticklabel_format(axis='y', style='plain')
        ax_cc12.set_ylim(0, 100)

        if self.target_anomalous_flag:
            ax_cc12.set_ylabel(r'$CC_{1/2}$ anom (%)', fontsize=15)
        else:
            ax_cc12.set_ylabel(r'$CC_{1/2}$ (%)', fontsize=15)
        ax_cc12.set_xticks(sel_bins)
        ax_cc12.set_xticklabels(sel_xlabels)
        ax_cc12.grid(True)
        cc12_start_percent = [c * 100 for c in self.info['binned_cc12'][0]]
        cc12_end_percent = [c * 100 for c in self.info['binned_cc12'][-1]]
        start, = ax_cc12.plot(bins, cc12_start_percent, c='#7fcdbb', lw=2)
        end, = ax_cc12.plot(bins, cc12_end_percent, c='#2c7fb8', lw=3)
        labels = ['Initial', 'Final']
        ax_cc12.legend([start, end],
                       labels,
                       loc='lower left',
                       fontsize=9,
                       fancybox=True)

        # Plot Completeness vs. resolution
        ax_comp = self.figure.add_subplot(gsp[1])
        ax_comp.set_xlabel(reslabel, fontsize=15)
        ax_comp.ticklabel_format(axis='y', style='plain')
        ax_comp.set_ylabel('Completeness (%)', fontsize=15)
        ax_comp.set_xticks(sel_bins)
        ax_comp.set_xticklabels(sel_xlabels)
        ax_comp.set_ylim(0, 100)
        ax_comp.grid(True)
        start, = ax_comp.plot(bins,
                              self.info['binned_completeness'][0],
                              c='#7fcdbb',
                              lw=2)
        end, = ax_comp.plot(bins,
                            self.info['binned_completeness'][-1],
                            c='#2c7fb8',
                            lw=3)
        labels = ['Initial', 'Final']
        ax_comp.legend([start, end],
                       labels,
                       loc='lower left',
                       fontsize=9,
                       fancybox=True)

        # Plot Multiplicity (no. of observations) vs. resolution
        ax_mult = self.figure.add_subplot(gsp[2])
        ax_mult.set_xlabel(reslabel, fontsize=15)
        ax_mult.ticklabel_format(axis='y', style='plain')
        ax_mult.set_ylabel('# of Observations', fontsize=15)
        ax_mult.set_xticks(sel_bins)
        ax_mult.set_xticklabels(sel_xlabels)
        ax_mult.grid(True)
        start, = ax_mult.plot(bins,
                              self.info['binned_n_obs'][0],
                              c='#7fcdbb',
                              lw=2)
        end, = ax_mult.plot(bins,
                            self.info['binned_n_obs'][-1],
                            c='#2c7fb8',
                            lw=3)
        labels = ['Initial', 'Final']
        ax_mult.legend([start, end],
                       labels,
                       loc='lower left',
                       fontsize=9,
                       fancybox=True)

        # Plot I / sig(I) vs. resolution
        ax_i_sigi = self.figure.add_subplot(gsp[3])
        ax_i_sigi.set_xlabel(reslabel, fontsize=15)
        ax_i_sigi.ticklabel_format(axis='y', style='plain')
        ax_i_sigi.set_ylabel(r'I / $\sigma$(I)', fontsize=15)
        ax_i_sigi.set_xticks(sel_bins)
        ax_i_sigi.set_xticklabels(sel_xlabels)
        ax_i_sigi.grid(True)
        start, = ax_i_sigi.plot(bins,
                                self.info['binned_i_o_sigi'][0],
                                c='#7fcdbb',
                                lw=2)
        end, = ax_i_sigi.plot(bins,
                              self.info['binned_i_o_sigi'][-1],
                              c='#2c7fb8',
                              lw=3)
        labels = ['Initial', 'Final']
        ax_i_sigi.legend([start, end],
                         labels,
                         loc='lower left',
                         fontsize=9,
                         fancybox=True)

        self.figure.set_tight_layout(True)
Ejemplo n.º 24
0
class ResidualPlot(FigureCanvas):

    __instance = None

    def __init__(self):
        Global.event.task_selected.connect(self._on_task_selected)
        Global.event.plot_x_limit_changed.connect(self._on_x_limit_changed)
        Global.event.task_deleted.connect(self._on_task_deleted)
        Global.event.tasks_list_updated.connect(self._on_tasks_list_updated)

        self.task = None
        self.axes = None
        self.last_x_limit = []
        self.chi2s = []
        bg_color = str(QPalette().color(QPalette.Active, QPalette.Window).name())
        rcParams.update({'font.size': 10})

        self.figure = Figure(facecolor=bg_color, edgecolor=bg_color)
        self.figure.hold(False)
        super(ResidualPlot, self).__init__(self.figure)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.updateGeometry()
        self.hide()

    def _on_task_selected(self, task):
        self.set_task(task)
        self.redraw()

    def _on_task_deleted(self, task):
        if self.task == task:
            self.set_task(None)
            self.clear()

    def _on_tasks_list_updated(self):
        if not len(Global.tasks()):
            self.set_task(None)
            self.clear()

    def set_task(self, task):
        self.task = task

    def clear(self):
        self.figure.clf()
        self.figure.clear()
        self.draw()
        self.parent().chi2_label.hide()
        self.parent().chi2_value.hide()
        self.hide()
        gc.collect()

    def redraw(self):
        self.clear()

        if self.task.result.chi2 is None:
            self.parent().chi2_label.hide()
            self.parent().chi2_value.hide()
            self.hide()
            return

        self.chi2s.append(self.task.result.chi2)

        self.show()
        self.parent().chi2_label.show()
        self.parent().chi2_value.show()

        self.axes = self.figure.add_subplot(1, 1, 1)
        self.axes.grid(False)
        self.figure.set_alpha(0)
        self.axes.set_xlabel('Phase')
        self.axes.set_ylabel('Residual')

        phases = []
        delta_values = []

        keys = sorted(self.task.result.data().keys())

        for key in keys:
            if self.task.result.data()[key]['delta_value'] is not None:
                phases.append(key)
                delta_values.append(self.task.result.data()[key]['delta_value'])


        y_max = max(abs(min(delta_values)), abs(max(delta_values)))
        y_pad = (y_max / 100) * 10

        self.axes.set_autoscaley_on(False)
        self.axes.set_ylim([-(y_max + y_pad), y_max + y_pad])

        self.axes.set_autoscalex_on(False)
        self.axes.set_xlim(self.last_x_limit)

        color = QColor(0,0,0)
        min_chi2 = min(self.chi2s)
        if len(self.chi2s) == 1 :
            color = QColor(0,0,0)
        elif self.task.result.chi2 <= min_chi2 :
            color = QColor(0,139,0)
        else:
            color = QColor(255,0,0)

        self.axes.axhline(y=0, ls='--', linewidth=0.5, color='black')
        self.axes.scatter(phases, delta_values, s=0.5, color='r')

        palette = self.parent().chi2_value.palette()
        palette.setColor(QPalette.Active, QPalette.Text, color)
        self.parent().chi2_value.setPalette(palette)
        self.parent().chi2_value.setText(str(self.task.result.chi2))

        self.draw()

    def _on_x_limit_changed(self, limit):
        self.last_x_limit = limit
Ejemplo n.º 25
0
def quiver_response(lon,
                    lat,
                    dx,
                    dy,
                    request,
                    unit_vectors=False,
                    dpi=80):
    
    from django.http import HttpResponse

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)
    width, height = wms_handler.get_width_height(request)
    
    colormap = wms_handler.get_colormap(request)

    climits = wms_handler.get_climits(request)

    cmax = 1.
    cmin = 0.
    
    if len(climits) == 2:
        cmin, cmax = climits
    else:
        logger.debug("No climits, default cmax to 1.0")

    # cmax = 10.

    #proj = get_pyproj(request)
    #x, y = proj(lon, lat)
    CRS = get_pyproj(request)
    x, y = pyproj.transform(EPSG4326, CRS, lon, lat) #TODO order for non-inverse?
    #logger.info("x, y: {0} {1}".format(x, y))
    
    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()
    
    
    
    #scale to cmin - cmax
    # dx = cmin + dx*(cmax-cmin)
    # dy = cmin + dy*(cmax-cmin)
    mags = np.sqrt(dx**2 + dy**2)
    # mags[mags>cmax] = cmax
    mags[mags>cmax] = cmax
    mags[mags<cmin] = cmin

    import matplotlib as mpl
    cmap = mpl.cm.get_cmap(colormap)
    bounds = np.linspace(cmin, cmax, 15)
    norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

    #plot unit vectors
    if unit_vectors:
        ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=colormap)
    else:
        ax.quiver(x, y, dx, dy, mags, cmap=cmap, norm=norm)
        #ax.quiver(x, y, dx/mags, dy/mags, mags, cmap=colormap,norm=norm)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response
Ejemplo n.º 26
0
def tricontourf_response(triang_subset,
                         data,
                         request,
                         dpi=80.0,
                         nlvls = 15):
    """
    triang_subset is a matplotlib.Tri object in lat/lon units (will be converted to projected coordinates)
    xmin, ymin, xmax, ymax is the bounding pox of the plot in PROJETED COORDINATES!!!
    request is the original getMap request object
    """
    from django.http import HttpResponse

    xmin, ymin, xmax, ymax = wms_handler.get_bbox(request)
    width, height = wms_handler.get_width_height(request)
    
    colormap = wms_handler.get_colormap(request)
    
    cmin, cmax = wms_handler.get_climits(request)
    #logger.info('cmin/cmax: {0} {1}'.format(cmin, cmax))

    # TODO: check this?
    try:
        data[data>cmax] = cmax
        data[data<cmin] = cmin
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        logger.warning("tricontourf_response error: " + repr(traceback.format_exception(exc_type, exc_value, exc_traceback)))
    
    clvls = wms_handler.get_clvls(request)

    #proj = get_pyproj(request)
    #triang_subset.x, triang_subset.y = proj(triang_subset.x, triang_subset.y)
    CRS = get_pyproj(request)
    triang_subset.x, triang_subset.y = pyproj.transform(EPSG4326, CRS, triang_subset.x, triang_subset.y) #TODO order for non-inverse?
    #logger.info('TRANSFORMED triang_subset.x: {0}'.format(triang_subset.x))
    #logger.info('TRANSFORMED triang_subset.y: {0}'.format(triang_subset.y))

    fig = Figure(dpi=dpi, facecolor='none', edgecolor='none')
    fig.set_alpha(0)
    fig.set_figheight(height/dpi)
    fig.set_figwidth(width/dpi)

    ax = fig.add_axes([0., 0., 1., 1.], xticks=[], yticks=[])
    ax.set_axis_off()

    lvls = np.linspace(float(cmin), float(cmax), int(clvls))
    #logger.info('trang.shape: {0}'.format(triang_subset.x.shape))
    #logger.info('data.shape: {0}'.format(data.shape))
    ax.tricontourf(triang_subset, data, levels = lvls, cmap=colormap)

    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    ax.set_frame_on(False)
    ax.set_clip_on(False)
    ax.set_position([0., 0., 1., 1.])

    #plt.axis('off')

    canvas = FigureCanvasAgg(fig)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    return response