def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

    degrees = list()
    diameters = list()
    velocities = list()
    for f in files:
        fin = open(options['outdir']+'/'+f, 'r')
        ts = -1
        for line in fin:
            if line.startswith('#'):
                continue
            time, degree, diameter, velocity = [t.strip() for t in line.split(',')]
            time = int(time)
            assert(ts == time-1)
            ts = time
            try:
                degrees[time].append(float(degree))
                diameters[time].append(int(diameter))
                velocities[time].append(float(velocity))
            except IndexError:
                degrees.append([float(degree)])
                diameters.append([int(diameter)])
                velocities.append([float(velocity)])

    polies = list()
    times = range(len(degrees))
    times2 = times + times[::-1]

    degrees_conf_upper = [confidence(d)[0] for d in degrees]
    degrees_conf_lower = [confidence(d)[1] for d in degrees]
    polies.append(conf2poly(times, degrees_conf_upper, degrees_conf_lower, color='blue'))

    diameters_conf_upper = [confidence(d)[0] for d in diameters]
    diameters_conf_lower = [confidence(d)[1] for d in diameters]
    polies.append(conf2poly(times, diameters_conf_upper, diameters_conf_lower, color='blue'))

    velocities_conf_upper = [confidence(d)[0] for d in velocities]
    velocities_conf_lower = [confidence(d)[1] for d in velocities]
    polies.append(conf2poly(times, velocities_conf_upper, velocities_conf_lower, color='green'))

    velocities = [scipy.mean(d) for d in velocities]
    diameters = [scipy.mean(d) for d in diameters]
    degrees = [scipy.mean(d) for d in degrees]

    fig = MyFig(options, figsize=(10, 8), xlabel='Time [s]', ylabel='Metric', grid=False, legend=True, aspect='auto', legend_pos='upper right')

    patch_collection = PatchCollection(polies, match_original=True)
    patch_collection.set_alpha(0.3)
    patch_collection.set_linestyle('dashed')
    fig.ax.add_collection(patch_collection)

    fig.ax.plot(times, degrees, label='Mean degree', color='blue')
    fig.ax.plot(times, diameters, label='Diameter', color='red')
    fig.ax.plot(times, velocities, label='Mean velocity $[m/s]$', color='green')

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max+10)
    fig.save('metrics', fileformat='pdf')
Esempio n. 2
0
File: gfx.py Progetto: caosuomo/rads
def show_boxes(boxes,S=None,col='b',ecol='k',alpha=1, fig=None):
	if boxes.dim != 2:
		raise Exception("show_boxes: dimension must be 2")
	if S is None:
		S = range(boxes.size)

	patches = []
	for i in S:
		art = mpatches.Rectangle(boxes.corners[i],boxes.widths[i][0],boxes.widths[i][1])
		patches.append(art)
        
	if fig is not None:
		ax = fig.gca()
	else:
                fig = plt.figure()
		ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	collection.set_alpha(alpha)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	#plt.show()
        plt.draw()
        return fig
Esempio n. 3
0
	def draw(self, ax, colour='k', alpha=1., linestyle='-', linewidth=1., 
		markers=None, facecolor='none', dashes=(1, 1), zorder=0):
		"""
		Draw the polygon on ax
		"""
		# Add the last point
		ptstoplot = self.verts.tolist()
		ptstoplot.append(ptstoplot[0])
		ptstoplot = np.array(ptstoplot)
		if facecolor == 'none':
			try:
				if linestyle == '--':
					ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha,
						ls=linestyle, dashes=dashes, lw=linewidth, marker=markers, zorder=zorder)
				else:
					ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha,
						ls=linestyle, lw=linewidth, marker=markers, zorder=zorder)
			except IndexError:
				pass
		else:
			patches = []
			filled_pol = mp.Polygon(self.verts)
			patches.append(filled_pol)
			collection = PatchCollection(patches, facecolors=facecolor)
			ax.add_collection(collection)
			collection.set_alpha(alpha)
			collection.set_edgecolor(colour)
			collection.set_linewidth(linewidth)
			collection.set_linestyle(linestyle)
Esempio n. 4
0
def create_pixels(lons,lats,widths,heights,alphas,color,label):
	"""
	Plot of pixels using centers (lons,lats), with sizes (widhts,heights), angle alphas, and color color.

	:param lons: array of longitude coordinates at the center of the pixels
	:param lats: array of latitude coordinates at the center of the pixels
	:param widths: array of widhts of the pixels
	:param heights: array of heights of the pixels
	:param alphas: array of angles of the pixels
	:param color: tuple with RGB color values
	:return col: collection of rectangles with the pixels

	Developed in Python 2.7.15 :: Anaconda 4.5.10, on MACINTOSH.
	Angel Farguell ([email protected]) 2018-12-28
	"""

	# Create pixels
	pixels=[]
	for x, y, h, w, a in zip(lons, lats, heights, widths, alphas):
		xpos = x - w/2 # The x position will be half the width from the center
		ypos = y - h/2 # same for the y position, but with height
		rect = Rectangle( (xpos, ypos), w, h, a) # Create a rectangle
		pixels.append(rect) # Add the rectangle patch to our list

	# Create a collection from the rectangles
	col = PatchCollection(pixels)
	# set the alpha for all rectangles
	col.set_alpha(0.5)
	# Set the colors using the colormap
	col.set_facecolor( [color]*len(lons) )
	# No lines
	col.set_linewidth( 0 )

	return col
def hatching(ax,
             lat,
             lon,
             condition,
             hatch='/////',
             force=False,
             wrap_lon=False):
    """Adds a hatching layer to an axis object.

    Parameters
    ----------
    ax : matplotlib.pyplot.axis object
    lat : sequence of float, shape (M,)
    lon : sequence of float, shape (N,)
    condition : sequence of bool, shape (M, N)
        Hatching will be drawn where condition is True.
    hatch : valid hatch string
        Note that multiple equivalent characters will lead to a finer hatching.
    force : bool, optional
        If True also work with unevenly spaced lat and lon. This might lead to
        unexpected behavior if the gird is too uneven.
    wrap_lon : bool, optional
        Wrap longitude to [-180, 180).

    Returns
    -------
    None"""
    if isinstance(lat, xr.core.dataarray.DataArray):
        lat = lat.data
    if isinstance(lon, xr.core.dataarray.DataArray):
        lon = lon.data

    dlat = np.unique(lat[1:] - lat[:-1])
    dlon = np.unique(lon[1:] - lon[:-1])

    if force:
        dlat = [np.mean(dlat)]
        dlon = [np.mean(dlon)]

    assert len(dlat) == 1, 'must be evenly spaced'
    assert len(dlon) == 1, 'must be evenly spaced'
    dxx = dlon[0] / 2
    dyy = dlat[0] / 2
    assert np.shape(condition) == (len(lat), len(lon))
    ii, jj = np.where(condition)
    lat_sel = lat[ii]
    lon_sel = lon[jj]

    if wrap_lon:
        lon_sel = [ll if ll < 180 else ll - 360 for ll in lon_sel]

    patches = [
        Polygon([[xx - dxx, yy + dyy], [xx - dxx, yy - dyy],
                 [xx + dxx, yy - dyy], [xx + dxx, yy + dyy]])
        for xx, yy in zip(lon_sel, lat_sel)
    ]
    pp = PatchCollection(patches)
    pp.set_alpha(0.)
    pp.set_hatch(hatch)
    ax.add_collection(pp)
Esempio n. 6
0
def _plot_eqks(axes, csda):
    """
    :parameter axes:
    :parameter csda:
    """

    if csda.ecat is None:
        return

    newcat = csda.ecat

    olo = csda.csec.olo
    ola = csda.csec.ola
    dsts = geodetic_distance(olo, ola,
                             newcat.data['longitude'],
                             newcat.data['latitude'])
    # MN: 'sze' assigned but never used
    sze = (newcat.data['magnitude'])**0.5
    patches = []
    for dst, dep, mag in zip(dsts,
                             newcat.data['depth'],
                             newcat.data['magnitude']):
        circle = Circle((dst, dep), (mag*0.5)**1.5, ec='white')
        patches.append(circle)
    colors = newcat.data['magnitude']
    p = PatchCollection(patches, zorder=6, edgecolors='white')
    p.set_alpha(0.5)
    p.set_array(numpy.array(colors))
    axes.add_collection(p)
Esempio n. 7
0
def draw_map(ratings_data, title, save_name):
  fig = plt.figure(figsize=(16,9))
  fig.suptitle(title, fontsize=20, y=.90)
  ax = fig.add_subplot(111, facecolor='w', frame_on=False)
  m = Basemap(lon_0=0, projection='robin')
  m.drawmapboundary(color='w')
  m.readshapefile(shapefile, 'units', color='#888888', linewidth=.2)

  for info, shape in zip(m.units_info, m.units):
    country = info["NAME"]
    if country not in ratings_data:
      color = inactive_color
    else:
      color = active_color
      try:
        non_visited_country.remove(country)
      except:
        pass

    pc = PatchCollection([Polygon(np.array(shape), True)])
    pc.set_facecolor(color)
    if country in ratings_data:
      pc.set_alpha((ratings_data[country]+rating_shift) / (max_rating+rating_shift))
    ax.add_collection(pc)

  ax.axhspan(0, 1000 * 1800, facecolor='w', edgecolor='w', zorder=2)

  ax_legend = fig.add_axes([0.35, 0.14, 0.3, 0.03], zorder=3)
  index  = [0.0, 1.0]
  cm = LinearSegmentedColormap.from_list('ramen_colormap', zip(index, colors))
  cb = mpl.colorbar.ColorbarBase(ax_legend, cmap=cm, ticks=[0, 1], orientation='horizontal')
  cb.ax.set_xticklabels(["3/5 Stars", "5/5 Stars"])

  plt.savefig("output/%s.png" % save_name, bbox_inches='tight', pad_inches=.2)
Esempio n. 8
0
def _plot_volc(axes, csda):
    """
    :parameter axes:
    :parameter csda:
    """
    if csda.volc is None:
        return

    olo = csda.csec.olo
    ola = csda.csec.ola
    patches = []

    if (len(csda.volc)-1) >= 1:
        vuls = geodetic_distance(olo, ola,
                                 csda.volc[:, 0],
                                 csda.volc[:, 1])
        for v in vuls:
            square = Rectangle((v, -10.0), 7, 12)
            patches.append(square)

    else:
        vuls = geodetic_distance(olo, ola,
                                 csda.volc[0],
                                 csda.volc[1])
        square = Rectangle((vuls, -10.0), 7, 12)
        patches.append(square)

    vv = PatchCollection(patches, zorder=6, color='red', edgecolors='red')
    vv.set_alpha(0.85)
    axes.add_collection(vv)
Esempio n. 9
0
def showGrid(domain, grid, filename, numbers=False, domainColor=False):
    fig, ax = plt.subplots()
    plt.xlim(0.15, 0.85)
    plt.ylim(0.15, 0.65)
    maxGeneration = max(cell.generation for cell in grid.cells if cell.generation is not None)
    n = 5
    getColor = lambda generation: plt.get_cmap("hsv")((generation-n)/(maxGeneration-n))
    print([getColor(i) for i in range(10)])
    patchesPerDomain = [[] for i in range(100)]
    plt.axis("off")
    for cell in grid.cells:
        patchesPerDomain[cell.domain].append(Polygon(cell.vertices))
        # for (v1, v2) in zip(cell.vertices, cell.vertices[1:] + [cell.vertices[0]]):
        #     drawLine(v1, v2, color=getColor(cell))
        if numbers:
            plt.text(cell.pos[0]+0.007, cell.pos[1], str(cell.generation), fontsize=15, horizontalalignment="center", verticalalignment="center")
        for successor in cell.successors:
            p1 = intermediatePoint(cell.pos, successor.pos, False)
            p2 = intermediatePoint(cell.pos, successor.pos, True)
            drawArrow(p1, p2, color=getColor(successor.generation))
    for (i, patchList) in enumerate(patchesPerDomain):
        patches = PatchCollection(patchList)
        if domainColor:
            patches.set_color(getDomainColor(i))
            patches.set_alpha(0.5)
        else:
            patches.set_color(getDomainColor(1))
            patches.set_alpha(0.5)
        ax.add_collection(patches)
    plt.savefig(filename, bbox_inches="tight", dpi=400)
Esempio n. 10
0
def data2fig(data, X, options, legend_title, xlabel, ylabel=r'Reachability~$\reachability$'):
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1, len(data.keys())))
    else:
        colors = options['color'](pylab.linspace(0, 1, len(data.keys())))
    fig = MyFig(options, figsize=(10, 8), xlabel=r'Sources~$\sources$', ylabel=ylabel, grid=False, aspect='auto', legend=True)
    for j, nhdp_ht in enumerate(sorted(data.keys())):
        d = data[nhdp_ht]
        try:
            mean_y = [scipy.mean(d[n]) for n in X]
        except KeyError:
            logging.warning('key \"%s\" not found, continuing...', nhdp_ht)
            continue
        confs_y = [confidence(d[n])[2] for n in X]
        poly = [conf2poly(X, list(numpy.array(mean_y)+numpy.array(confs_y)), list(numpy.array(mean_y)-numpy.array(confs_y)), color=colors[j])]
        patch_collection = PatchCollection(poly, match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)
        fig.ax.plot(X, mean_y, label='$%d$' % nhdp_ht, color=colors[j])
    fig.ax.set_xticks(X)
    fig.ax.set_xticklabels(['$%s$' % i for i in X])
    fig.ax.set_ylim(0,1)
    fig.legend_title = legend_title
    return fig
Esempio n. 11
0
def get_circles_for_scatter(x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
def plot_on_image(densitymap, image):
    """
    Plot the density grid as a collection of colored rectangles layered
    over the given fits image.

    Parameters
    ----------
    densitymap: DensityMap
        the density map instance

    image: imageHDU
        the fits image, which should include a WCS

    Returns
    -------
    image_fig: matplotlib Figure
        the figure on which the plot was made

    image_ax: matplotlib Axes
        the axes on which the imshow and the patches were applied

    patch_col: matplotlib PatchCollection
        the patch collection that was added to the axes to plot the
        rectangles representing the background map tiles
    """
    # plot the image
    image_wcs = wcs.WCS(image.header)
    image_fig = plt.figure()
    image_ax = image_fig.add_subplot(1, 1, 1, projection=image_wcs)
    # image_ax = plt.subplot(1, 1, 1, projection=wcs.WCS(image))
    imdata = image.data.astype(float)
    vmin = np.percentile(imdata, 16)
    vmax = np.percentile(imdata, 99)
    plt.imshow(imdata,
               cmap="gray_r",
               interpolation="mitchell",
               vmin=vmin,
               vmax=vmax)

    # Make a rectangular patch for each tile of the map
    rectangles = []
    for row in densitymap.tile_data:
        ll = row["min_ra"]  # left
        r = row["max_ra"]  # right
        b = row["min_dec"]  # bottom
        t = row["max_dec"]  # top
        ra_dec_corners = np.array([[ll, b], [r, b], [r, t], [ll, t]])
        pix_corners = image_wcs.wcs_world2pix(ra_dec_corners, 0)
        rec = Polygon(pix_corners, closed=True)
        rectangles.append(rec)

    # This will give each tile a color according to the given values.
    # Some of the plt.scatter functionality works with PatchCollection
    # under the hood, apparently.
    patch_col = PatchCollection(rectangles, cmap="viridis")
    patch_col.set_alpha(0.3)
    patch_col.set_array(densitymap.tile_vals())
    image_ax.add_collection(patch_col)
    return image_fig, image_ax, patch_col
Esempio n. 13
0
def plot_shapefile_polys(shapefile, ax, m, cmap):
    """
    Plot polygons from the given shapefile on a basemap.

    Parameters
    ----------
    shapefile : shapefile object
        Shapefile opened with fiona (``fiona.open(path_to_shapefile)``)
    ax : matplotlib ax object
        Axes to plot on
    m : basemap object
    cmap : matplotlib colormap
        Colormap to use to color the individual polygons in the shapefile

    """
    from descartes import PolygonPatch
    from matplotlib.collections import PatchCollection
    import shapely
    import shapely.ops

    # Break up MultiPolygons into Polygons, keeping track of
    # which shape they belong to
    polygons = []
    names = []
    for i in shapefile:
        # name = i['properties'][name_property]
        name = i['id']
        geom = shapely.geometry.shape(i['geometry'])
        if geom.geom_type == 'MultiPolygon':
            for poly in geom:
                polygons.append(poly)
                names.append(name)
        else:
            polygons.append(geom)
            names.append(name)

    # Create patches with basemap-transformed coordinates
    def TransformedPolygonPatch(poly):
        return PolygonPatch(shapely.ops.transform(m, poly),
                            ec='#555555',
                            lw=.2,
                            alpha=1.,
                            zorder=4)

    polygon_patches = [TransformedPolygonPatch(p) for p in polygons]

    # Create name->color_id mapping dict
    colors = {name: idx for idx, name in enumerate(list(set(names)))}
    n = plt.Normalize(0, len(colors))

    pc = PatchCollection(polygon_patches, match_original=True)
    # Now go through all names and set the color appropriately
    pc.set_facecolor(cmap(n([colors[i] for i in names])))
    pc.set_alpha(0.2)
    ax.add_collection(pc)

    return ax
Esempio n. 14
0
def plot_rectangles(fld, xp, yp, title = None, cntr_lat=None, cntr_lon=None, 
                    c_width=2500., ctables=None, norm=None, ax=None, fig=None):
               
    if ctables == None:
        ctables = P.cm.viridis
        
    if title == None:
        title = "No Title"

    if norm == None:
        norm = [fld.min(), fld.max()]
        
      
    Fnorm = mpl.colors.Normalize(vmin=norm[0], vmax=norm[1], clip=True)
    # Here's where you have to make a ScalarMappable with the colormap
    mappable = P.cm.ScalarMappable(norm=Fnorm, cmap=ctables)
    
    # normalize the data for the colormapping
    colors_norm = fld/(norm[1]-norm[0])
    
    # Give it your non-normalized color data
    mappable.set_array(fld)

    rects = []
    for p in zip(xp, yp):
        xpos = p[0] - c_width/2 # The x position will be half the width from the center
        ypos = p[1] - c_width/2 # same for the y position, but with height
        rect = Rectangle( (xpos, ypos), c_width, c_width ) # Create a rectangle
        rects.append(rect) # Add the rectangle patch to our list

    # Create a collection from the rectangles
    col = PatchCollection(rects)
    
    # set the alpha for all rectangles
    col.set_alpha(0.8)
    
    # Set the colors using the colormap
    col.set_facecolor( ctables(colors_norm) )
    
    # create figure if fig == None
    if fig == None:
        fig = plt.figure()
        
    if ax == None:
        ax = fig.add_subplot(111)

    # plot collection of rectangles
    ax.add_collection(col)    
    # add a colorbar
    P.colorbar(mappable)
    
    P.title(title, fontsize=10)

    return
Esempio n. 15
0
    def zoneLines(self, edgecolour='black'):        #was 'red'
        """
        Set boundary colour for defined ESRI shapes
        edgecolour -- HTML colour name for boundary
        """

        pc2 = PatchCollection(self.patches, match_original=True)
        pc2.set_facecolor('none')
        pc2.set_edgecolor(edgecolour)
        pc2.set_alpha(0.5) #5.0
        pc2.set_linewidth(0.5)
        pc2.set_zorder(25) # 500

        sq2 = self.ax.add_collection(pc2)
Esempio n. 16
0
    def _create_patch(self):
        """Creates a matplotlib polygon patch from the Shape points.
        This is used when making 2d images of the Shape object.

        :raises ValueError: No points defined for the Shape

        :return: a plotable polygon shape
        :rtype: Matplotlib object patch
        """

        if self.points is None:
            ValueError("No points defined for", self)

        patches = []
        xylist = []

        for x1, z1 in zip([row[0] for row in self.points],
                          [row[1] for row in self.points]):
            xylist.append([x1, z1])

        polygon = Polygon(xylist, closed=True)
        patches.append(polygon)

        p = PatchCollection(patches)

        if self.color is not None:
            p.set_facecolor(self.color)
            p.set_color(self.color)
            p.color = self.color
            p.edgecolor = self.color
            # checks to see if an alpha value is provided in the color
            if len(self.color) == 4:
                p.set_alpha = self.color[-1]
        self.patch = p
        return p
Esempio n. 17
0
    def _create_patch(self):
        """Creates a matplotlib polygon patch from the Shape points. This is
        used when making 2d images of the Shape object.

        Raises:
            ValueError: No points defined for the Shape

        Returns:
            Matplotlib object patch: a plotable polygon shape
        """

        if self.points is None:
            raise ValueError("No points defined for", self)

        patches = []
        xylist = []

        for point in self.points:
            xylist.append([point[0], point[1]])

        polygon = Polygon(xylist, closed=True)
        patches.append(polygon)

        patch = PatchCollection(patches)

        if self.color is not None:
            patch.set_facecolor(self.color)
            patch.set_color(self.color)
            patch.color = self.color
            patch.edgecolor = self.color
            # checks to see if an alpha value is provided in the color
            if len(self.color) == 4:
                patch.set_alpha = self.color[-1]
        self.patch = patch
        return patch
Esempio n. 18
0
 def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor):
     ell_patches = []
     for (x, y, a, c, d) in fpts:  # Manually Calculated sqrtm(inv(A))
         with catch_warnings():
             simplefilter("ignore")
             aIS = 1 / sqrt(a)
             cIS = (c / sqrt(a) - c / sqrt(d)) / (a - d + eps(1))
             dIS = 1 / sqrt(d)
         transEll = Affine2D([(aIS, 0, x), (cIS, dIS, y), (0, 0, 1)])
         unitCirc1 = Circle((0, 0), 1, transform=transEll)
         ell_patches = [unitCirc1] + ell_patches
     ellipse_collection = PatchCollection(ell_patches)
     ellipse_collection.set_facecolor("none")
     ellipse_collection.set_transform(T_data)
     ellipse_collection.set_alpha(alpha)
     ellipse_collection.set_edgecolor(edgecolor)
     return ellipse_collection
def plot_trajectory_ellipse(frame, varx="attr_VARX", vary="attr_VARY", covxy="attr_COVXY", opacity_factor=1):
    """
    Draw the trajectory and uncertainty ellipses around teach point.
    1) Scatter of points 
    2) Trajectory lines
    3) Ellipses 
    :param frame: Trajectory
    :param opacity_factor: all opacity values are multiplied by this. Useful when used to plot multiple Trajectories in
     an overlay plot.
    :return: axis
    """
    ellipses = []    
    segments = []
    start_point = None

    for i, pnt in frame.iterrows():  
        # The ellipse
        U, s, V = np.linalg.svd(np.array([[pnt[varx], pnt[covxy]], 
                                          [pnt[covxy], pnt[vary]]]), full_matrices=True)
        w, h = s**.5 
        theta = np.arctan(V[1][0]/V[0][0])   # == np.arccos(-V[0][0])              
        ellipse = {"xy":pnt[list(frame.geo_cols)].values, "width":w, "height":h, "angle":theta}
        ellipses.append(Ellipse(**ellipse))
        
        # The line segment
        x, y = pnt[list(frame.geo_cols)][:2]
        if start_point:           
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    ax = plt.gca()
    ellipses = PatchCollection(ellipses)
    ellipses.set_facecolor('none')
    ellipses.set_color("green")
    ellipses.set_linewidth(2)
    ellipses.set_alpha(.4*opacity_factor)
    ax.add_collection(ellipses)

    frame.plot(kind="scatter", x=frame.geo_cols[0], y=frame.geo_cols[1], marker=".", ax=plt.gca(), alpha=opacity_factor)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_linewidth(1)
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)
    return ax
Esempio n. 20
0
def get_ellipses_for_scatter(ax, x, y, color='black', edgecolor='none', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0):
    
    # get ellipse size to make it a circle given axes
    x0, y0 = ax.transAxes.transform((ax.get_ylim()[0],ax.get_xlim()[0]))
    x1, y1 = ax.transAxes.transform((ax.get_ylim()[1],ax.get_xlim()[1]))
    dx = x1-x0
    dy = y1-y0
    maxd = max(dx,dy)
    
    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    ellipses = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        width = r*2*maxd/dx
        height = r*2*maxd/dy
        ellipses[i] = patches.Ellipse( pt, width, height)

    # make a collection of those circles    
    cc = PatchCollection(ellipses, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)
    
    return cc
Esempio n. 21
0
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Probability $p_s$', ylabel=r'Reachability~$\reachability$', aspect='auto')
    fig_vs = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')

    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, 3))
    else:
        colors = fu_colormap()(pylab.linspace(0, 1.0, 3))
    nodes = 105

    axins = None
    if options['inset_loc'] >= 0:
        axins = zoomed_inset_axes(fig_vs.ax, options['inset_zoom'], loc=options['inset_loc'])
        axins.set_xlim(options['inset_xlim'])
        axins.set_ylim(options['inset_ylim'])
        axins.set_xticklabels([])
        axins.set_yticklabels([])
        mark_inset(fig_vs.ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")

    for i, (name, label) in enumerate(names):
        data = parse_site_only(options['datapath'][0], name)
        rs = numpy.array([r for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])
        fws = numpy.array([fw for p, r, std, conf, n, fw, fw_std, fw_conf in data if r <= options['limit']])/(nodes-1)
        ps = numpy.array([p for p, r, std, conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])
        yerr = numpy.array([conf for p,r,std,conf, n, fw, fw_std, fw_conf in data]) #[0:len(rs)])

        patch_collection = PatchCollection([conf2poly(ps, list(rs+yerr), list(rs-yerr), color=colors[i])], match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)

        fig.ax.plot(ps, rs, label=label, color=colors[i])
        fig_vs.ax.plot(fws, rs, label=label, color=colors[i])
        if axins:
            axins.plot(fws, rs, color=colors[i])

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0,1)
    fig_vs.ax.set_ylim(0,1)
    fig_vs.save('vs_pb')
Esempio n. 22
0
    def zoneColour(self, colours):
        """
        Set display colours for defined ESRI shapes
        colours -- list containing HTML colour names
        """

        self.colours = colours

        if not (isinstance(self.colours, list)):
            raise Exception('Invalid list of zone colours')

        pc = PatchCollection(self.patches, match_original=True)
        pc.set_facecolor(self.colours)
        pc.set_edgecolor('none')
        pc.set_alpha(0.5)
        pc.set_linewidth(0.5)
        pc.set_zorder(20)

        sq = self.ax.add_collection(pc)
Esempio n. 23
0
def show_boxes(boxes, S=None, col="b", ecol="k", alpha=1):
    if boxes.dim != 2:
        raise Exception("show_boxes: dimension must be 2")
    if S is None:
        S = range(boxes.size)

    patches = []
    for i in S:
        art = mpatches.Rectangle(boxes.corners[i], boxes.widths[i][0], boxes.widths[i][1])
        patches.append(art)

    ax = plt.gca()
    ax.hold(True)
    collection = PatchCollection(patches)
    collection.set_facecolor(col)
    collection.set_edgecolor(ecol)
    collection.set_alpha(alpha)
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    plt.show()
Esempio n. 24
0
 def _get_fpt_ell_collection(dm, fpts, T_data, alpha, edgecolor):
     ell_patches = []
     for (x,y,a,c,d) in fpts: # Manually Calculated sqrtm(inv(A))
         with catch_warnings():
             simplefilter("ignore")
             aIS = 1/sqrt(a)
             cIS = (c/sqrt(a) - c/sqrt(d))/(a - d + eps(1))
             dIS = 1/sqrt(d)
         transEll = Affine2D([\
                 ( aIS,   0,   x),\
                 ( cIS, dIS,   y),\
                 (   0,   0,   1)])
         unitCirc1 = Circle((0,0),1,transform=transEll)
         ell_patches = [unitCirc1] + ell_patches
     ellipse_collection = PatchCollection(ell_patches)
     ellipse_collection.set_facecolor('none')
     ellipse_collection.set_transform(T_data)
     ellipse_collection.set_alpha(alpha)
     ellipse_collection.set_edgecolor(edgecolor)
     return ellipse_collection
Esempio n. 25
0
def show_box(b, col="b", ecol="k", alpha=1):
    patches = []

    # lower left corner at b[0], followed by width and height
    xy = b[0]
    width = np.absolute(b[0, 1] - b[0, 0])
    height = np.absolute(b[1, 1] - b[1, 0])
    art = mpatches.Rectangle(xy, width, height)
    # art = mpatches.Rectangle(b[0],b[1,0],b[1,1])
    patches.append(art)

    ax = plt.gca()
    ax.hold(True)
    collection = PatchCollection(patches)
    collection.set_facecolor(col)
    collection.set_edgecolor(ecol)
    collection.set_alpha(alpha)
    ax.add_collection(collection, autolim=True)
    ax.autoscale_view()
    plt.show()
def plot_sparse_trajectory(trajectory, r=50, opacity_factor=1, plot_text=True,
                           num_col="segment_sparcify_n", min_static=100):
    """
    Plots a sparsified trajectory as circles with the number of points they represent as a number inside.
    :param trajectory: Trajectory object
    :param r: the radius of circles
    :param num_col: where to find the number to put in the circles
    :param min_static: minimum count to change color of circle
    :param plot_text: put the text with num of points in the circle?
    :return: ax
    """
    ax = plt.gca()
    trajectory.plot(kind="scatter", x=trajectory.geo_cols[0], y=trajectory.geo_cols[1], marker=".",
                    ax=plt.gca(), alpha=0.0*opacity_factor)

    circles = []
    segments = []
    start_point = None

    for i, pnt in trajectory.iterrows():
        circles.append(Circle(pnt[list(trajectory.geo_cols)].values, radius=r))

        if plot_text:
            plt.text(*pnt[list(trajectory.geo_cols)], s=str(int(pnt[num_col])), fontsize=12)

        x, y = pnt[list(trajectory.geo_cols)][:2]
        if start_point:
            segments.append([start_point, (x, y)])
        start_point = (x, y)

    circles = PatchCollection(circles)
    circles.set_facecolor(['none' if cnt < min_static else 'red' for cnt in trajectory[num_col].values])
    circles.set_alpha(.5*opacity_factor)
    ax.add_collection(circles)

    lines = LineCollection(segments)
    lines.set_color("gray")
    lines.set_alpha(.2*opacity_factor)
    ax.add_collection(lines)

    return ax
Esempio n. 27
0
def plot_fig_sens_analysis_obj_2D():
    """
	ERROR TO BE CORRECTED
	"""
    x_widget = widgets.FloatSlider(min=0.0, max=140.0, step=1, value=50)
    y_widget = widgets.FloatSlider(min=0.0, max=116.0, step=1, value=60)

    def printer(x, y):
        return

    interact(printer, x=x_widget, y=y_widget)

    def update_x_range(*args):
        x_widget.value = (7000 - y_widget.value * 50) / 60
        line.set_ydata((7000 - y_widget.value * x) / x_widget.value)
        fig.canvas.draw()

    y_widget.observe(update_x_range, 'value')

    x = np.linspace(0, 200)
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)

    line, = ax.plot(x, (60 * x - 7000) / 50)

    # Plot the solution space
    polygon = Polygon([[0, 0], [0, 80], [50, 60], [80, 0]], facecolor=None)
    p = PatchCollection([polygon])
    p.set_alpha(0.3)
    ax.add_collection(p)

    # Plot the constraint (1) 4X + 10Y = 800 #
    plt.plot([0, 200], [80, 0], color='g', label='4X + 10Y = 800', linewidth=2)

    # Plot the constraint (2) 4X + 2Y = 320
    plt.plot([0, 80], [160, 0], color='m', label='4X + 2Y = 320', linewidth=2)

    ax.set_xlim(0, 150)
    ax.set_ylim(0, 150)

    interact(update_x_range)
Esempio n. 28
0
File: gfx.py Progetto: caosuomo/rads
def show_box(b,col='b',ecol='k',alpha=1, fig=None):
	patches = []
	
	# lower left corner at b[0], followed by width and height
	art = mpatches.Rectangle(b[0],b[1,0],b[1,1])
	patches.append(art)

	if fig:
		ax = fig.gca()
	else:
                fig = plt.figure()
		ax = fig.gca()
	ax.hold(True)
	collection = PatchCollection(patches)
	collection.set_facecolor(col)
	collection.set_edgecolor(ecol)
	collection.set_alpha(alpha)
	ax.add_collection(collection,autolim=True)
	ax.autoscale_view()
	plt.show()

	return fig
Esempio n. 29
0
def scatter(ax, x, y, color='black', colormap='jet', radius=0.01, colornorm=None, alpha=1, radiusnorm=None, maxradius=1, minradius=0, edgecolors='none'): 
    # color can be array-like, or a matplotlib color 
    # I can't figure out how to control alpha through the individual circle patches.. it seems to get overwritten by the collection. low priority!

    cmap = plt.get_cmap(colormap)
    if colornorm is not None:
        colornorm = plt.Normalize(colornorm[0], colornorm[1], clip=True)
    
    # setup normalizing for radius scale factor (if used)
    if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
        if radiusnorm is None:
            radiusnorm = matplotlib.colors.Normalize(np.min(radius), np.max(radius), clip=True)
        else:
            radiusnorm = matplotlib.colors.Normalize(radiusnorm[0], radiusnorm[1], clip=True)

    # make circles
    points = np.array([x, y]).T
    circles = [None for i in range(len(x))]
    for i, pt in enumerate(points):    
        if type(radius) is list or type(radius) is np.array or type(radius) is np.ndarray:
            r = radiusnorm(radius[i])*(maxradius-minradius) + minradius
        else:
            r = radius
        circles[i] = patches.Circle( pt, radius=r )

    # make a collection of those circles    
    cc = PatchCollection(circles, cmap=cmap, norm=colornorm) # potentially useful option: match_original=True
    
    # set properties for collection
    cc.set_edgecolors(edgecolors)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        cc.set_array(color)
    else:
        cc.set_facecolors(color)
    cc.set_alpha(alpha)

    # add collection to axis    
    ax.add_collection(cc)  
Esempio n. 30
0
    def _create_patch(self):
        """Creates a matplotlib polygon patch from the Shape points. This is
        used when making 2d images of the Shape object.

        Raises:
            ValueError: No points defined for the Shape

        Returns:
            Matplotlib object patch: a plotable polygon shape
        """

        if self.points is None:
            raise ValueError("No points defined for", self)

        patches = []

        edges = facet_wire(wire=self.wire,
                           facet_splines=True,
                           facet_circles=True)

        fpoints = []
        for edge in edges:
            for vertice in edge.Vertices():
                fpoints.append((vertice.X, vertice.Z))

        polygon = Polygon(fpoints, closed=True)
        patches.append(polygon)

        patch = PatchCollection(patches)

        if self.color is not None:
            patch.set_facecolor(self.color)
            patch.set_color(self.color)
            patch.color = self.color
            patch.edgecolor = self.color
            # checks to see if an alpha value is provided in the color
            if len(self.color) == 4:
                patch.set_alpha = self.color[-1]
        self.patch = patch
        return patch
Esempio n. 31
0
def colorflood(gridobject, arr, **kwargs):
    """
    Method for color flooding an array for a Modflow grid.
    """

    #imports
    import matplotlib.cm as cm
    import matplotlib.colors as colors
    from matplotlib.patches import Polygon
    from matplotlib.collections import PatchCollection

    #set defaults from kwargs
    ax = matplotlib.pyplot.gca()
    arrexclude = []
    arrmin = arr.min()
    arrmax = arr.max()
    alpha = 1.0
    cb = False
    if kwargs.has_key('ax'): ax = kwargs['ax']
    if kwargs.has_key('arrexclude'): arrexclude = kwargs['arrexclude']
    if kwargs.has_key('arrmin'): arrmin = kwargs['arrmin']
    if kwargs.has_key('arrmax'): arrmax = kwargs['arrmax']
    if kwargs.has_key('alpha'): alpha = kwargs['alpha']
    if kwargs.has_key('cb'): cb = kwargs['cb'] #plot colorbar?

    norm = colors.normalize(arrmin, arrmax)
    patches = []
    for nodenumber in range(gridobject.nodes):
        nodeobj = gridobject.get_nodeobj(nodenumber)
        (k, i, j) = gridobject.get_indices(nodenumber)
        x, y = nodeobj.position[0], nodeobj.position[1]
        dx, dy = nodeobj.dxdydz[0], nodeobj.dxdydz[1]
        xmin = x - dx / 2.
        xmax = x + dx / 2.
        ymin = y - dy / 2.
        ymax = y + dy / 2.
        vertices = [ (xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)]
        if arr[k, i, j] in arrexclude:
            #cannot get visible and alpha to work, so this is the hack.
            vertices = [(0,0), (0,0), (0,0), (0,0) ]
        poly = Polygon(vertices, linewidth=0., fc = None, 
                       ec='none')
        patches.append(poly)

    #set up the patchcollection for faster coloring
    p = PatchCollection(patches, match_original=True)
    p.set_array(arr.reshape(-1))
    p.set_norm(norm)
    p.set_edgecolor(None)
    p.set_alpha(alpha)
    ax.add_collection(p)
    
    #create the colorbar
    if cb:
        pc = []
        color = cm.jet(norm(arrmin))
        poly = Polygon( ((0,0), (1,0), (1,1), (0,1)), linewidth=0., 
            fc = color, ec='none', alpha=0.4)
        pc.append(poly)
        color = cm.jet(norm(arrmax))
        poly = Polygon( ((0,0), (1,0), (1,1), (0,1)), linewidth=0., 
            fc = color, ec='none', alpha=0.4)
        pc.append(poly)
        p = PatchCollection(pc, match_original=True)
        p.set_array(numpy.array([arrmin, arrmax]))
        matplotlib.pyplot.colorbar(p, shrink=0.5)

    return    
Esempio n. 32
0
def plot_multiZ(prefix, minval=0, maxval=200, bluefree=702):

    fraclist = np.array([0.005, 0.02, 0.2, 0.4, 1, 2.5])
    rw = 0.5
    rh = 0.05

    minchi = np.inf
    for z in range(fraclist.size):

        stepfile = "{}_Z{:04}_steps.dat".format(prefix, int(fraclist[z] * 1000))
        blueChi = np.loadtxt(stepfile, usecols=(17,), unpack=True)
        blueChi *= bluefree
        if blueChi[-1] < minchi:
            minchi = blueChi[-1]

    fig = plt.figure()
    grid = ImageGrid(
        fig, 111, nrows_ncols=(1, 1), cbar_mode="each", cbar_location="top", cbar_pad="1%", axes_class=None
    )
    ax = grid[0]

    ax.set_xlabel("$Z/Z_{\odot}$")
    ax.set_ylabel("MLWA")
    for z in range(fraclist.size):

        stepfile = "{}_Z{:04}_steps.dat".format(prefix, int(fraclist[z] * 1000))
        MLWA, TAUV, Chi, blueChi = np.loadtxt(stepfile, usecols=(12, 13, 15, 17), unpack=True)
        blueChi *= bluefree

        #        good = np.where(blueChi < 80)
        #        blueChi = blueChi[good]
        #        MLWA = MLWA[good]
        blueChi -= minchi
        patches = []
        print np.log10(blueChi.min()), np.log10(blueChi.max())
        for i in range(MLWA.size):
            #            patches.append(Circle((z,MLWA[i]),radius=0.1,linewidth=0))
            width = rw * ((minchi + 5000) / (blueChi[i] + 5000))
            #            width = rw * (minchi/blueChi[i])
            patches.append(Rectangle((z - width / 2, MLWA[i] - rh / 2), width, rh))

        collection = PatchCollection(
            np.array(patches)[::-1],
            cmap=plt.get_cmap("gnuplot"),
            norm=matplotlib.colors.Normalize(vmin=minval, vmax=maxval),
        )
        collection.set_alpha(0.1)
        collection.set_linewidth(0.0)
        collection.set_array(np.log10(blueChi)[::-1])
        ax.add_collection(collection)

        #        ax.axhline(y=MLWA[-1],color='k',ls=':',alpha=0.6)
        ax.hlines(MLWA[-1], z - 0.5, z + 0.5, color="g", lw=2)
        ax.text(
            z + 0.5,
            MLWA[-1],
            "{:5.2f}%, {:4.1f}".format(100 - 100 * ss.chi2.cdf(blueChi[-1], bluefree + 5), blueChi[-1]),
        )

    collection.set_alpha(1.0)
    cbar = ax.cax.colorbar(collection)

    ci = [68.27, 50.0, 80.0, 40.0]
    dc = [4.72, 3.36, 5.99, 2.75]

    # for (c, d) in zip(ci, dc):
    #     ax.cax.axvline(x = np.log10(d), color='g')
    #     ax.cax.text(np.log10(d) - 0.03, 2, '{}'.format(c),
    #                 transform=ax.cax.transData,
    #                 fontsize=8)

    collection.set_alpha(0.1)
    cbar.set_label_text("Log( $\Delta\chi^2_{\mathrm{blue}}$ )")

    ax.set_xlim(-1, fraclist.size + 1)
    ax.set_ylim(0, 12)
    ax.set_xticks(np.arange(fraclist.size))
    ax.set_xticklabels(fraclist)
    fig.show()

    return fig
Esempio n. 33
0
         elif params[0] == 1:  # polygon
             params[1] = int(params[1])
             count = params[1]
             vecs = params[2:]
             x = vecs[::2]
             y = np.array(vecs[1::2])
             polygon = Polygon(np.array([x, y]).transpose(),
                               True,
                               color='gray')
             patches_polygon.append(polygon)
     pcc = PatchCollection(patches_circle, match_original=False)
     pcp = PatchCollection(patches_polygon, match_original=False)
     if args.collision_status:
         pcc.set_color('#85878b')
         pcp.set_color('#85878b')
         pcc.set_alpha(0.3)
         pcp.set_alpha(0.3)
         pcc.set_linestyle('dashed')
         pcp.set_linestyle('dashed')
         pcc.set_edgecolor('#73cdc9')
         pcp.set_edgecolor('#73cdc9')
         pcc.set_linewidth(0.4)
         pcp.set_linewidth(0.4)
         pcc.set_joinstyle('round')
         pcp.set_joinstyle('round')
     else:
         pcc.set_color('gray')
         pcp.set_color('gray')
     ax.add_collection(pcc)
     ax.add_collection(pcp)
 if args.safety_certificate:
def plot(trench, cat, cs_dict, interdistance):
    """
    :parameter trench:
        An instance of the :class:`Trench` class
    :parameter cat:
        An instance of the :class:`` class
    :parameter cs_dict:
        A <key,value> dictionary where the key is a section ID and the value is
        an instance of the :class:`CrossSection` class
    :parameter interdistance:
        Separation distance between cross-sections [km]
    """

    minlo = min(trench.axis[:, 0]) - 5
    minla = min(trench.axis[:, 1]) - 5
    maxlo = max(trench.axis[:, 0]) + 5
    maxla = max(trench.axis[:, 1]) + 5
    midlo = (minlo + maxlo) / 2
    midla = (minla + maxla) / 2

    # MN: 'fig' assigned but never used
    fig = plt.figure(figsize=(12, 9))

    #
    # Plot the basemap
    m = Basemap(llcrnrlon=minlo,
                llcrnrlat=minla,
                urcrnrlon=maxlo,
                urcrnrlat=maxla,
                resolution='i',
                projection='tmerc',
                lon_0=midlo,
                lat_0=midla)

    #
    # Draw paralleles and meridians with labels
    # labels = [left,right,top,bottom]
    m.drawcoastlines()
    m.drawmeridians(numpy.arange(
        numpy.floor(minlo / 10.) * 10,
        numpy.ceil(maxlo / 10.) * 10, 5.),
                    labels=[False, False, False, True])
    m.drawparallels(numpy.arange(
        numpy.floor(minla / 10.) * 10,
        numpy.ceil(maxla / 10.) * 10, 5.),
                    labels=[True, False, False, False])

    #
    # Plot the instrumental catalogue
    xa, ya = m(cat.data['longitude'], cat.data['latitude'])
    szea = (cat.data['magnitude'] * 100)**1.5
    patches = []
    for x, y, sze in zip(list(xa), list(ya), szea):
        circle = Circle((x, y), sze, ec='white')
        patches.append(circle)
    colors = cat.data['depth']
    p = PatchCollection(patches, zorder=6, edgecolors='white')
    p.set_alpha(0.5)
    p.set_clim([0, 200])
    p.set_array(numpy.array(colors))
    plt.gca().add_collection(p)
    plt.colorbar(p, fraction=0.02, pad=0.04, extend='max')

    #
    # Plot the traces of cross-sections
    ts = trench.resample(interdistance)

    x, y = m(trench.axis[:, 0], trench.axis[:, 1])
    plt.plot(x, y, '-g', linewidth=2, zorder=10)
    x, y = m(ts.axis[:, 0], ts.axis[:, 1])
    plt.plot(x, y, '--y', linewidth=4, zorder=20)

    for key in cs_dict:
        cs = cs_dict[key]
        if cs is not None:
            x, y = m(cs.plo, cs.pla)
            plt.plot(x, y, ':r', linewidth=2, zorder=20)
            text = plt.text(x[0],
                            y[0],
                            '%s' % key,
                            ha='center',
                            va='center',
                            size=10,
                            zorder=30)
            text = plt.text(x[-1],
                            y[-1],
                            '%s' % key,
                            ha='center',
                            va='center',
                            size=10,
                            zorder=30)
            text.set_path_effects(
                [PathEffects.withStroke(linewidth=3, foreground="w")])
    plt.show()
def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

    degrees = list()
    diameters = list()
    velocities = list()
    for f in files:
        fin = open(options['outdir'] + '/' + f, 'r')
        ts = -1
        for line in fin:
            if line.startswith('#'):
                continue
            time, degree, diameter, velocity = [
                t.strip() for t in line.split(',')
            ]
            time = int(time)
            assert (ts == time - 1)
            ts = time
            try:
                degrees[time].append(float(degree))
                diameters[time].append(int(diameter))
                velocities[time].append(float(velocity))
            except IndexError:
                degrees.append([float(degree)])
                diameters.append([int(diameter)])
                velocities.append([float(velocity)])

    polies = list()
    times = range(len(degrees))
    times2 = times + times[::-1]

    degrees_conf_upper = [confidence(d)[0] for d in degrees]
    degrees_conf_lower = [confidence(d)[1] for d in degrees]
    polies.append(
        conf2poly(times, degrees_conf_upper, degrees_conf_lower, color='blue'))

    diameters_conf_upper = [confidence(d)[0] for d in diameters]
    diameters_conf_lower = [confidence(d)[1] for d in diameters]
    polies.append(
        conf2poly(times,
                  diameters_conf_upper,
                  diameters_conf_lower,
                  color='blue'))

    velocities_conf_upper = [confidence(d)[0] for d in velocities]
    velocities_conf_lower = [confidence(d)[1] for d in velocities]
    polies.append(
        conf2poly(times,
                  velocities_conf_upper,
                  velocities_conf_lower,
                  color='green'))

    velocities = [scipy.mean(d) for d in velocities]
    diameters = [scipy.mean(d) for d in diameters]
    degrees = [scipy.mean(d) for d in degrees]

    fig = MyFig(options,
                figsize=(10, 8),
                xlabel='Time [s]',
                ylabel='Metric',
                grid=False,
                legend=True,
                aspect='auto',
                legend_pos='upper right')

    patch_collection = PatchCollection(polies, match_original=True)
    patch_collection.set_alpha(0.3)
    patch_collection.set_linestyle('dashed')
    fig.ax.add_collection(patch_collection)

    fig.ax.plot(times, degrees, label='Mean degree', color='blue')
    fig.ax.plot(times, diameters, label='Diameter', color='red')
    fig.ax.plot(times,
                velocities,
                label='Mean velocity $[m/s]$',
                color='green')

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max + 10)
    fig.save('metrics', fileformat='pdf')
Esempio n. 36
0
def plot_multifolder_old(folder_list, Zlist, pointing, ap):
    rw = 0.5
    rh = 0.1
    numfree = 1334 - 5 - 1

    minchi = np.inf
    maxchi = 0
    for f in folder_list:
        stepfile = glob("{:}/P{:}_*{:02n}_steps.dat".format(f, pointing, ap))[0]
        print stepfile
        chi = np.loadtxt(stepfile, usecols=(12,), unpack=True)
        chi = chi[chi == chi]
        upperlim = np.median(chi) + 1.3 * np.min(chi)
        if chi[-1] < minchi:
            minchi = chi[-1]
        if upperlim > maxchi:
            maxchi = upperlim

    fig = plt.figure()
    grid = ImageGrid(
        fig, 111, nrows_ncols=(1, 1), cbar_mode="each", cbar_location="top", cbar_pad="1%", axes_class=None
    )
    ax = grid[0]

    ax.set_xlabel("$Z/Z_{\odot}$")
    ax.set_ylabel("MLWA")
    goodage = []
    bigZ = np.zeros(len(folder_list))
    for z, f in enumerate(folder_list):

        stepfile = glob("{:}/P{:}_*{:02n}_steps.dat".format(f, pointing, ap))[0]
        print stepfile
        MLWA, chi = np.loadtxt(stepfile, usecols=(6, 12), unpack=True)
        idx = chi == chi
        chi = chi[idx]
        MLWA = MLWA[idx]
        idx = MLWA == MLWA
        chi = chi[idx]
        MLWA = MLWA[idx]

        #        good = np.where(chi < 80)
        #        chi = chi[good]
        #        MLWA = MLWA[good]
        chi -= minchi
        patches = []
        for i in range(MLWA.size):
            #            patches.append(Circle((z,MLWA[i]),radius=0.1,linewidth=0))
            width = rw * ((minchi + 5000) / (chi[i] + 5000))
            #            width = rw * (minchi/chi[i])
            patches.append(Rectangle((z - width / 2, MLWA[i] - rh / 2), width, rh))

        collection = PatchCollection(
            np.array(patches)[::-1],
            cmap=plt.get_cmap("gnuplot"),
            norm=matplotlib.colors.Normalize(vmin=minchi, vmax=maxchi),
        )
        collection.set_alpha(0.7)
        collection.set_linewidth(0.0)
        collection.set_array(chi[::-1])
        ax.add_collection(collection)

        #        ax.axhline(y=MLWA[-1],color='k',ls=':',alpha=0.6)
        ax.hlines(MLWA[-1], z - 0.3, z + 0.3, color="g", lw=2)
        prob = 1 - ss.chi2.cdf(chi[-1] * numfree, numfree)
        if prob >= 0.68:
            goodage.append(MLWA[-1])
            bigZ[z] = 1

        ax.text(z + 0.5, MLWA[-1], "{:4.2f}\n{:4.2f}".format(prob, chi[-1]), fontsize=10)

    collection.set_alpha(1.0)
    cbar = ax.cax.colorbar(collection)

    ci = [68.27, 50.0, 80.0, 40.0]
    dc = [4.72, 3.36, 5.99, 2.75]

    # for (c, d) in zip(ci, dc):
    #     ax.cax.axvline(x = np.log10(d), color='g')
    #     ax.cax.text(np.log10(d) - 0.03, 2, '{}'.format(c),
    #                 transform=ax.cax.transData,
    #                 fontsize=8)

    collection.set_alpha(0.1)
    cbar.set_label_text(r"$\Delta\chi^2_{\nu}$")

    ax.set_xlim(-1, len(Zlist) + 1)
    ax.set_ylim(0, 12)
    ax.set_xticks(np.arange(len(Zlist)))
    ax.set_xticklabels(Zlist)
    #    fig.show()

    return fig, np.mean(goodage), np.std(goodage), bigZ
Esempio n. 37
0
def get_wedges_for_heading_plot(x, y, color, orientation, size_radius=0.1, size_angle=20, colormap='jet', colornorm=None, size_radius_range=(0.01,.1), size_radius_norm=None, edgecolor='none', alpha=1, flip=True, deg=True, nskip=0, center_offset_fraction=0.75):
    '''
    Returns a Patch Collection of Wedges, with arbitrary color and orientation
    
    Outputs:
    Patch Collection
    
    Inputs:
    x, y        - x and y positions (np.array or list, each of length N)
    color       - values to color wedges by (np.array or list, length N), OR color string. 
       colormap - specifies colormap to use (string, eg. 'jet')
       norm     - specifies range you'd like to normalize to, 
                  if none, scales to min/max of color array (2-tuple, eg. (0,1) )
    orientation - angles are in degrees, use deg=False to convert radians to degrees
    size_radius - radius of wedge, in same units as x, y. Can be list or np.array, length N, for changing sizes
       size_radius_norm - specifies range you'd like to normalize size_radius to, if size_radius is a list/array
                  should be tuple, eg. (0.01, .1)
    size_angle  - angular extent of wedge, degrees. Can be list or np.array, length N, for changing sizes
    edgecolor   - color for lineedges, string or np.array of length N
    alpha       - transparency (single value, between 0 and 1)
    flip        - flip orientations by 180 degrees, default = True
    nskip       - allows you to skip between points to make the points clearer, nskip=1 skips every other point
    center_offset_fraction  - (float in range (0,1) ) - 0 means (x,y) is at the tip, 1 means (x,y) is at the edge
    '''
    cmap = plt.get_cmap(colormap)
    
    # norms
    if colornorm is None and type(color) is not str:
        colornorm = plt.Normalize(np.min(color), np.max(color))
    elif type(color) is not str:
        colornorm = plt.Normalize(colornorm[0], colornorm[1])
    if size_radius_norm is None:
        size_radius_norm = plt.Normalize(np.min(size_radius), np.max(size_radius), clip=True)
    else:
        size_radius_norm = plt.Normalize(size_radius_norm[0], size_radius_norm[1], clip=True)
        
    indices_to_plot = np.arange(0, len(x), nskip+1)
        
    # fix orientations
    if type(orientation) is list:
        orientation = np.array(orientation)
    if deg is False:
        orientation = orientation*180./np.pi
    if flip:
        orientation += 180
    
    flycons = []
    n = 0
    for i in indices_to_plot:
        # wedge parameters
        if type(size_radius) is list or type(size_radius) is np.array or type(size_radius) is np.ndarray: 
            r = size_radius_norm(size_radius[i])*(size_radius_range[1]-size_radius_range[0]) + size_radius_range[0] 
        else: r = size_radius
        
        if type(size_angle) is list or type(size_angle) is np.array or type(size_angle) is np.ndarray: 
            angle_swept = size_radius[i]
        else: angle_swept = size_radius
        theta1 = orientation[i] - size_angle/2.
        theta2 = orientation[i] + size_angle/2.
        
        center = [x[i], y[i]]
        center[0] -= np.cos(orientation[i]*np.pi/180.)*r*center_offset_fraction
        center[1] -= np.sin(orientation[i]*np.pi/180.)*r*center_offset_fraction
        
        wedge = patches.Wedge(center, r, theta1, theta2)
        flycons.append(wedge)
        
    # add collection and color it
    pc = PatchCollection(flycons, cmap=cmap, norm=colornorm)
    
    # set properties for collection
    pc.set_edgecolors(edgecolor)
    if type(color) is list or type(color) is np.array or type(color) is np.ndarray:
        if type(color) is list:
            color = np.asarray(color)
        pc.set_array(color[indices_to_plot])
    else:
        pc.set_facecolors(color)
    pc.set_alpha(alpha)
    
    return pc
    starting_time = time.process_time_ns()
    #bt = BallTree(min_samples_to_split = len(X) // 5) #int(math.ceil(math.sqrt(len(X)))))
    bt = BallTree()
    bt.fit(X, y)
    bt_process_time = time.process_time_ns() - starting_time
    print()

    print()
    print('BENCHMARKING')
    print('    %-20s  %12.3f ms' % ('BallTree', bt_process_time / 1.0e+6))

    fig, axis = pyplot.subplots(nrows = 1, ncols = 1, figsize = (10, 10))
    circles = list()
    def print_balls(split):
        print(split.center)
        circles.append(Circle((split.center[0], split.center[1]), math.sqrt(split.radius)))
        print(split.center)
        if split.left  is not None: print_balls(split.left)
        if split.right is not None: print_balls(split.right)
    print_balls(bt.root_split)

    p = PatchCollection(circles, alpha = 1.0)
    p.set_color('#1f77b4')
    p.set_alpha(0.2)
    axis.add_collection(p)
    axis.scatter(X[:, 0], X[:, 1], s = 30, color = 'black', alpha = 1.0)
    axis.set_xlim(-100, 100)
    axis.set_ylim(-100, 100)
    pyplot.tight_layout()
    pyplot.show()
    def task1_3c(self):
        """
         This function shows 2 sub-figures to describe showing the fraction of
         the most common category of accidents per LGA. Using Geopandas and
         suitable basemap to draw choropleth maps
        """
        temp2013 = pd.DataFrame(
            self.pd2013.groupby(['LGA_NAME', 'SEVERITY'])['OBJECTID'].count())
        temp2018 = pd.DataFrame(
            self.pd2018.groupby(['LGA_NAME', 'SEVERITY'])['OBJECTID'].count())

        temp2013.rename(columns={'OBJECTID': 'count'}, inplace=True)
        temp2013.sort_values(by=["LGA_NAME", "count"], ascending=False,
                             inplace=True)
        temp2013['rank'] = temp2013['count'].groupby("LGA_NAME").rank(
            method='first', ascending=False)
        temp2013 = temp2013.loc[temp2013['rank'] == 1.0].copy()
        tab2013 = pd.DataFrame(
            self.pd2013.groupby('LGA_NAME')['OBJECTID'].count())
        temp2013 = temp2013.merge(tab2013, on='LGA_NAME')
        temp2013['fraction'] = (100 * temp2013['count']) / temp2013['OBJECTID']
        temp13 = temp2013.reset_index()
        temp2013 = temp13.set_index('LGA_NAME')

        temp2018.rename(columns={'OBJECTID': 'count'}, inplace=True)
        temp2018.sort_values(by=["LGA_NAME", "count"], ascending=False,
                             inplace=True)
        temp2018['rank'] = temp2018['count'].groupby("LGA_NAME").rank(
            method='first', ascending=False)
        temp2018 = temp2018.loc[temp2018['rank'] == 1.0].copy()
        tab2018 = pd.DataFrame(
            self.pd2018.groupby('LGA_NAME')['OBJECTID'].count())
        temp2018 = temp2018.merge(tab2018, on='LGA_NAME')
        temp2018['fraction'] = (100 * temp2018['count']) / temp2018['OBJECTID']
        temp18 = temp2018.reset_index()
        temp2018 = temp18.set_index('LGA_NAME')

        dict2013 = temp13[['LGA_NAME', 'fraction']].set_index(
            'LGA_NAME').to_dict()
        dict2013 = dict2013['fraction']

        dict2018 = temp18[['LGA_NAME', 'fraction']].set_index(
            'LGA_NAME').to_dict()
        dict2018 = dict2018['fraction']

        arr_2013 = temp2013['fraction'].values
        arr_2018 = temp2018['fraction'].values
        values = np.append(arr_2013, arr_2018)

        # setup Lambert Conformal basemap.
        # set resolution=None to skip processing of boundary datasets.
        num_colors = 20
        cm = plt.get_cmap('Reds')
        scheme = [cm(i / num_colors) for i in range(num_colors)]
        bins = np.linspace(values.min(), values.max(), num_colors)
        temp2013['bin'] = np.digitize(arr_2013, bins) - 1
        temp2018['bin'] = np.digitize(arr_2018, bins) - 1

        fig = plt.figure(figsize=(14, 7))
        fig.tight_layout()
        ax_legend = fig.add_axes([0.122, 0.18, 0.78, 0.03], zorder=1)

        ax1 = fig.add_subplot(121)
        m = Basemap(width=12000000, height=9000000, projection='lcc',
                    resolution='f',
                    lat_0=-37.45,
                    lon_0=145.1,
                    llcrnrlon=138.8,
                    llcrnrlat=-39.74,
                    urcrnrlon=150.8,
                    urcrnrlat=-33.55)

        parallels = np.arange(-40., -30., 2.)
        m.drawparallels(parallels, labels=[False, True, True, False])
        meridians = np.arange(130., 160., 2.)
        m.drawmeridians(meridians, labels=[True, False, False, True])

        m.shadedrelief()
        m.readshapefile('add_dataset/LGA/LGA', 'country', drawbounds=False)

        for info, shape in zip(m.country_info, m.country):
            if info['LGA_NAME17'] in dict2013.keys():
                lga_name = info['LGA_NAME17']
                color = scheme[int(temp2013.loc[lga_name]['bin'])]

                patches = [Polygon(np.array(shape), True)]
                pc = PatchCollection(patches)
                pc.set_facecolor(color)
                pc.set_alpha(0.7)
                pc.set_edgecolor('#52616b')
                ax1.add_collection(pc)

            ax1.set_title('Year 2013',
                          fontsize=18,
                          fontweight='roman',
                          fontstyle='italic')

        ax2 = fig.add_subplot(122)
        m = Basemap(width=12000000, height=9000000, projection='lcc',
                    resolution='f',
                    lat_0=-37.45,
                    lon_0=145.1,
                    llcrnrlon=138.8,
                    llcrnrlat=-39.74,
                    urcrnrlon=150.8,
                    urcrnrlat=-33.55)

        parallels = np.arange(-40., -30., 2.)
        m.drawparallels(parallels, labels=[False, True, True, False])
        meridians = np.arange(130., 160., 2.)
        m.drawmeridians(meridians, labels=[True, False, False, True])

        m.shadedrelief()
        m.readshapefile('add_dataset/LGA/LGA', 'country', drawbounds=False)

        for info, shape in zip(m.country_info, m.country):
            if info['LGA_NAME17'] in dict2018.keys():
                lga_name = info['LGA_NAME17']
                color = scheme[int(temp2018.loc[lga_name]['bin'])]

                patches = [Polygon(np.array(shape), True)]
                pc = PatchCollection(patches)
                pc.set_facecolor(color)
                pc.set_alpha(0.7)
                pc.set_edgecolor('#52616b')
                ax2.add_collection(pc)

            ax2.set_title('Year 2018',
                          fontsize=18,
                          fontweight='roman',
                          fontstyle='italic')

            cmap = mpl.colors.ListedColormap(scheme)
            cb = mpl.colorbar.ColorbarBase(ax_legend, cmap=cmap, ticks=bins,
                                           boundaries=bins,
                                           orientation='horizontal')
            cb.ax.set_xticklabels([str(round(i, 1)) for i in bins])

        plt.show()
Esempio n. 40
0
  # a cor do polígono vem da imagem original            
  cores.append(image_rgb[y-1][x-1])
    
  # criamos um polígono para representar o triângulo (aqui começa o desenho
  # que estamos sintetizando)
  poly = Polygon(pontos[:,[0,1]][t_i], True)
  patches.append(poly)


# adicionamos os polígonos a uma coleção de colagens
p = PatchCollection(patches)
#print 'patches:', len(patches), 'regions:', len(cores)
# definimos as cores conforme imagem original  e as bordas em transparente
p.set_facecolor(cores)
p.set_edgecolor(cores)
p.set_alpha(.8)
# plotamos o desenho sintetizado
ax3.add_collection(p)
for ax in axes:
  ax.axis('off')

nome_pintura = '%s_passos.svg' % IMG[:-4]
fig.savefig(nome_pintura)

print 'pintura gerada em: %s' % nome_pintura 

# lista com coordenadas de cada triângulo
# print 'coords. triângulos:', coords_tri
# número de triângulos
# print 'num. de triângulos:', len(coords_tri)
Esempio n. 41
0
def plot_bond_site(options):
    options['prefix'] = 'bond_site'
    epsilon = numpy.finfo(numpy.float).eps

    bins = 11
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, bins))
    else:
        colors = options['color'](pylab.linspace(0, 1.0, bins))
    try:
        data_files = [(open('%s/results' % (options['datapath'][0]), 'r'), '')]
    except IOError:
        dirList = os.listdir(options['datapath'][0])
        files = [f for f in dirList if f.startswith('results')]
        data_files = [(open('%s/%s' % (options['datapath'][0], f), 'r'), f.replace('results', '')) for f in files]

    for (data_file, suffix) in data_files:
        bond_site = False
        max_cluster = False
        merge = dict()
        for line_num, line in enumerate(data_file):
            if line_num < 100 and line.find('bond-site') >= 0:
                bond_site = True
            if line_num < 10 and line.find('maximum cluster size') >=0:
                max_cluster = True
            if line.startswith('#') or line.isspace():
                continue
            tokens = line.split(':')[1].split(',')
            # ps, pb, reachability, std, conf, replications
            if len(tokens) == 9:
                ps, pb, r, std, conf, n, fw, fw_std, fw_conf = tokens
                t = ((float(ps), float(pb), float(r), float(std), float(conf), int(n), float(fw), float(fw_std), float(fw_conf)))
            else:
                ps, pb, r, std, conf, n = tokens
                t = ((float(ps), float(pb), float(r), float(std), float(conf), int(n), 0.0, 0.0, 0.0))

            try:
                merge[(float(tokens[0]), float(tokens[1]))].append(t)
            except KeyError:
                merge[(float(tokens[0]), float(tokens[1]))] = [t]

        fig_contour = MyFig(options, figsize=(10, 8), xlabel=r'Probability $p_s$', ylabel=r'Probability $p_b$', aspect='auto')
        fig_pcolor = MyFig(options, figsize=(10, 8), xlabel=r'Probability $p_s$', ylabel=r'Probability $p_b$', aspect='auto')
        fig_vs_pb = None
        fig_vs_ps = None
        if bond_site:
            if max_cluster:
                ylabel= 'Max. Percolation Cluster Size'
            else:
                ylabel= 'Mean Percolation Cluster Size'
        else:
            fig_vs_pb = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')
            fig_vs_ps = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')
            fig_fw_pb = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Probability $p_s$', ylabel=r'Fraction of Forwarded Packets~$\forwarded$', aspect='auto')
            fig_fw_ps = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Probability $p_b$', ylabel=r'Fraction of Forwarded Packets~$\forwarded$', aspect='auto')
            ylabel = r'Reachability~$\reachability$'
        fig_site = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Probability $p_s$', ylabel=ylabel, aspect='auto')
        fig_bond = MyFig(options, figsize=(10, 8), legend=(not options['no_legend']), grid=False, xlabel=r'Probability $p_b$', ylabel=ylabel, aspect='auto')

        def fit_data(X, Y, options):
            init_params = [1.0, 0.0, 0.0, 1.0]
            hyperbolic2 = lambda (a,b,c,d), x: 1/(map(lambda _x: a*_x, x)+b)    # f(x) = 1/(ax+b)
            hyperbolic4 = lambda (a,b,c,d), x: d/(map(lambda _x: a*_x, x)+b)+c  # f(x) = d/(ax+b)+c
            exponential = lambda (a,b,c,d), x: scipy.e**(a*(x+b))+c             # f(x) = e^(-a(x+b))+c
            fitfunc = locals()[options['fit']]
            errfunc = lambda (a,b,c,d), x, y: y-fitfunc((a,b,c,d), x)
            return scipy.optimize.leastsq(errfunc, init_params, args=(X, Y)), fitfunc

        def contour_plot(tuples):
            X = pylab.linspace(0, 1, scipy.sqrt(len(tuples)))
            Y = pylab.linspace(0, 1, scipy.sqrt(len(tuples)))
            Z = numpy.array([r for p, pb, r in tuples]).reshape((len(X), len(Y))).transpose()
            X, Y = pylab.meshgrid(X, Y)
            if options['grayscale']:
                pcolor = fig_contour.ax.contourf(X, Y, Z, levels=pylab.linspace(0, 1, 101), cmap=options['graycm'], antialiased=True, linestyles=None)
            else:
                pcolor = fig_contour.ax.contourf(X, Y, Z, levels=pylab.linspace(0, 1, 101), cmap=fu_colormap(), antialiased=True, linestyles=None)
            cbar = fig_contour.colorbar(pcolor)
            cbar.set_ticks(pylab.linspace(0, 1, 11))

            if options['grayscale']:
                pcolor = fig_pcolor.ax.pcolormesh(X, Y, Z, vmin=0, vmax=1, cmap=options['graycm'])
            else:
                pcolor = fig_pcolor.ax.pcolormesh(X, Y, Z, vmin=0, vmax=1, cmap=fu_colormap())
            cbar = fig_pcolor.colorbar(pcolor)
            cbar.set_ticks(pylab.linspace(0, 1, 11))

        data = calc_metrics(merge)
        tuples = [(ps, pb, r) for ps, pb, r, _std, _conf, _n, _fw_mean, _fw_std, _fw_std in data]
        contour_plot(tuples)
        nodes = options['nodes']

        for i, bin in enumerate(pylab.linspace(0, 1, bins)):
            r_pb1       = numpy.array([r for _ps, pb, r, _std, _conf, _n, _fw_mean, _fw_std, _fw_conf in data if abs(pb - bin) < epsilon*2])
            fw_pb1      = numpy.array([fw_mean for _ps, pb, _r, _std, _conf, _n, fw_mean, _fw_std, _fw_conf in data if abs(pb - bin) < epsilon*2])/nodes
            fw_conf_pb1 = numpy.array([fw_conf for _ps, pb, _r, _std, _conf, _n, fw_mean, _fw_std, fw_conf in data if abs(pb - bin) < epsilon*2])/nodes
            conf_pb1    = numpy.array([conf for _ps, pb, _r, _std, conf, _n, _fw_mean, _fw_std, _fw_conf in data if abs(pb - bin) < epsilon*2])
            p_pb1       = numpy.array([ps for ps, pb, _r, _std, _conf, _n, _fw_mean, _fw_std, _fw_conf in data if abs(pb - bin) < epsilon*2])

            r_ps1       = numpy.array([r for ps, _pb, r, _std, _conf, n, _fw_mean, _fw_std, _fw_conf in data if abs(ps - bin) < epsilon*2])
            fw_ps1      = numpy.array([fw_mean for ps, _pb, r, _std, _conf, n, fw_mean, _fw_std, _fw_conf in data if abs(ps - bin) < epsilon*2])/nodes
            fw_conf_ps1 = numpy.array([fw_conf for ps, _pb, r, _std, _conf, n, fw_mean, _fw_std, fw_conf in data if abs(ps - bin) < epsilon*2])/nodes
            conf_ps1    = numpy.array([conf for ps, _pb, _r, _std, conf, _n, _fw_mean, _fw_std, _fw_conf in data if abs(ps - bin) < epsilon*2])
            p_ps1       = numpy.array([pb for ps, pb, _r, _std, _conf, n, _fw_mean, _fw_std, _fw_conf in data if abs(ps - bin) < epsilon*2])

            assert(len(r_pb1) == len(conf_pb1) == len(p_pb1))
            assert(len(r_ps1) == len(conf_ps1) == len(p_ps1))

            if len(r_pb1) > 0:
                if not options['noconfidence']:
                    patch_collection = PatchCollection([conf2poly(p_pb1, list(r_pb1+conf_pb1), list(r_pb1-conf_pb1), color=colors[i])], match_original=True)
                    patch_collection.set_alpha(0.3)
                    patch_collection.set_linestyle('dashed')
                    fig_site.ax.add_collection(patch_collection)
                    fig_site.ax.plot(p_pb1, r_pb1, color=colors[i], label='$%.2f$' % bin)

                    if fig_vs_pb:
                        fig_vs_pb.ax.plot(fw_pb1, r_pb1, color=colors[i], label='$%.2f$' % bin)

                        patch_collection = PatchCollection([conf2poly(p_pb1, list(fw_pb1+fw_conf_pb1), list(fw_pb1-fw_conf_pb1), color=colors[i])], match_original=True)
                        patch_collection.set_alpha(0.3)
                        patch_collection.set_linestyle('dashed')
                        fig_fw_pb.ax.add_collection(patch_collection)
                        fig_fw_pb.ax.plot(p_pb1, fw_pb1, color=colors[i], label='$%.2f$' % bin)
                else:
                    fig_site.ax.plot(p_pb1, r_pb1, color=colors[i], label='$%.2f$' % bin)
                    if fig_vs_pb:
                        fig_vs_pb.ax.plot(fw_pb1, r_pb1, color=colors[i], label='$%.2f$' % bin)
                        fig_fw_pb.ax.plot(p_pb1, fw_pb1, color=colors[i], label='$%.2f$' % bin)
            if len(r_ps1) > 0:
                if not options['noconfidence']:
                    patch_collection = PatchCollection([conf2poly(p_ps1, list(r_ps1+conf_ps1), list(r_ps1-conf_ps1), color=colors[i])], match_original=True)
                    patch_collection.set_alpha(0.3)
                    patch_collection.set_linestyle('dashed')
                    fig_bond.ax.add_collection(patch_collection)
                    fig_bond.ax.plot(p_ps1, r_ps1, color=colors[i], label='$%.2f$' % bin)

                    if fig_vs_ps:
                        fig_vs_ps.ax.plot(fw_ps1, r_ps1, color=colors[i], label='$%.2f$' % bin)

                        patch_collection = PatchCollection([conf2poly(p_ps1, list(fw_ps1+fw_conf_ps1), list(fw_ps1-fw_conf_ps1), color=colors[i])], match_original=True)
                        patch_collection.set_alpha(0.3)
                        patch_collection.set_linestyle('dashed')
                        fig_fw_ps.ax.add_collection(patch_collection)
                        fig_fw_ps.ax.plot(p_ps1, fw_ps1, color=colors[i], label='$%.2f$' % bin)
                else:
                    fig_bond.ax.plot(p_ps1, r_ps1, color=colors[i], label='$%.2f$' % bin)
                    if fig_vs_ps:
                        fig_vs_ps.ax.plot(fw_ps1, r_ps1, color=colors[i], label='$%.2f$' % bin)
                        fig_fw_ps.ax.plot(p_ps1, fw_ps1, color=colors[i], label='$%.2f$' % bin)

            X = [p for p, pb, r in tuples if r < bin and r >= bin-0.1]
            Y = [pb for ps, pb, r in tuples if r < bin and r >= bin-0.1]
            assert(len(X) == len(Y))
            if len(X) >= 4 and len(options['fit']):
                (fitted_params, success), fitfunc = fit_data(X, Y, options)
                #print fitted_params, success
                min_x = min(X)
                while fitfunc(fitted_params, [min_x]) <= 1.0 and min_x >= 0.0:
                    min_x -= 0.01
                max_x = max(X)
                while fitfunc(fitted_params, [max_x]) >= 0.0 and max_x <= 1.0:
                    max_x += 0.01
                xfit = pylab.linspace(min_x, max_x, 100)
                fig_contour.ax.plot(xfit, fitfunc(fitted_params, xfit), color='black', lw=2, label='%.2f' % bin)

        for f in [fig_contour, fig_pcolor, fig_site, fig_bond]:
            f.ax.set_xlim(0, 1)
            f.ax.set_ylim(0, 1)
        fig_site.legend_title = '$p_b$'
        fig_bond.legend_title = '$p_s$'
        fig_contour.save('contour%s' % suffix)
        fig_pcolor.save('pcolor%s' % suffix)
        fig_site.save('graph-site%s' % suffix)
        fig_bond.save('graph-bond%s' % suffix)
        if fig_vs_ps:
            fig_vs_ps.ax.set_xlim(0,1)
            fig_vs_ps.ax.set_ylim(0,1)
            fig_vs_ps.legend_title = '$p_s$'
            fig_vs_ps.save('vs_ps')

            fig_fw_ps.ax.set_xlim(0,1)
            fig_fw_ps.ax.set_ylim(0,1)
            fig_fw_ps.legend_title = '$p_s$'
            fig_fw_ps.save('fw_ps')

            fig_vs_pb.ax.set_xlim(0,1)
            fig_vs_pb.ax.set_ylim(0,1)
            fig_vs_pb.legend_title = '$p_b$'
            fig_vs_pb.save('vs_pb')

            fig_fw_pb.ax.set_xlim(0,1)
            fig_fw_pb.ax.set_ylim(0,1)
            fig_fw_pb.legend_title = '$p_b$'
            fig_fw_pb.save('fw_pb')
Esempio n. 42
0
    def draw(self,
             ax,
             draw_polygons=True,
             colour='k',
             line_alpha=1.,
             fill_alpha=1.,
             linestyle='-',
             linewidth=1.,
             markers=None,
             values=None,
             precompv=None,
             vmin=None,
             vmax=None,
             title=None,
             cmap=None,
             cblabel=None,
             logscale=False,
             allowed_cbticklabels=(None, ),
             extend='neither',
             zorder=0):
        """
		Draw the diagram
		"""

        drawvalues = values is not None

        if drawvalues:
            patches = []
            colours = np.zeros(self.nc)

        for i, pol in self.polygons.items():

            # Colours and filled polygons
            if drawvalues:
                filled_pol = mp.Polygon(self.cellverts[i])
                patches.append(filled_pol)
                if values == 'areas':
                    colours[i] = pol.area
                if values == 'inv_areas':
                    colours[i] = 1. / self.free_areas[i]
                if values == 'free_areas':
                    colours[i] = self.free_areas[i]
                if values == 'precomputed':
                    if logscale:
                        colours[i] = np.abs(precompv[i])
                    else:
                        colours[i] = precompv[i]

                # Colour for the polygon contours
                if colour == 'same_as_facecolors':
                    pc_ = colours[i]
            else:
                pc_ = colour

            # Draw the polygon
            if draw_polygons:
                pol.draw(ax=ax,
                         colour=pc_,
                         alpha=line_alpha,
                         linestyle=linestyle,
                         linewidth=linewidth,
                         markers=markers,
                         zorder=zorder)

        # Line colours
        if drawvalues:
            if vmin is None:
                vmin = colours.min()
            if vmax is None:
                vmax = colours.max()
            if logscale:
                vmin = np.abs(vmin)
                vmax = np.abs(vmax)
                norm = LogNorm(vmin=vmin, vmax=vmax)
            else:
                norm = Normalize(vmin=vmin, vmax=vmax)
            m = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
            line_colours = m.to_rgba(colours)
            print(line_colours)

        if drawvalues:

            collection = PatchCollection(patches, cmap=cmap, norm=norm)
            ax.add_collection(collection)
            collection.set_alpha(fill_alpha)
            collection.set_array(colours)
            if logscale:
                collection.set_clim(vmin=vmin, vmax=vmax)
            else:
                collection.set_clim(vmin=0., vmax=vmax)
            if colour == 'same_as_facecolors':
                collection.set_edgecolors(line_colours)
            else:
                collection.set_edgecolor(colour)
            collection.set_linewidth(linewidth)

        if values == 'precomputed':

            collection.set_clim(vmin=vmin, vmax=vmax)

            # Color bar
            if logscale:
                l_f = LogFormatter(10, labelOnlyBase=False)
                cb = plt.colorbar(collection,
                                  ax=ax,
                                  orientation='vertical',
                                  format=l_f,
                                  extend=extend)
                # Set minor ticks
                # We need to nomalize the tick locations so that they're in the range from 0-1...
                # minorticks = p.norm(np.arange(1, 10, 2))
                # Minimum and maximum exponents
                min_exp = int(np.log10(min(vmin, vmax)))
                max_exp = int(np.log10(max(vmin, vmax))) + 1
                # Ticks for the colorbar in case it's logscale
                minorticks = 10.**np.arange(min_exp, max_exp + 1, 1)
                minorticks_ = minorticks.tolist()
                for i in range(2, 10, 1):
                    minorticks_ = minorticks_ + (float(i) *
                                                 minorticks).tolist()
                minorticks_.sort()
                minorticks = np.array(minorticks_)
                minorticks = minorticks[np.where(minorticks >= vmin)]
                minorticks = minorticks[np.where(minorticks <= vmax)]
                print(minorticks)
                cb.set_ticks(minorticks)
                cb.set_ticklabels([
                    str(int(x)) if x in allowed_cbticklabels else ''
                    for x in minorticks
                ])
            else:
                cb = plt.colorbar(collection,
                                  ax=ax,
                                  orientation='vertical',
                                  extend=extend)
            cb.set_label(cblabel)
        if title is not None:
            ax.set_title(title)

        ax.set_xlabel(r'$\rm x$ ($\rm \mu m$)')
        ax.set_ylabel(r'$\rm y$ ($\rm \mu m$)')
Esempio n. 43
0
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options,
                figsize=(10, 8),
                legend=True,
                grid=False,
                xlabel=r'Probability $p_s$',
                ylabel=r'Reachability~$\reachability$',
                aspect='auto')
    fig_vs = MyFig(options,
                   figsize=(10, 8),
                   legend=True,
                   grid=False,
                   xlabel=r'Fraction of Forwarded Packets~$\forwarded$',
                   ylabel=r'Reachability~$\reachability$',
                   aspect='auto')

    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, 3))
    else:
        colors = fu_colormap()(pylab.linspace(0, 1.0, 3))
    nodes = 105

    axins = None
    if options['inset_loc'] >= 0:
        axins = zoomed_inset_axes(fig_vs.ax,
                                  options['inset_zoom'],
                                  loc=options['inset_loc'])
        axins.set_xlim(options['inset_xlim'])
        axins.set_ylim(options['inset_ylim'])
        axins.set_xticklabels([])
        axins.set_yticklabels([])
        mark_inset(fig_vs.ax, axins, loc1=2, loc2=3, fc="none", ec="0.5")

    for i, (name, label) in enumerate(names):
        data = parse_site_only(options['datapath'][0], name)
        rs = numpy.array([
            r for p, r, std, conf, n, fw, fw_std, fw_conf in data
            if r <= options['limit']
        ])
        fws = numpy.array([
            fw for p, r, std, conf, n, fw, fw_std, fw_conf in data
            if r <= options['limit']
        ]) / (nodes - 1)
        ps = numpy.array([
            p for p, r, std, conf, n, fw, fw_std, fw_conf in data
        ])  #[0:len(rs)])
        yerr = numpy.array([
            conf for p, r, std, conf, n, fw, fw_std, fw_conf in data
        ])  #[0:len(rs)])

        patch_collection = PatchCollection(
            [conf2poly(ps, list(rs + yerr), list(rs - yerr), color=colors[i])],
            match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)

        fig.ax.plot(ps, rs, label=label, color=colors[i])
        fig_vs.ax.plot(fws, rs, label=label, color=colors[i])
        if axins:
            axins.plot(fws, rs, color=colors[i])

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0, 1)
    fig_vs.ax.set_ylim(0, 1)
    fig_vs.save('vs_pb')
Esempio n. 44
0
def plot_bond_site(options):
    options['prefix'] = 'bond_site'
    epsilon = numpy.finfo(numpy.float).eps

    bins = 11
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1.0, bins))
    else:
        colors = options['color'](pylab.linspace(0, 1.0, bins))
    try:
        data_files = [(open('%s/results' % (options['datapath'][0]), 'r'), '')]
    except IOError:
        dirList = os.listdir(options['datapath'][0])
        files = [f for f in dirList if f.startswith('results')]
        data_files = [(open('%s/%s' % (options['datapath'][0], f),
                            'r'), f.replace('results', '')) for f in files]

    for (data_file, suffix) in data_files:
        bond_site = False
        max_cluster = False
        merge = dict()
        for line_num, line in enumerate(data_file):
            if line_num < 100 and line.find('bond-site') >= 0:
                bond_site = True
            if line_num < 10 and line.find('maximum cluster size') >= 0:
                max_cluster = True
            if line.startswith('#') or line.isspace():
                continue
            tokens = line.split(':')[1].split(',')
            # ps, pb, reachability, std, conf, replications
            if len(tokens) == 9:
                ps, pb, r, std, conf, n, fw, fw_std, fw_conf = tokens
                t = ((float(ps), float(pb), float(r), float(std), float(conf),
                      int(n), float(fw), float(fw_std), float(fw_conf)))
            else:
                ps, pb, r, std, conf, n = tokens
                t = ((float(ps), float(pb), float(r), float(std), float(conf),
                      int(n), 0.0, 0.0, 0.0))

            try:
                merge[(float(tokens[0]), float(tokens[1]))].append(t)
            except KeyError:
                merge[(float(tokens[0]), float(tokens[1]))] = [t]

        fig_contour = MyFig(options,
                            figsize=(10, 8),
                            xlabel=r'Probability $p_s$',
                            ylabel=r'Probability $p_b$',
                            aspect='auto')
        fig_pcolor = MyFig(options,
                           figsize=(10, 8),
                           xlabel=r'Probability $p_s$',
                           ylabel=r'Probability $p_b$',
                           aspect='auto')
        fig_vs_pb = None
        fig_vs_ps = None
        if bond_site:
            if max_cluster:
                ylabel = 'Max. Percolation Cluster Size'
            else:
                ylabel = 'Mean Percolation Cluster Size'
        else:
            fig_vs_pb = MyFig(
                options,
                figsize=(10, 8),
                legend=(not options['no_legend']),
                grid=False,
                xlabel=r'Fraction of Forwarded Packets~$\forwarded$',
                ylabel=r'Reachability~$\reachability$',
                aspect='auto')
            fig_vs_ps = MyFig(
                options,
                figsize=(10, 8),
                legend=(not options['no_legend']),
                grid=False,
                xlabel=r'Fraction of Forwarded Packets~$\forwarded$',
                ylabel=r'Reachability~$\reachability$',
                aspect='auto')
            fig_fw_pb = MyFig(
                options,
                figsize=(10, 8),
                legend=(not options['no_legend']),
                grid=False,
                xlabel=r'Probability $p_s$',
                ylabel=r'Fraction of Forwarded Packets~$\forwarded$',
                aspect='auto')
            fig_fw_ps = MyFig(
                options,
                figsize=(10, 8),
                legend=(not options['no_legend']),
                grid=False,
                xlabel=r'Probability $p_b$',
                ylabel=r'Fraction of Forwarded Packets~$\forwarded$',
                aspect='auto')
            ylabel = r'Reachability~$\reachability$'
        fig_site = MyFig(options,
                         figsize=(10, 8),
                         legend=(not options['no_legend']),
                         grid=False,
                         xlabel=r'Probability $p_s$',
                         ylabel=ylabel,
                         aspect='auto')
        fig_bond = MyFig(options,
                         figsize=(10, 8),
                         legend=(not options['no_legend']),
                         grid=False,
                         xlabel=r'Probability $p_b$',
                         ylabel=ylabel,
                         aspect='auto')

        def fit_data(X, Y, options):
            init_params = [1.0, 0.0, 0.0, 1.0]
            hyperbolic2 = lambda (a, b, c, d), x: 1 / (map(
                lambda _x: a * _x, x) + b)  # f(x) = 1/(ax+b)
            hyperbolic4 = lambda (a, b, c, d), x: d / (map(
                lambda _x: a * _x, x) + b) + c  # f(x) = d/(ax+b)+c
            exponential = lambda (a, b, c, d), x: scipy.e**(a * (
                x + b)) + c  # f(x) = e^(-a(x+b))+c
            fitfunc = locals()[options['fit']]
            errfunc = lambda (a, b, c, d), x, y: y - fitfunc((a, b, c, d), x)
            return scipy.optimize.leastsq(errfunc, init_params,
                                          args=(X, Y)), fitfunc

        def contour_plot(tuples):
            X = pylab.linspace(0, 1, scipy.sqrt(len(tuples)))
            Y = pylab.linspace(0, 1, scipy.sqrt(len(tuples)))
            Z = numpy.array([r for p, pb, r in tuples]).reshape(
                (len(X), len(Y))).transpose()
            X, Y = pylab.meshgrid(X, Y)
            if options['grayscale']:
                pcolor = fig_contour.ax.contourf(X,
                                                 Y,
                                                 Z,
                                                 levels=pylab.linspace(
                                                     0, 1, 101),
                                                 cmap=options['graycm'],
                                                 antialiased=True,
                                                 linestyles=None)
            else:
                pcolor = fig_contour.ax.contourf(X,
                                                 Y,
                                                 Z,
                                                 levels=pylab.linspace(
                                                     0, 1, 101),
                                                 cmap=fu_colormap(),
                                                 antialiased=True,
                                                 linestyles=None)
            cbar = fig_contour.colorbar(pcolor)
            cbar.set_ticks(pylab.linspace(0, 1, 11))

            if options['grayscale']:
                pcolor = fig_pcolor.ax.pcolormesh(X,
                                                  Y,
                                                  Z,
                                                  vmin=0,
                                                  vmax=1,
                                                  cmap=options['graycm'])
            else:
                pcolor = fig_pcolor.ax.pcolormesh(X,
                                                  Y,
                                                  Z,
                                                  vmin=0,
                                                  vmax=1,
                                                  cmap=fu_colormap())
            cbar = fig_pcolor.colorbar(pcolor)
            cbar.set_ticks(pylab.linspace(0, 1, 11))

        data = calc_metrics(merge)
        tuples = [
            (ps, pb, r)
            for ps, pb, r, _std, _conf, _n, _fw_mean, _fw_std, _fw_std in data
        ]
        contour_plot(tuples)
        nodes = options['nodes']

        for i, bin in enumerate(pylab.linspace(0, 1, bins)):
            r_pb1 = numpy.array([
                r for _ps, pb, r, _std, _conf, _n, _fw_mean, _fw_std, _fw_conf
                in data if abs(pb - bin) < epsilon * 2
            ])
            fw_pb1 = numpy.array([
                fw_mean for _ps, pb, _r, _std, _conf, _n, fw_mean, _fw_std,
                _fw_conf in data if abs(pb - bin) < epsilon * 2
            ]) / nodes
            fw_conf_pb1 = numpy.array([
                fw_conf for _ps, pb, _r, _std, _conf, _n, fw_mean, _fw_std,
                fw_conf in data if abs(pb - bin) < epsilon * 2
            ]) / nodes
            conf_pb1 = numpy.array([
                conf for _ps, pb, _r, _std, conf, _n, _fw_mean, _fw_std,
                _fw_conf in data if abs(pb - bin) < epsilon * 2
            ])
            p_pb1 = numpy.array([
                ps for ps, pb, _r, _std, _conf, _n, _fw_mean, _fw_std, _fw_conf
                in data if abs(pb - bin) < epsilon * 2
            ])

            r_ps1 = numpy.array([
                r for ps, _pb, r, _std, _conf, n, _fw_mean, _fw_std, _fw_conf
                in data if abs(ps - bin) < epsilon * 2
            ])
            fw_ps1 = numpy.array([
                fw_mean for ps, _pb, r, _std, _conf, n, fw_mean, _fw_std,
                _fw_conf in data if abs(ps - bin) < epsilon * 2
            ]) / nodes
            fw_conf_ps1 = numpy.array([
                fw_conf for ps, _pb, r, _std, _conf, n, fw_mean, _fw_std,
                fw_conf in data if abs(ps - bin) < epsilon * 2
            ]) / nodes
            conf_ps1 = numpy.array([
                conf for ps, _pb, _r, _std, conf, _n, _fw_mean, _fw_std,
                _fw_conf in data if abs(ps - bin) < epsilon * 2
            ])
            p_ps1 = numpy.array([
                pb for ps, pb, _r, _std, _conf, n, _fw_mean, _fw_std, _fw_conf
                in data if abs(ps - bin) < epsilon * 2
            ])

            assert (len(r_pb1) == len(conf_pb1) == len(p_pb1))
            assert (len(r_ps1) == len(conf_ps1) == len(p_ps1))

            if len(r_pb1) > 0:
                if not options['noconfidence']:
                    patch_collection = PatchCollection([
                        conf2poly(p_pb1,
                                  list(r_pb1 + conf_pb1),
                                  list(r_pb1 - conf_pb1),
                                  color=colors[i])
                    ],
                                                       match_original=True)
                    patch_collection.set_alpha(0.3)
                    patch_collection.set_linestyle('dashed')
                    fig_site.ax.add_collection(patch_collection)
                    fig_site.ax.plot(p_pb1,
                                     r_pb1,
                                     color=colors[i],
                                     label='$%.2f$' % bin)

                    if fig_vs_pb:
                        fig_vs_pb.ax.plot(fw_pb1,
                                          r_pb1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)

                        patch_collection = PatchCollection([
                            conf2poly(p_pb1,
                                      list(fw_pb1 + fw_conf_pb1),
                                      list(fw_pb1 - fw_conf_pb1),
                                      color=colors[i])
                        ],
                                                           match_original=True)
                        patch_collection.set_alpha(0.3)
                        patch_collection.set_linestyle('dashed')
                        fig_fw_pb.ax.add_collection(patch_collection)
                        fig_fw_pb.ax.plot(p_pb1,
                                          fw_pb1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)
                else:
                    fig_site.ax.plot(p_pb1,
                                     r_pb1,
                                     color=colors[i],
                                     label='$%.2f$' % bin)
                    if fig_vs_pb:
                        fig_vs_pb.ax.plot(fw_pb1,
                                          r_pb1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)
                        fig_fw_pb.ax.plot(p_pb1,
                                          fw_pb1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)
            if len(r_ps1) > 0:
                if not options['noconfidence']:
                    patch_collection = PatchCollection([
                        conf2poly(p_ps1,
                                  list(r_ps1 + conf_ps1),
                                  list(r_ps1 - conf_ps1),
                                  color=colors[i])
                    ],
                                                       match_original=True)
                    patch_collection.set_alpha(0.3)
                    patch_collection.set_linestyle('dashed')
                    fig_bond.ax.add_collection(patch_collection)
                    fig_bond.ax.plot(p_ps1,
                                     r_ps1,
                                     color=colors[i],
                                     label='$%.2f$' % bin)

                    if fig_vs_ps:
                        fig_vs_ps.ax.plot(fw_ps1,
                                          r_ps1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)

                        patch_collection = PatchCollection([
                            conf2poly(p_ps1,
                                      list(fw_ps1 + fw_conf_ps1),
                                      list(fw_ps1 - fw_conf_ps1),
                                      color=colors[i])
                        ],
                                                           match_original=True)
                        patch_collection.set_alpha(0.3)
                        patch_collection.set_linestyle('dashed')
                        fig_fw_ps.ax.add_collection(patch_collection)
                        fig_fw_ps.ax.plot(p_ps1,
                                          fw_ps1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)
                else:
                    fig_bond.ax.plot(p_ps1,
                                     r_ps1,
                                     color=colors[i],
                                     label='$%.2f$' % bin)
                    if fig_vs_ps:
                        fig_vs_ps.ax.plot(fw_ps1,
                                          r_ps1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)
                        fig_fw_ps.ax.plot(p_ps1,
                                          fw_ps1,
                                          color=colors[i],
                                          label='$%.2f$' % bin)

            X = [p for p, pb, r in tuples if r < bin and r >= bin - 0.1]
            Y = [pb for ps, pb, r in tuples if r < bin and r >= bin - 0.1]
            assert (len(X) == len(Y))
            if len(X) >= 4 and len(options['fit']):
                (fitted_params, success), fitfunc = fit_data(X, Y, options)
                #print fitted_params, success
                min_x = min(X)
                while fitfunc(fitted_params, [min_x]) <= 1.0 and min_x >= 0.0:
                    min_x -= 0.01
                max_x = max(X)
                while fitfunc(fitted_params, [max_x]) >= 0.0 and max_x <= 1.0:
                    max_x += 0.01
                xfit = pylab.linspace(min_x, max_x, 100)
                fig_contour.ax.plot(xfit,
                                    fitfunc(fitted_params, xfit),
                                    color='black',
                                    lw=2,
                                    label='%.2f' % bin)

        for f in [fig_contour, fig_pcolor, fig_site, fig_bond]:
            f.ax.set_xlim(0, 1)
            f.ax.set_ylim(0, 1)
        fig_site.legend_title = '$p_b$'
        fig_bond.legend_title = '$p_s$'
        fig_contour.save('contour%s' % suffix)
        fig_pcolor.save('pcolor%s' % suffix)
        fig_site.save('graph-site%s' % suffix)
        fig_bond.save('graph-bond%s' % suffix)
        if fig_vs_ps:
            fig_vs_ps.ax.set_xlim(0, 1)
            fig_vs_ps.ax.set_ylim(0, 1)
            fig_vs_ps.legend_title = '$p_s$'
            fig_vs_ps.save('vs_ps')

            fig_fw_ps.ax.set_xlim(0, 1)
            fig_fw_ps.ax.set_ylim(0, 1)
            fig_fw_ps.legend_title = '$p_s$'
            fig_fw_ps.save('fw_ps')

            fig_vs_pb.ax.set_xlim(0, 1)
            fig_vs_pb.ax.set_ylim(0, 1)
            fig_vs_pb.legend_title = '$p_b$'
            fig_vs_pb.save('vs_pb')

            fig_fw_pb.ax.set_xlim(0, 1)
            fig_fw_pb.ax.set_ylim(0, 1)
            fig_fw_pb.legend_title = '$p_b$'
            fig_fw_pb.save('fw_pb')
Esempio n. 45
0
def patchValMap(vals,
                xvec=None,
                yvec=None,
                ax=None,
                cMin=None,
                cMax=None,
                logScale=None,
                label=None,
                dx=1,
                dy=None,
                cTrim=0,
                **kwargs):
    """Plot previously generated (generateVecMatrix) y map (category).

    Parameters
    ----------
    vals : iterable
        Data values to show.
    xvec : dict {i:num}
        dict (must match vals.shape[0])
    ymap : iterable
        vector for x axis (must match vals.shape[0])
    ax : mpl.axis
        axis to plot, if not given a new figure is created
    cMin/cMax : float
        minimum/maximum color values
    cTrim : float [0]
        use trim value to exclude outer cTrim percent of data from color scale
    logScale : bool
        logarithmic colour scale [min(vals)>0]
    label : string
        colorbar label
    ** kwargs:
        * circular : bool
            Plot in polar coordinates.
    """
    if cMin is None:
        cMin = np.min(vals)
        # cMin = np.nanquantile(vals, cTrim/100)
    if cMax is None:
        cMax = np.max(vals)
        # cMin = np.nanquantile(vals, 1-cTrim/100)

    if logScale is None:
        logScale = (cMin > 0.0)

    norm = None
    if logScale and cMin > 0:
        norm = LogNorm(vmin=cMin, vmax=cMax)
    else:
        norm = Normalize(vmin=cMin, vmax=cMax)

    if ax is None:
        ax = plt.subplots()[1]

    recs = []

    circular = kwargs.pop('circular', False)
    if circular:
        recs = [None] * len(xvec)
        if dy is None:  # map y values to unique
            ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}

            xyMap = {}
            for i, y in enumerate(yvec):
                if y not in xyMap:
                    xyMap[y] = []
                xyMap[y].append(i)

            # maxR = max(ymap.values())  # what's that for? not used
            dR = 1 / (len(ymap.values()) + 1)
            # dOff = np.pi / 2  # what's that for? not used

            for y, xIds in xyMap.items():
                r = 1. - dR * (ymap[y] + 1)
                # ax.plot(r * np.cos(xvec[xIds]),
                #         r * np.sin(xvec[xIds]), 'o')

                # print(y, ymap[y])
                for i in xIds:
                    phi = xvec[i]
                    # x = r * np.cos(phi)  # what's that for? not used
                    y = r * np.sin(phi)

                    dPhi = (xvec[1] - xvec[0])

                    recs[i] = Wedge((0., 0.),
                                    r + dR / 1.5,
                                    (phi - dPhi) * 360 / (2 * np.pi),
                                    (phi + dPhi) * 360 / (2 * np.pi),
                                    width=dR,
                                    zorder=1 + r)
                    # if i < 5:
                    #     ax.text(x, y, str(i))
                    # pg.wait()
        else:
            raise ("Implementme")
    else:
        if dy is None:  # map y values to unique
            ymap = {xy: ii for ii, xy in enumerate(np.unique(yvec))}
            for i in range(len(vals)):
                recs.append(
                    Rectangle((xvec[i] - dx / 2, ymap[yvec[i]] - 0.5), dx, 1))
        else:
            for i in range(len(vals)):
                recs.append(
                    Rectangle((xvec[i] - dx / 2, yvec[i] - dy / 2), dx, dy))
        ax.set_xlim(min(xvec) - dx / 2, max(xvec) + dx / 2)
        ax.set_ylim(len(ymap) - 0.5, -0.5)

    pp = PatchCollection(recs)
    # ax.clear()
    col = ax.add_collection(pp)
    pp.set_edgecolor(None)
    pp.set_linewidths(0.0)
    if 'alpha' in kwargs:
        pp.set_alpha(kwargs['alpha'])

    if circular:
        pp.set_edgecolor('black')
        pp.set_linewidths(0.1)

    cmap = pg.mplviewer.cmapFromName(**kwargs)
    if kwargs.pop('markOutside', False):
        cmap.set_bad('grey')
        cmap.set_under('darkgrey')
        cmap.set_over('lightgrey')
        cmap.set_bad('black')
    pp.set_cmap(cmap)

    pp.set_norm(norm)
    pp.set_array(vals)
    pp.set_clim(cMin, cMax)

    updateAxes_(ax)
    cbar = kwargs.pop('colorBar', True)
    ori = kwargs.pop('orientation', 'horizontal')
    if cbar in ['horizontal', 'vertical']:
        ori = cbar
        cbar = True

    if cbar is True:  # not for cbar=1, which is really confusing!
        cbar = pg.mplviewer.createColorBar(col,
                                           cMin=cMin,
                                           cMax=cMax,
                                           nLevs=5,
                                           label=label,
                                           orientation=ori)
    elif cbar is not False:
        # .. cbar is an already existing cbar .. so we update its values
        pg.mplviewer.updateColorBar(cbar,
                                    cMin=cMin,
                                    cMax=cMax,
                                    nLevs=5,
                                    label=label)

    updateAxes_(ax)
    return ax, cbar, ymap
Esempio n. 46
0
def plot_on_image(image,
                  background_map,
                  ra_grid,
                  dec_grid,
                  mask=None,
                  title=None):
    """
    Plot the density grid as a collection of colored rectangles layered
    over the given fits image.

    Parameters
    ----------
    image: imageHDU
        the fits image, which should include a WCS

    background_map: 2d ndarray
        the values for the bins (indexed on [ra_index,dec_index])

    ra_grid: list of float
        edges of the right ascension bins in degrees

    dec_grid: list of float
        edges of the declination bins in degrees

    mask: 2d ndarray of bool
        Mask that blacks out pixels. Needs to be of same dimensions as
        image.data (indexed on y,x).

    title: str
        title of the resulting image, also used as prefix for the image
        file
    """
    # plot the image
    image_fig, image_ax = plt.subplots()
    imdata = image.data.astype(float)
    f = np.sort(imdata.flatten())
    p = len(f) // 32
    vmin = np.median(f[:p])
    vmax = np.median(f[-p:])
    if mask is not None:
        imdata = np.where(mask, vmin, imdata)
    plt.imshow(imdata, cmap='gray', interpolation='none', vmin=vmin, vmax=vmax)
    plt.colorbar()

    # If we want to rotate the rectangles so they align with the WCS
    rotation = (90. - image.header['ORIENTAT']) * math.pi / 180.

    # Make a rectangular patch for each grid point
    rectangles = []
    values = []
    image_wcs = wcs.WCS(image.header)

    height, width = imdata.shape
    height /= len(dec_grid)
    width /= len(ra_grid)

    for ix in range(len(ra_grid) - 1):
        for iy in range(len(dec_grid) - 1):
            # Current, one to the right, and one upwards. Remember
            # that the x and xup can be different because of the
            # orientation of the WCS.
            [x], [y] = image_wcs.wcs_world2pix([ra_grid[ix]], [dec_grid[iy]],
                                               0)

            rec = Rectangle((x, y), width, height)
            rot = mpl.transforms.Affine2D().rotate_around(x, y, rotation)
            rec.set_transform(rot)
            rectangles.append(rec)
            values.append(background_map[ix, iy])

            patch_col = PatchCollection(rectangles, cmap='viridis')
            patch_col.set_alpha(0.3)

    # Associate the values with the patches. They will be used to
    # pick colors from the colorbar. By passing the patch collection
    # as an argument, the patch collection will be treated as a
    # 'mappable', which works because we did set_array.
    image_ax.add_collection(patch_col)
    patch_col.set_array(np.array(values))
    cb = image_fig.colorbar(patch_col)
    cb.set_alpha(1)
    cb.draw_all()
    plt.title(title)
    image_fig.savefig('{}_overlay.png'.format(title))
Esempio n. 47
0
        continue
    zone = zone[0]
    if zone == 'R':
        color = 'y'
    elif zone == 'C':
        color = 'c'
    elif zone == 'M':
        color = 'darkmagenta'
    elif zone == 'O':
        color = 'ivory'
    elif zone == 'P':
        color = 'forestgreen'

    patches = [mplPolygon(np.array(shape), True)]
    pc = PatchCollection(patches)
    pc.set_alpha(.7)
    pc.set_facecolor(color)
    pc.set_zorder(2)
    pc.set_linewidth(.1)
    pc.set_edgecolor('k')
    ax.add_collection(pc)

#####################################################################
#				Add Roads shapefile to map 							#
#####################################################################
map.readshapefile('RoadCenterlines/RoadCenterlines_2',
                  'RoadCenterlines_2',
                  linewidth=.2)

#####################################################################
#						TRY CODE HERE 								#