Example #1
0
def color_legend(fig,colors, labels,
                 frameon = False,
                 markersize = 40,
                 pos = 0,
                 ax = None):
    n = len(colors)
    patches = []

    if not ax:
        dax = fig.add_axes([0,0,.1,.1])
        dax.set_visible(False)
        trg = fig
    else:
        trg = ax

    for i in range(n):
        c = colors[i]
        l = labels[i]
        patches.append(circ((0,0),1,
                         ec = 'none',
                         fc = c,
                         ))
    
    trg.legend(patches,
               labels,pos,
               frameon = frameon,prop = {'family':'serif'},
               fancybox = True
               )
Example #2
0
def ell2plot(out,S,bbox,colorRange,colorBy='angVel',**kw):
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    import matplotlib.collections, matplotlib.patches
    import numpy
    import math
    import woo.dem
    from minieigen import Vector2, Vector3
    fig=Figure()
    ax=fig.add_subplot(1,1,1)
    canvas=FigureCanvasAgg(fig)
    patches,colors=[],[]
    def flat(v): return Vector2(v[0],v[1])
    for p in S.dem.par:
        if not isinstance(p.shape,woo.dem.Ellipsoid): continue
        # project rotation onto the z-axis
        rotAxis,rotAngle=p.ori.toAxisAngle()
        if abs(rotAxis.dot(Vector3.UnitZ))<0.99: raise ValueError("Ellipsoid rotated other than along the z-axis?")
        if rotAxis.dot(Vector3.UnitZ)<0: rotAngle*=-1 # rotation along -z = - rotation along +z 
        patches.append(matplotlib.patches.Ellipse(xy=flat(p.pos),width=2*p.shape.semiAxes[0],height=2*p.shape.semiAxes[1],angle=math.degrees(rotAngle)))
        if colorBy=='angVel': colors.append(abs(p.angVel[2]))
        elif colorBy=='vel': colors.append(p.vel[2])
        else: raise ValueError('colorBy must be one of "angVel", "vel" (not %s)'%colorBy)
    coll=matplotlib.collections.PatchCollection(patches,cmap=matplotlib.cm.jet,alpha=.9)
    coll.set_array(numpy.array(colors))
    ax.add_collection(coll)
    # cbar=fig.colorbar(coll)
    coll.set_clim(*colorRange)
    ax.grid(True)
    ax.set_xlim(bbox[0][0],bbox[1][0])
    ax.set_ylim(bbox[0][1],bbox[1][1])
    ax.set_aspect('equal')
    fig.savefig(out)
    return max(colors)
Example #3
0
def get_patch_collection(modelgrid, head, conc, cmap='jet', zorder=None):
    # create patches for each cell
    import matplotlib.patches
    import matplotlib.collections
    xv, yv, zv = modelgrid.xyzvertices
    botm = modelgrid.botm
    patches = []
    for k in range(modelgrid.nlay):
        for j in range(modelgrid.ncol):
            x0 = xv[0, j]
            x1 = xv[0, j + 1]
            z0 = zv[k, 0, j]
            z0 = min(z0, head[k, 0, j])
            z0 = max(z0, botm[k, 0, j])
            z1 = zv[k + 1, 0, j]
            poly = [[x0, z0], [x1, z0], [x1, z1], [x0, z1], [x0, z0]]
            patch = matplotlib.patches.Polygon(poly,
                                               closed=True,
                                               edgecolor='k',
                                               facecolor='red')
            patches.append(patch)
    pc = matplotlib.collections.PatchCollection(patches,
                                                cmap=cmap,
                                                zorder=zorder)
    pc.set_array(conc.flatten())
    return pc
Example #4
0
File: ell2d.py Project: sjl767/woo
def ell2plot(out,S,bbox,colorRange,colorBy='angVel',**kw):
    from matplotlib.figure import Figure
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    import matplotlib.collections, matplotlib.patches
    import numpy
    import math
    import woo.dem
    from minieigen import Vector2, Vector3
    fig=Figure()
    ax=fig.add_subplot(1,1,1)
    canvas=FigureCanvasAgg(fig)
    patches,colors=[],[]
    def flat(v): return Vector2(v[0],v[1])
    for p in S.dem.par:
        if not isinstance(p.shape,woo.dem.Ellipsoid): continue
        # project rotation onto the z-axis
        rotAxis,rotAngle=p.ori.toAxisAngle()
        if abs(rotAxis.dot(Vector3.UnitZ))<0.99: raise ValueError("Ellipsoid rotated other than along the z-axis?")
        if rotAxis.dot(Vector3.UnitZ)<0: rotAngle*=-1 # rotation along -z = - rotation along +z 
        patches.append(matplotlib.patches.Ellipse(xy=flat(p.pos),width=2*p.shape.semiAxes[0],height=2*p.shape.semiAxes[1],angle=math.degrees(rotAngle)))
        if colorBy=='angVel': colors.append(abs(p.angVel[2]))
        elif colorBy=='vel': colors.append(p.vel[2])
        else: raise ValueError('colorBy must be one of "angVel", "vel" (not %s)'%colorBy)
    coll=matplotlib.collections.PatchCollection(patches,cmap=matplotlib.cm.jet,alpha=.9)
    coll.set_array(numpy.array(colors))
    ax.add_collection(coll)
    # cbar=fig.colorbar(coll)
    coll.set_clim(*colorRange)
    ax.grid(True)
    ax.set_xlim(bbox[0][0],bbox[1][0])
    ax.set_ylim(bbox[0][1],bbox[1][1])
    ax.set_aspect('equal')
    fig.savefig(out)
    return max(colors)
def get_legend_patches(dx, colordict, n=10):
    # n = len(dx.sum()) # number of sorted patches you want for the header
    top10 = dx.sum().sort_values(ascending=False).head(n)
    patches = []
    for name, score in top10.iteritems():
        patches.append(mpatches.Patch(color=colordict[name], label=name))
    return patches
Example #6
0
def _makeAssemPatches(core):
    """Return a list of assembly shaped patch for each assembly."""
    patches = []

    if isinstance(core.spatialGrid, grids.HexGrid):
        nSides = 6
    elif isinstance(core.spatialGrid, grids.ThetaRZGrid):
        raise TypeError(
            "This plot function is not currently supported for ThetaRZGrid grids."
        )
    else:
        nSides = 4

    pitch = core.getAssemblyPitch()
    for a in core:
        x, y, _ = a.spatialLocator.getLocalCoordinates()
        if nSides == 6:
            assemPatch = matplotlib.patches.RegularPolygon(
                (x, y),
                nSides,
                pitch / math.sqrt(3),
                orientation=math.pi / 2.0)
        elif nSides == 4:
            # for rectangle x, y is defined as sides instead of center
            assemPatch = matplotlib.patches.Rectangle(
                (x - pitch[0] / 2, y - pitch[1] / 2), *pitch)
        else:
            raise ValueError(f"Unexpected number of sides: {nSides}.")
        patches.append(assemPatch)
    return patches
Example #7
0
def patches_from_grid(grid):
    """Returns a list of `matplotlib` `patches` from the passed
    :class:`MaskedGrid` object.  Typical usage:

        pc = matplotlib.collections.PatchCollection(patches_from_grid(grid))
        fig, ax = plt.subplots()
        ax.add_collection(pc)

    This will be slow if there are a large number of grid cells.

    :param grid: A :class:`MaskedGrid` instace.

    :return: A list of patches.
    """
    height, width = grid.mask.shape
    patches = []
    for y in range(height):
        yy = y * grid.ysize + grid.yoffset
        for x in range(width):
            if grid.is_valid(x, y):
                xx = x * grid.xsize + grid.xoffset
                patches.append(
                    matplotlib.patches.Rectangle((xx, yy), grid.xsize,
                                                 grid.ysize))
    return patches
Example #8
0
def plot_bboxes(img,
                bbox_dict,
                colormap,
                alpha=0.5,
                ax=None,
                figsize=None,
                show_axs=False):
    if not ax:
        fig, ax = plt.subplots(figsize=figsize)
    show_img(img, ax, figsize, show_axs)
    patches = []
    colors = []

    labels = list(bbox_dict.keys())
    # st()
    for l in labels:
        color = colormap[l]
        for poly in bbox_dict[l]:
            if poly:
                # st()
                p = np.array(convert_poly(poly, img.shape))
                patches.append(Polygon(p, True))
            colors.append(color)
    patch_collection = PatchCollection(patches, alpha=alpha)
    patch_collection.set_array(np.array(colors))
    ax.add_collection(patch_collection)
Example #9
0
    def draw_graph(self):
        ax = plt.subplot()
        patches = []
        colors = self._create_color()

        for center in self.centers_dic.values():
            b = True
            polygon = []
            for vertex in center.corners:
                if vertex.position[0] < self.bounding_box[0] - 10 or vertex.position[0] > self.bounding_box[1] + 10 or \
                   vertex.position[1] < self.bounding_box[2] - 10 or vertex.position[1] > self.bounding_box[3] + 10:
                    if vertex.is_water:
                        b = False
                        break
                polygon.append(vertex.position)

            if b:
                color = '#AADAFF' if center.is_water else colors[
                    center.cluster][int(center.elevation)]
                patches.append(matplotlib.patches.Polygon(polygon,
                                                          color=color))

        p = PatchCollection(patches, alpha=0.8, match_original=True)
        ax.add_collection(p)
        plt.xlim(-80, 80)
        plt.ylim(-80, 80)
        plt.show()
Example #10
0
def plot_polygons_lines_and_points(blue_polygons=None,
                                   red_polygons=None,
                                   yellow_polygon=None,
                                   additional_polygons=None):
    patches = [] if additional_polygons is None else additional_polygons
    if red_polygons is not None:
        patches += [_get_patch(polygon, "red") for polygon in red_polygons]

    if blue_polygons is not None:
        patches += [_get_patch(polygon, "blue") for polygon in blue_polygons]

    if yellow_polygon is not None:
        polygon = matplotlib.patches.Polygon(yellow_polygon,
                                             True,
                                             alpha=0.4,
                                             color="yellow")
        patches.append(polygon)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.axis("auto")

    for patch in patches:
        ax.add_patch(patch)

    plt.axis("equal")

    plt.show()
Example #11
0
def draw_polygons(polygons):
    patches = []
    for (lons, lats) in polygons:
        x, y = city_map(lons, lats)
        xy = zip(x, y)
        patches.append(matplotlib.patches.Polygon(xy, color='k'))
    p = matplotlib.collections.PatchCollection(patches, alpha=0.7)
    plt.gca().add_collection(p)
Example #12
0
 def animate(i):
     patches = []
     if i>0:
         for j in range(len(history_agents[i-1])):
             history_agents[i-1][j].set_visible(False)
     for j in range(len(history_agents[i])):
         history_agents[i][j].set_visible(True)
         patches.append(ax.add_patch(history_agents[i][j]))
     return patches
Example #13
0
def plot_lag(x, y, n, group=0, lag=0, title=''):
    """Scatter plot of group-th n elements of data and lag*n elements previous
    
    Parameters
    ----------
    x : independent variable
    
    y : dependent variable
    
    n : number of elements to plot in each batch
    
    group : index of final batch of data
    
    lag : number of batches before group-th to be plotted
    
    Output
    ------
    Scatterplot with labelled legend
    """

    blues = [
        '#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6',
        '#2171b5', '#08519c', '#08306b'
    ]

    l = int(lag)
    if l < 0:
        print('lag **kwarg should be an int between 0 and 8')
        raise
    if l > 8:
        print('max recommended lag **kwarg is 8')
        l = 8
    fig, axs = matplotlib.pyplot.subplots()
    data_x = x[group * n:(group + 1) * n]
    data_y = y[group * n:(group + 1) * n]
    axs.scatter(data_x, data_y, color=blues[-1])
    axs.set_xlabel('x')
    axs.set_ylabel('y')
    for i in range(l):  #Plot lagged groups in lighter color
        data_x = x[(group - i - 1) * n:(group - i) * n]
        data_y = y[(group - i - 1) * n:(group - i) * n]
        axs.scatter(data_x, data_y, color=blues[-2 - i])

    patches = []
    for i in range(l + 1):  #Create legend patches
        patches.append(
            matplotlib.patches.Patch(
                color=blues[-1 - i],
                label='{0} [{1}:{2}], {3} [{1}:{2}]'.format(
                    'x', (group - i) * n, (group - i + 1) * n, 'y')))
    matplotlib.pyplot.legend(handles=patches,
                             bbox_to_anchor=(1.05, 1),
                             loc=2,
                             borderaxespad=0)
    matplotlib.pyplot.title(title)
    matplotlib.pyplot.show()
def show_image(imageId=None, img=None, width=18, addMask=True, markCars=False):

    if imageId is not None:
        # Read Image Using OpenCV lib
        img_path = os.path.join(DATASET_DIR, 'train_images',
                                '{}.{}'.format(imageId, 'jpg'))
        img = cv2.imread(img_path, 1)
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

    dimensions = img.shape
    heightImage, widthImage, channels = dimensions
    # Optionally Show Dimension
    # print(dimensions)

    # Calculate Aspect Ratio Maintained Height
    width = min(widthImage, width)
    height = width * (heightImage / widthImage)
    size = (width, height)

    # Draw Image in SubPlot
    fig, ax = plt.subplots(figsize=size)
    ax.imshow(img / 255)
    ax.set_title(imageId)

    if (addMask):

        # Get corresponding mask
        mask_path = os.path.join(DATASET_DIR, 'train_masks',
                                 '{}.{}'.format(imageId, 'jpg'))
        mask = cv2.imread(mask_path, 0)

        patches = []
        _, contours, _ = cv2.findContours(mask, cv2.RETR_TREE,
                                          cv2.CHAIN_APPROX_SIMPLE)
        for contour in contours:
            poly_patch = Polygon(contour.reshape(-1, 2),
                                 closed=True,
                                 linewidth=2,
                                 edgecolor='black',
                                 facecolor='black',
                                 fill=True)
            patches.append(poly_patch)
        p = PatchCollection(patches,
                            match_original=True,
                            cmap=matplotlib.cm.jet,
                            alpha=0.3)

        ax.add_collection(p)

    #ax.set_xticklabels([])
    #ax.set_yticklabels([])

    if (markCars is not False):
        plt.scatter(*get_img_coords(markCars), color='red', s=100)

    plt.show()
Example #15
0
def plot_bivariates(stats, show_hull=False):
    current_palette = sns.utils.get_color_cycle()
    n_colors = stats['rider id'].max() + 1

    if n_colors <= len(current_palette):
        colors = sns.color_palette(n_colors=n_colors)
    else:
        colors = sns.husl_palette(n_colors, l=.7)

    riders = np.unique(stats['rider id'])
    proxy_lines = []
    for rid in riders:
        c = colors[rid]
        l = matplotlib.lines.Line2D([], [],
                linestyle='', marker='o', markerfacecolor=c,
                label='rider {}'.format(rid))
        proxy_lines.append(l)

    grids = []
    for yf in yfields:
        name, unit = yf
        x = stats['linregress slope']
        y = stats[name]

        g = sns.JointGrid(x=x, y=y)
        g.plot_marginals(sns.distplot, kde=False,
                         color=sns.xkcd_palette(['charcoal'])[0])
        g.plot_joint(plt.scatter,
                     color=list(map(lambda x: colors[x], stats['rider id'])))
        g.ax_joint.legend(handles=proxy_lines, ncol=2, title=
                'pearson r = {:.2g}, p = {:.2g}'.format(
                    *scipy.stats.pearsonr(x, y)))
        g.set_axis_labels('slope [m/s^2]', '{} [{}]'.format(yf, unit))
        g.fig.suptitle('scatterplots of braking events')
        g.fig.set_size_inches(12.76, 7.19) # fix size for pdf save

        if show_hull:
            patches = []
            for rid in riders:
                index = stats['rider id'] == rid
                m = stats[index][['linregress slope', name]].copy()
                X = m.view(np.float64).reshape(m.shape[0], -1)

                hull = scipy.spatial.ConvexHull(X)
                polygon = matplotlib.patches.Polygon(X[hull.vertices, :],
                                                     closed=True,
                                                     zorder=1,
                                                     facecolor=colors[rid])
                patches.append(polygon)
            p = matplotlib.collections.PatchCollection(patches,
                                                       match_original=True,
                                                       alpha=0.05)
            g.ax_joint.add_collection(p)

        grids.append(g)
    return grids
Example #16
0
    def draw(self, ax, outlines):
        for outline in outlines:
            assert outline.shape[1] == 2

        patches = []
        for outline in outlines:
            polygon = matplotlib.patches.Polygon(
                outline[:, :2], color=self.color, facecolor=self.color, alpha=self.alpha)
            patches.append(polygon)
        ax.add_collection(matplotlib.collections.PatchCollection(patches, match_original=True))
Example #17
0
 def plot_agents_xy(self, figure=None):
     if figure is None:
         figure = plt.gcf()
     patches = []
     worldstate = self.worldstate
     for i, _ in enumerate(worldstate.get_agents()):
         patch = self.get_viz_agent_patch(i)
         figure.gca().add_artist(patch)
         patches.append(patch)
     return patches
Example #18
0
    def draw_polygon(ax, outlines, *, alpha=0.5, color='orange'):
        for outline in outlines:
            assert outline.shape[1] == 2

        patches = []
        for outline in outlines:
            polygon = matplotlib.patches.Polygon(
                outline[:, :2], color=color, facecolor=color, alpha=alpha)
            patches.append(polygon)
        ax.add_collection(matplotlib.collections.PatchCollection(patches, match_original=True))
Example #19
0
def to_rectangle(boxes,facecolor=(0,1,0)):
    if(type(boxes)!=list):
        boxes=[boxes]
    patches=[]
    for box_i in boxes:
        if(type(box_i)!=convex.Box):
            box_i=box_i.get_box()
            print(box_i)
        rect_i=matplotlib.patches.Rectangle(*box_i.as_point(),facecolor=facecolor)
        patches.append(rect_i)
    return PatchCollection(patches, cmap=matplotlib.cm.jet, alpha=0.4)
Example #20
0
def true_footprint(ax, blockname):
    # with open('/Users/bannisterm/Dropbox/OSSOS/ossos-pipeline/src/ossos/core/ossos/planning/triplet_and_processing_notes/T_15B_discovery_expnums.txt') as infile:
    #     for line in infile.readlines():

    # Trying a test field on T block only
    ra = 7.55171
    dec = 4.52681

    print('plotting footprint')
    fill = False
    print(ra, dec)
    patches = []
    patches.append(
        matplotlib.patches.Rectangle(
            xy=(math.degrees(ra) - camera_width_40 / 2.0,
                math.degrees(dec) - camera_height / 4.0),
            width=camera_width_40,
            height=camera_height / 2.0,
            color='b',
            zorder=0,
            lw=0.5,
            fill=fill,
            alpha=0.3))
    ax.add_artist(
        matplotlib.patches.Rectangle(
            xy=(math.degrees(ra) - camera_width_36 / 2.0,
                math.degrees(dec) - camera_height / 2.0),
            height=camera_height / 4.0,
            width=camera_width_36,
            color='b',
            zorder=0,
            lw=0.5,
            fill=fill,
            alpha=0.3))
    ax.add_artist(
        matplotlib.patches.Rectangle(
            xy=(math.degrees(ra) - camera_width_36 / 2.0,
                math.degrees(dec) + camera_height / 4.0),
            height=camera_height / 4.0,
            width=camera_width_36,
            color='b',
            zorder=0,
            lw=0.5,
            fill=fill,
            alpha=0.3))

    # WHERE IS MY FIELD whyyyyy
    collection = PatchCollection(patches)
    ax.add_collection(collection)

    return ax
Example #21
0
def plot_group_histories(root,
                         history_values,
                         title,
                         xlabel,
                         ylabel,
                         max_nb_plots_per_group=5,
                         colors=utilities.make_unique_colors_f()):
    """
    Plot groups of histories
    :param root: the directory where the plot will be exported
    :param history_values: a map of list of list of (epoch, value)
    :param title: the title of the graph
    :param xlabel: the x label
    :param ylabel: the y label
    :param max_nb_plots_per_group: the maximum number of plots per group
    :param colors: the colors to be used
    """
    if len(history_values) == 0:
        return
    assert isinstance(
        history_values,
        collections.Mapping), 'must be a dictionary of lists of values'
    assert isinstance(next(iter(history_values.items()))[1],
                      list), 'must be a dictionary of lists of values'
    assert len(history_values) <= len(colors), 'not enough colors!'

    fig = plt.figure()
    ax = fig.add_subplot(111)
    patches = []
    for group_index, (name, values_list) in enumerate(history_values.items()):
        color = colors[group_index]
        patches.append(matplotlib.patches.Patch(color=color, label=name))

        for list_index, values in enumerate(values_list):
            i = []
            v = []
            for index, value in values:
                i.append(index)
                v.append(value)

            ax.plot(i, v, color=color)
            if index >= max_nb_plots_per_group:
                break

    ax.set_ylabel(ylabel)
    ax.set_xlabel(xlabel)
    ax.set_title(title)
    plt.legend(handles=patches, loc='upper right')
    fig_tight_layout(fig)
    export_figure(root, title)
    plt.close()
Example #22
0
def plot_occupancy3(occupancy,
                    offset=0.0,
                    animals=None,
                    cm=None,
                    n_cages=None,
                    n_animals=None,
                    label_left=None):
    if cm is None:
        cm = default_cm
    # [enter, exit, cage, animal]

    # give each animal a color
    if animals is None:
        aids = sorted(numpy.unique(occupancy[:, 3]))
    else:
        aids = animals
    if n_animals is None:
        n_aids = len(aids)
    else:
        n_aids = n_animals
    dy = 1. / n_aids
    ainfo = {
        aid: (cm(i / (n_aids - 1.)), i * dy)
        for (i, aid) in enumerate(aids)
    }

    # find # of cages
    if n_cages is None:
        n_cages = len(numpy.unique(occupancy[:, 2]))

    bar_height = 1. / n_aids
    patches = []
    dy = 1. / n_aids
    xmin, xmax = occupancy[0][:2]
    ax = pylab.gca()
    for o in occupancy:
        (t0, t1, cage, animal) = o[:4]
        c, ady = ainfo[animal]
        p = matplotlib.patches.Rectangle((t0, cage + ady),
                                         t1 - t0,
                                         dy,
                                         color=c)
        patches.append(p)
        ax.add_patch(p)
        xmin = min(xmin, t0)
        xmax = max(xmax, t1)
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(0, n_cages)
    return patches
def bestfit(x_train,
            y_train,
            x_test,
            y_test,
            CI,
            x_label,
            y_label,
            filename=None):

    opacity = 0.8
    mpl.rcParams['axes.linewidth'] = 2.0
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    plt.grid()
    ax.set_axis_bgcolor('silver')

    #plt.fill_between(xo, bottom, top, facecolor='crimson', alpha=0.5)
    patches = []
    for i in range(0, len(y_test) - 1):
        xy = np.array([[x_test[i, 0], y_test[i, 0] - CI[i]],
                       [x_test[i, 0], y_test[i, 0] + CI[i]],
                       [x_test[i + 1, 0], y_test[i + 1, 0] + CI[i, 0]],
                       [x_test[i + 1, 0], y_test[i + 1, 0] - CI[i, 0]]])
        #xy = np.random.rand(4,2)
        polygon = Polygon(xy, closed=False)
        patches.append(polygon)
    p = PatchCollection(patches, alpha=0.2, edgecolor='none', facecolor='teal')
    ax.add_collection(p)
    plt.scatter(x_train,
                y_train,
                marker='o',
                s=120,
                alpha=opacity,
                color='orangered',
                linewidth=1.5)
    plt.plot(x_test, y_test, linestyle='-', linewidth=2, color='steelblue')
    ax.set_axisbelow(True)
    adjust_spines(ax, ['left', 'bottom'])
    plt.xlabel(x_label, fontsize=13)
    plt.ylabel(y_label, fontsize=13)
    plt.grid(b=True, which='major', color='w', linestyle='-', linewidth=2)
    plt.grid(b=True, which='minor', color='w', linestyle='-', linewidth=2)
    plt.xticks(fontsize=13)
    plt.yticks(fontsize=13)
    plt.tight_layout()
    if filename is not None:
        plt.savefig(filename, dpi=300, bbox_inches='tight')
    else:
        plt.show()
Example #24
0
def read_fiducial(fn):
    patches = []

    tree = ET.parse(fn)
    root = tree.getroot()
    for child in root:
        if child.tag != "Quadrilateral":
            raise ValueError
        babys = [baby for baby in child]

        vs = [float(x) for x in babys[0].text.split()]
        ws = [float(x) for x in babys[1].text.split()]

        points = zip(vs, ws)
        patches.append(points)
        quads.append(points)
    return patches
Example #25
0
def split_image_in_patches(img_path, patch_size: int):
    img = np.array(Image.open(img_path).convert('RGB'))
    h, w, _ = img.shape
    rows = h // patch_size
    cols = w // patch_size
    patches = list()
    for i in range(0, rows):
        for j in range(0, cols):
            ymin = i * h // rows
            ymax = i * h // rows + h // rows
            xmin = j * w // cols
            xmax = j * w // cols + w // cols
            patch = img[ymin:ymax, xmin:xmax]
            patch = cv2.resize(patch, (patch_size, patch_size),
                               interpolation=cv2.INTER_CUBIC)
            patches.append(patch)
    return patches
Example #26
0
def patches_from_geometry(geo, **kwargs):
    """Convert an iterable of geometry to `matplotlib` patches.
    
    :param geo: An iterable of geometry items.  If `descartes` cannot parse
      an item, it is ignored.
    :param **kwargs: Any key-word arguments to forward on to the `patch`
      constructor.
      
    :return: A list of `matplotlib.patches.Patch` objects.
    """
    patches = []
    for x in geo:
        try:
            patches.append(descartes.PolygonPatch(x, **kwargs))
        except:
            pass
    return patches
Example #27
0
def match_patches(patches, t, lefts, rights, tolerance):
    """
    Given a list of lists of patches ("patches"), append each of the new patches
    defined by t, lefts, rights to the closest-matching ones, possibly creating
    new lists of patches.
    """
    new_matches = [[] for _ in lefts]
    patch_matches = [[] for _ in patches]
    for j, (l, r) in enumerate(zip(lefts, rights)):
        for k, (a, u) in enumerate(patches):
            if a:
                ll = u[-1][1]
                lr = u[-1][2]
                dx = np.abs(l - ll) + np.abs(r - lr)
                if dx <= tolerance:
                    new_matches[j].append((dx, ll - lr, k))
                    patch_matches[k].append((dx, l - r, j))
        new_matches[j].sort()
    matches = np.repeat(-1, len(new_matches))
    for j, m in enumerate(new_matches):
        if len(m) > 0:
            u = m.pop(0)
            matches[j] = u[-1]
    num_matches = np.bincount(matches + 1, minlength=len(patches) + 1)[1:]
    while np.any(num_matches > 1):
        for k in np.where(num_matches > 1)[0]:
            xm = [x for x in patch_matches[k] if matches[x[2]] == k]
            xm.sort()
            for _, _, j in xm[1:]:
                if len(new_matches[j]) > 0:
                    _, _, k = new_matches[j].pop(0)
                    matches[j] = k
                else:
                    matches[j] = -1
        num_matches = np.bincount(matches + 1, minlength=len(patches) + 1)[1:]
    for j, k in enumerate(matches):
        if k == -1:
            patches.append([True, [(t, lefts[j], rights[j])]])
        else:
            patches[k][1].append((t, lefts[j], rights[j]))
    for k in np.where(num_matches == 0)[0]:
        patches[k][0] = False
Example #28
0
    def get_patches(self,offsets=(0,0)):
        """Run through the interactions edges to create a Matplotlib patch for each of them

        Args:
            offsets (float,float): Size 2 tuple containing the offset to leave between the edges an the node1 and node2.

        Returns:
            [Matplotlib.Patches]: list of Matplotlib patches
        """

        patches = []
        new_iter = sorted(self.edges.items(), key=lambda a: 1-a[1].receiveEdge)

        for i,edge in new_iter:
            if self.isAuto:
                ## Distribute the arrows symmetrically about the node1-node2 axis
                if self.node1==2:
                    patches.append(edge.get_autoPatch(offsets=offsets,num=i))
                else:
                    patches.append(edge.get_autoPatch(offsets=offsets,num=i))
            else:
                ## Distribute the arrows symmetrically about the node1-node2 axis
                angle = ((1-self.numberEdges)*0.5 + i)*0.4
                if edge.nodeFrom.index==self.node2:
                    angle*=-1
                patches.append(edge.get_patch(offsets=offsets,angle=angle))
        return patches
Example #29
0
def get_legend_patches(labels, just_rect=False, just_lines= False, linecolor= 'black', linewidth=0, marker ='o', 
                           markeredgecolor='black', markeredgewidth=1, 
                           markerfacecolor = 'white', markersize=20, linestyle= '-',
                       rectedgecolor='black', rectfacecolor = 'white', rectlinewidth=1, hatch = '', alpha = 1):
                        
    """Function to return a list of patches with any combination of markeredgewidths, facecolors, markersizes, edgecolors- only for points and other markers- lines with or without points
    
    if lines = True- return patches of just lines from colors_lines, and labels_lines
    to insert spaces in a legend- pass a list with linewidths or markersize= 0 and label = '' for those elements
    make a legend by ax.legend(handles =patches) and adjust as desired
    
    """

    patches = []
    num_patches = len(labels)
  
    props = [markeredgecolor, markerfacecolor, markeredgewidth, markersize, marker, 
             linewidth, linecolor, linestyle, rectedgecolor, rectfacecolor,  rectlinewidth, hatch, alpha]
    prop_names = ['markeredgecolor', 'markerfacecolor', 'markeredgewidth', 'markersize', 'marker', 
                  'linewidth', 'linecolor', 'linestyle','rectedgecolor', 'rectfacecolor', 
                  'rectlinewidth', 'hatch', 'alpha']
    

    for i, z in enumerate(props):
        if hasattr(z, '__iter__'): 
            assert len(z) == num_patches, 'incorrect length of list of {}'.format(prop_names[i])

        else:
            # duplicate the default into a list of length num patches- simplify patch list building below
            z = [z for l in range(num_patches)]
            props[i] = z

    (markeredgecolor, markerfacecolor, markeredgewidth, markersize, 
     marker, linewidth, linecolor, linestyle, rectedgecolor, rectfacecolor,  
     rectlinewidth, hatch, alpha) = props
    
    
    if just_lines:
        for i, l in enumerate(labels):
            # plot a line with no markers
            p= plt.Line2D((0,0),(0,0), linewidth=linewidth[i], color=linecolor[i], label = l, linestyle=linestyle[i])

            patches.append(p)     
    
    elif just_rect:
        for i, l in enumerate(labels):
            # plot rects not lines
            p = plt.Rectangle((0, 0), 0, 0, fc= rectfacecolor[i], ec = rectedgecolor[i], 
                              lw = rectlinewidth[i], linestyle = linestyle[i], hatch=hatch[i], label = l, alpha = alpha[i])
            patches.append(p)
    else:    
        for i, l in enumerate(labels):
            # plot lines/markers- default to no line just marker
            p= plt.Line2D((0,0),(0,0), linewidth= linewidth[i], color= linecolor[i], 
                          markeredgecolor = markeredgecolor[i],
                          markeredgewidth= markeredgewidth[i], markerfacecolor = markerfacecolor[i], 
                          markersize=markersize[i], label= l, marker= marker[i])
            patches.append(p)
        
    return patches
Example #30
0
def plot_lag(x, y, n, group=0, lag=0):
    """Scatter plot of group-th n elements of data and lag * n elements previous"""
    import matplotlib.pyplot
    import matplotlib.patches

    blues = [
        '#f7fbff', '#deebf7', '#c6dbef', '#9ecae1', '#6baed6', '#4292c6',
        '#2171b5', '#08519c', '#08306b'
    ]

    l = lag
    if l < 0:
        print('lag **kwarg should be an int between 0 and 8')
        raise
    if l > 8:
        print('max recommended lag **kwarg is 8')
        l = 8
    fig, axs = matplotlib.pyplot.subplots()
    data_x = x[group * n:(group + 1) * n]
    data_y = y[group * n:(group + 1) * n]
    axs.scatter(data_x, data_y, color=blues[-1])
    axs.set_xlabel('x')
    axs.set_ylabel('y')
    for i in range(l):  #Plot lagged groups in lighter color
        data_x = x[(group - i - 1) * n:(group - i) * n]
        data_y = y[(group - i - 1) * n:(group - i) * n]
        axs.scatter(data_x, data_y, color=blues[-1 - i])

    patches = []
    for i in range(l + 1):  #Create legend patches
        patches.append(
            matplotlib.patches.Patch(
                color=blues[-1 - i],
                label='{0} [{1}:{2}], {3} [{1}:{2}]'.format(
                    'x', (group - i) * n, (group - i + 1) * n, 'y')))
    matplotlib.pyplot.legend(handles=patches,
                             bbox_to_anchor=(1.05, 1),
                             loc=2,
                             borderaxespad=0)
def createImage(i):
	if not pause:
		ax.cla()
		plotBoard = [[0 for x in range(15)] for x in range(15)]

		for i in range(15):
			for j in range(15):
				plotBoard[i][j] = (board[i][j].getA(),board[i][j].getB(), 1)

		patches = []
		for x in range(0,15):
			for y in range(0,15):
				patches.append(ax.add_patch( plt.Rectangle((x,y),1,1,color=plotBoard[x][y])))
		playGame(board)
		updateProbability(board, profitSums)
		invasion(board, .005)
		return patches
	else:
		for i in range(15):
			for j in range(15):
				board[i][j].printPair()
			print
		exit()
Example #32
0
def plot_coverage(X, Y,
                  rotation=None, translation=None, max_distance=1e4, 
                  ax=None, figsize=(30,20), cmap=cm.jet, alpha=0.4):
    '''Plot the coverage of the projection of multiple images in a single axis.

    Plot the outline of lists of real-world x and y coordinate
    matrices. The resulting composition can be rotated and
    translated seperately.

    Points projected at infinite distance can be ignored by
    specifying a maximum distance.

    Parameters
    ----------
    X : list of np.ndarrays
        List of NxM matrix containing real-world x-coordinates
    Y : list of np.ndarrays
        List of NxM matrix containing real-world y-coordinates
    rotation : float, optional
        Rotation angle in degrees
    translation : list or tuple, optional
        2-tuple or list with x and y translation distances
    max_distance : float, optional
        Maximum distance from origin to be included in the plot.
        Larger numbers are considered to be beyond the horizon.
    ax : matplotlib.axes.AxesSubplot, optional
        Axis object used for plotting
    figsize : tuple, optional
        2-tuple or list containing figure dimensions
    cmap : matplotlib.colors.Colormap, optional
        Colormap to determine colors for individual patches
    alpha : float, optional
        Alpha value for patches

    Returns
    -------
    matplotlib.figure.Figure
        Figure object containing axis object
    matplotlib.axes.AxesSubplot
        Axis object containing plot
    '''

    # create figure
    if ax is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        fig = ax.figure

    xl = [0,0]
    yl = [0,0]

    # loop over images
    patches = []
    for x, y in zip(X, Y):

        # find horizon based on max_distance
        o = find_horizon_offset(x, y, max_distance=max_distance)

        # rotate to world coordinate system
        x, y = rotate_translate(x, y, rotation=rotation, translation=translation)

        xl[0] = np.min((np.min(x), xl[0]))
        xl[1] = np.max((np.max(x), xl[1]))
        yl[0] = np.min((np.min(y), yl[0]))
        yl[1] = np.max((np.max(y), yl[1]))
        
        # create patch
        xy = np.vstack((x[[o,o,-1,-1],[0,-1,-1,0]], y[[o,o,-1,-1],[0,-1,-1,0]])).T
        patches.append(matplotlib.patches.Polygon(xy, closed=True))
    
    # create collection from patches
    p = matplotlib.collections.PatchCollection(patches, cmap=cmap, alpha=alpha)
    p.set_array(np.array(range(len(X))))

    # plot
    ax.add_collection(p)
    ax.set_xlim(xl)
    ax.set_ylim(yl)
    ax.set_aspect('equal')

    return fig, ax
Example #33
0
def createCountryMap(input,
                     baseColor=None,
                     baseTexture=None,
                     colormap="Greens",
                     countryKey="",
                     dataKey="",
                     filename="",
                     isWorldBank=False,
                     max_year=3000,
                     min_year=0,
                     printMissingCountries=False,
                     range_min=None,
                     range_max=None,
                     transparent=False,
                     yearKey=""):
    """Function to take a CSV file containing country-based data and build a Science on a Sphere texture from it.
    """
    if isinstance(input, pd.DataFrame):
        df = input
    elif isinstance(input, list):
        df = pd.DataFrame()
        df["Country"] = input
        df["Data"] = 1
    elif isinstance(input, str):  # We probably got a CSV filename
        df = getOptimizedDataset(input,
                                 countryKey=countryKey,
                                 dataKey=dataKey,
                                 isWorldBank=isWorldBank,
                                 max_year=max_year,
                                 min_year=min_year,
                                 yearKey=yearKey)
    else:
        print(
            "createCountryMap: Error: You must pass a CSV filename or a pandas DataFrame, or a list of countries"
        )
        return

    # Matplotlib setup
    plt.rcParams["figure.figsize"] = (16, 8)
    plt.clf()
    fig = plt.figure()
    ax = fig.add_subplot(111)

    if baseTexture is not None:
        m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
                    llcrnrlon=-180,urcrnrlon=180,resolution='l')
        m.warpimage(baseTexture)
    elif baseColor is not None:
        fig.patch.set_facecolor(baseColor)

    colormap = cm.get_cmap(colormap)
    if range_min is not None:
        vmin = range_min
    else:
        vmin = np.min(df["Data"])
    if range_max is not None:
        vmax = range_max
    else:
        vmax = np.max(df["Data"])
    norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax)

    # Shapefile setup
    sf = shapefile.Reader("./world_shapefile/world.shp")
    records = sf.records()
    shapes = sf.shapes()
    num_shapes = len(shapes)

    country_names = []
    for i in range(num_shapes):
        country_names.append(records[i][1])
    country_names = np.array(country_names)
    if isWorldBank:
        country_names = countryNameToWorldBank(country_names)
    else:
        country_names = countryNameNormalize(country_names)
        df["Country"] = countryNameNormalize(df["Country"].values)
    if printMissingCountries:
        print("Countries in input data that are not in the map data:")
        print((df[~df["Country"].isin(country_names)])["Country"].values)
        print("Countries in the map data that are not in the input data:")

    # Iterate the country shapes and color them based on the data
    for i in range(num_shapes):
        patches = []
        points = np.array(shapes[i].points)
        parts = shapes[i].parts
        par = list(parts) + [points.shape[0]]

        for j in range(len(parts)):
            patches.append(mpl.patches.Polygon(points[par[j]:par[j + 1]]))

        country = country_names[i]

        try:
            val = float((df[df['Country'] == country])["Data"].values[0])
            base_color = colormap(norm(val))
            if baseTexture is not None:
                color = (base_color[0], base_color[1], base_color[2], 0.5
                         )  # Make patrially transparent
            else:
                color = base_color
            ax.add_collection(
                PatchCollection(patches,
                                facecolor=color,
                                edgecolor='k',
                                linewidths=.1))
        except:
            if printMissingCountries:
                print(country)
            if baseTexture is None:
                color = "gray"
            else:
                color = (0, 0, 0, 0.5)
            ax.add_collection(
                PatchCollection(patches,
                                facecolor=color,
                                edgecolor='k',
                                linewidths=.1))

    fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
    ax.axis("off")
    ax.set_xlim(-180, +180)
    ax.set_ylim(-90, 90)

    if filename != "":
        plt.savefig(filename,
                    dpi=256,
                    facecolor=baseColor,
                    transparent=transparent)
Example #34
0
def draw_regions(borders, count):
    # Um die Anzahlen unterscheiden zu können weisen jeder Anzahl
    # eine Farbe zu.
    # Der Einfachheit halber verwenden wir eine vorgefertige.
    colors = matplotlib.cm.get_cmap('Spectral')
    # Matplotlib kann nur Zahlen zwischen 0.0 und 1.0 darstellen.
    # Daher erzeugen wir uns eine Möglichkeit unsere Zahlen zu
    # "normalisieren".
    normalize = matplotlib.colors.Normalize(vmin=min(count.values()),
                                            vmax=max(count.values()))
    # Aktuell sind die Grenzen der Stadtteile durch Paare aus Längen- und
    # Breitengrad definiert. Matplotlib benötigt jedoch zwei getrennte
    # Listen mit jeweils eine mit allen Längengraden und eine mit allen
    # Breitengraden.
    # Wir transformieren unsere Stadtteilgrenzen entsprechend.
    outlines = {
        name: tuple(
            (
                [lon for lon, lat in polygon],
                [lat for lon, lat in polygon]
            ) for polygon in polygons
        ) for name, polygons in borders.iteritems()
    }

    # Im nächsten Schritt können wir jetzt alle Sammlung aller Grenzpolygone
    # erzeugen um diese auf der Karte zu zeichnen.
    # Wir erzeugen zuerst eine Sammlung, da wir dann in einem einzigen
    # Schritt zeichen können. (Zeichnen dauert lange.)
    # Gleichzeitig wollen wir eine Liste der Schulanzahlen erstellen,
    # damit wir eine Legende neben der Karte anzeigen können.
    patches = []
    counts = []
    for name, polygons in outlines.items():
        # Aus der zuvor generierten Zählung der Stadtteile nehmen wir
        # die Anzahl der Schulen in unsere Zählungsliste auf.
        counts.append(count[name])
        for (lons, lats) in polygons:
            # Die Koordinaten liegen sind nach wie vor in Längen- und
            # Breitengraden angegeben.
            # Um die Karte darstellen zu können, müssen wir diese in
            # einzelne Pixelposition umwandeln. Diese macht die Karte für
            # uns.
            x, y = city_map(lons, lats)
            # Anschließend fügen wir die Koordinaten zum einem Objekt
            # zusammen und erzeugen das Polygon.
            xy = zip(x, y)
            patches.append(matplotlib.patches.Polygon(xy))

    # Nachdem wir alle Polygon erstellt haben fügen wird diese mit den
    # Farb- und Normalisierungsinformationen zusammen.
    p = matplotlib.collections.PatchCollection(patches,
                                               cmap=colors,
                                               norm=normalize,
                                               alpha=0.7)
    # Jeden Polygon in der Sammlung wird jetzt die Anzahl der Schulen
    # zugewiesen. Dies erscheint ein wenig nach doppelter Arbeit, leider
    # scheint es keinen direkteren Weg zu geben.
    p.set_array(np.array(counts))
    # Die Polygone der Stadtteilgrenzen werden in den Plot eingefügt.
    plt.gca().add_collection(p)
    # Dem Plot wird eine Legende hinzugefügt, damit die Farben eine
    # sichtbare Bedeutung erhalten.
    plt.colorbar(p,
                 spacing="proportional",
                 ticks=range(max(counts) + 1),
                 boundaries=range(max(counts) + 1))
    # Setze die karte wieder zurück auf die Stadt, für den Fall dass
    # Punkte außerhalb gezeichnet wurden.
    city_map.set_axes_limits()
    return plt
Example #35
0
def get_offsets_A_B(f, plot=False, interactive=False):
    '''
    Returns the offsets for A and B, so that when offseting, the images do not overlap.  
    Example fits:/scr2/nblago/Projects/SEDM/data/finders/f_b_a_rPTF15fks_r.fits
    '''
    from scipy import stats
    
    image = pf.open(f)
    data = image[0].data.T
    wcs = pywcs.WCS(image[0].header)
    ra, dec = cc.hour2deg(image[0].header['OBJRA'], image[0].header['OBJDEC'] )
    obj = fitsutils.get_par(f, "OBJECT")
    pra, pdec = wcs.wcs_sky2pix(ra, dec, 0)
    
   
    #Get a local image
    xl, yl = np.round(wcs.wcs_sky2pix(ra+30./3600, dec-30./3600, 0), 0)
    xu, yu = np.round(wcs.wcs_sky2pix(ra-30./3600, dec+30./3600, 0), 0)
    imageloc = image[0].data[xl:xu,yu:yl]
    
    bkg = np.median(imageloc)
    perc10 = np.percentile(imageloc, 15)
    perc90 = np.percentile(imageloc, 85)
    mask = (image[0].data > perc10) * (image[0].data < perc90)
    bkg_std = np.std(image[0].data[mask])# mad(image[0].data)
    
        
    linestyles = ['solid' , 'dashed' , 'dashdot' , 'dotted', 'solid']
    
    offsets = np.array([[+3, -4], [+3, +4], [+2, +4], [+2, +2]])

    Noff = len(offsets)
    pvalues = np.zeros((Noff, 2))
    
    if (plot):
        fig, axarr = plt.subplots(2, Noff, sharey='row', figsize=(6*len(offsets), 12))
        axarr = np.array(axarr, ndmin=1)
        

    for i, off in enumerate(offsets):
        ra_off = ra - off[0]/3600.
        dec_off = dec - off[1]/3600.

        ra_off_op = ra + off[0]/3600.
        dec_off_op = dec + off[1]/3600.
        
        prao, pdeco = wcs.wcs_sky2pix(ra+ off[0]/3600., dec + off[1]/3600., 0)
        praosym, pdecosym = wcs.wcs_sky2pix(ra- 2*off[0]/3600., dec - 2*off[1]/3600., 0)

        #Extract sample window to check wether the background matches well.
        #number on samples on each side
        ns = 7
        sample = data[prao-ns:prao+ns, pdeco-ns:pdeco+ns]
        sm = np.median(sample)
        sstd = np.std(sample[(sample<6000)*(sample>0)])
        bkg_prob = np.minimum(1 - stats.norm.cdf(sm, bkg, bkg_std), stats.norm.cdf(sm, bkg, bkg_std))


        #Extract sample window to check wether the background matches well.        
        sample = data[praosym-7:praosym+7, pdecosym-7:pdecosym+7]
        smo = np.median(sample)
        sstdo = np.std(sample)
        bkg_probo = np.minimum(1 - stats.norm.cdf(smo, bkg, bkg_std), stats.norm.cdf(smo, bkg, bkg_std))
        
        pvalues[i] = np.array([bkg_prob, bkg_probo])
        

        if(plot):
            
            #Retrieve the image of the object
            xl, yl = wcs.wcs_sky2pix(ra+20./3600, dec-20./3600, 0)
            xu, yu = wcs.wcs_sky2pix(ra-20./3600, dec+20./3600, 0)
            ifuwin = data[xl:xu,yu:yl]
            
            
            #Retrieve the offset A image of the object
            x0, y0 = wcs.wcs_sky2pix(ra_off+20./3600, dec_off-20./3600, 0)
            x1, y1 = wcs.wcs_sky2pix(ra_off-20./3600, dec_off+20./3600, 0)
            ifuwin1 = data[x0:x1,y1:y0]

            nx, ny = ifuwin1.shape
            
            #print nx,ny, ifuwin1.shape
            
            #Retrieve the offset A image of the object
            x0, y0 = wcs.wcs_sky2pix(ra_off_op+20./3600, dec_off_op-20./3600, 0)
            x1, y1 = wcs.wcs_sky2pix(ra_off_op-20./3600, dec_off_op+20./3600, 0)
            ifuwin2 = data[x0:x0+nx,y1:y1+ny]
            
            #Plot the A and B
            zmin, zmax = zscale.zscale(ifuwin)
            zmin1, zmax1 = zscale.zscale(ifuwin1-ifuwin2)

                       

            axarr[0, i].imshow(ifuwin.T, aspect="auto", vmin=zmin, vmax=zmax, extent=(20,-20,-20,20), alpha=0.5)
            axarr[1, i].imshow(ifuwin1.T-ifuwin2.T, aspect="auto", vmin=zmin1, vmax=zmax1, extent=(20,-20,-20,20), alpha=0.5)#, cmap=matplotlib.cm.RdBu_r)  
            #axarr[1, i].imshow(-1 * ifuwin2.T, aspect="auto", vmin=zmin2, vmax=zmax2, extent=(20,-20,-20,20), alpha=0.5)#, cmap=matplotlib.cm.RdBu_r) 

            axarr[0, i].scatter(0, 0, marker="x", s=20)
            axarr[1, i].scatter(0, 0, marker="x", s=20)

            axarr[0, i].set_xlabel("OBJRA")
            axarr[0, i].set_ylabel("OBJDEC")
            axarr[1, i].set_xlabel("OBJRA")
            axarr[1, i].set_ylabel("OBJDEC")
            axarr[0, i].text(19, 17, "Red stats: $\mu=$%.2f, $\sigma=$%.2f, p-value=%.5f"%(sm, sstd, bkg_prob),  bbox=dict(facecolor='white', alpha=0.5))
            axarr[0, i].text(19, 14, "Blue stats: $\mu=$%.2f, $\sigma=$%.2f, p-value=%.5f"%(smo, sstdo, bkg_probo),  bbox=dict(facecolor='white', alpha=0.5))
            axarr[0, i].text(19, 11, "Background stats: $\mu=$%.2f, $\sigma=$%.2f"%( bkg, bkg_std),  bbox=dict(facecolor='white', alpha=0.5))
        
            #r = plt.Circle((prao-pra, pdeco-pdec), 5, facecolor="none", edgecolor="red", lw=2)
            #b = plt.Circle((praosym-pra, pdecosym-pdec), 5, facecolor="none", edgecolor="blue", lw=2)
            r = plt.Circle((2*off[0], + 2*off[1]), 2, facecolor="none", edgecolor="red", lw=3, ls=linestyles[i])
            b = plt.Circle((-2*off[0], -2*off[1]), 2, facecolor="none", edgecolor="blue", lw=3, ls=linestyles[i])
            
            #Plot the true location of the IFU
            patches = []
            Path = mpath.Path
            path_data = [
                (Path.MOVETO, [20, -12]),
                (Path.LINETO, [20, 20]),
                (Path.LINETO, [-13,  13]),
                (Path.LINETO, [-20 , -18]),
                (Path.CLOSEPOLY, [20, 10])
                ]
            codes, verts = zip(*path_data)
            path = mpath.Path(verts, codes)
            patch = mpatches.PathPatch(path)
            patches.append(patch)
            collection = PatchCollection(patches, cmap=plt.cm.YlGn, alpha=0.2)
            colors = np.linspace(0, 1, len(patches))
            collection.set_array(np.array(colors))

            axarr[0, i].add_artist(r)
            axarr[0, i].add_artist(b)
            axarr[1, i].add_collection(collection)


            plt.suptitle(obj, fontsize=20)
    
    prod = np.prod(pvalues, axis=1)
        
    if (plot and interactive):
        axarr[0, np.argmax(prod)].text(0,0,"WINNER")
        plt.show()
    elif(plot):
        axarr[0, np.argmax(prod)].text(0,0,"WINNER")
        plt.savefig(os.path.join(os.path.dirname(f).replace("raw", "phot"), os.path.basename(f).replace(".fits", "_ab.png")))
        plt.clf()
       

    return 0, offsets[np.argmax(prod)], -2*offsets[np.argmax(prod)]
Example #36
0
def _makeBlockPinPatches(block, cold):
    """Return lists of block component patches and corresponding data and names (which relates to material
    of the component for later plot-coloring/legend) for a single block.


    Takes in a block that must have a spatialGrid attached as well as a variable
    which signifies whether the dimensions of the components are at hot or cold temps.
    When cold is set to true, you would get the BOL cold temp dimensions.

    Parameters
    ----------
    block : Block

    cold : boolean
        true for cold temps, hot = false

    Return
    ------
    patches : list
        list of patches for block components

    data : list
        list of the materials these components are made of

    name : list
        list of the names of these components
    """

    patches = []
    data = []
    names = []
    if isinstance(block.spatialGrid, grids.HexGrid):
        largestPitch, comp = block.getPitch(returnComp=True)

    elif isinstance(block.spatialGrid, grids.ThetaRZGrid):
        raise TypeError(
            "This plot function is not currently supported for ThetaRZGrid grids."
        )
    else:
        largestPitch, comp = block.getPitch(returnComp=True)
        if block.getPitch()[0] != block.getPitch()[1]:
            raise ValueError(
                "Only works for blocks with equal length and width.")

    sortedComps = sorted(block, reverse=True)

    derivedComponents = block.getComponentsOfShape(DerivedShape)
    if len(derivedComponents) == 1:
        derivedComponent = derivedComponents[0]
        sortedComps.remove(derivedComponent)
        cName = derivedComponent.name

        if isinstance(derivedComponent.material, custom.Custom):
            material = derivedComponent.p.customIsotopicsName
        else:
            material = derivedComponent.material.name

        location = comp.spatialLocator
        if isinstance(location, grids.MultiIndexLocation):
            location = location[0]
        x, y, _ = location.getLocalCoordinates()
        if isinstance(comp, Hexagon):
            derivedPatch = matplotlib.patches.RegularPolygon(
                (x, y), 6, largestPitch / math.sqrt(3))
        elif isinstance(comp, Square):
            derivedPatch = matplotlib.patches.Rectangle(
                (x - largestPitch[0] / 2, y - largestPitch[0] / 2),
                largestPitch[0],
                largestPitch[0],
            )
        else:
            raise TypeError(
                "Shape of the pitch-defining element is not a Square or Hex it is {}, cannot plot for this type of block"
                .format(comp.shape))
        patches.append(derivedPatch)
        data.append(material)
        names.append(cName)
    for component in sortedComps:
        locs = component.spatialLocator
        if not isinstance(locs, grids.MultiIndexLocation):
            # make a single location a list to iterate.
            locs = [locs]
        for loc in locs:
            x, y, _ = loc.getLocalCoordinates()

            # goes through each location
            # want to place a patch at that location
            blockPatches = _makeComponentPatch(component, (x, y), cold)
            for element in blockPatches:
                patches.append(element)

                if isinstance(component.material, custom.Custom):
                    material = component.p.customIsotopicsName
                else:
                    material = component.material.name

                data.append(material)
                names.append(component.name)

    return patches, data, names
Example #37
0
def three_cells_alt(coupling_strength, ax):

	c = coupling_strength+0.00001
	patches = []
	art = mpatches.Circle(np.array([xblue, yblue]), radius, fc='b')
	patches.append(art)
	art = mpatches.Circle(np.array([xgreen, ygreen]), radius, fc='g')
	patches.append(art)
	art = mpatches.Circle(np.array([xred, yred]), radius, fc='r')
	patches.append(art)

	sh = 0.02
	shr = 0.25
	alpha = 1.3

	# 1 blue -> green
	xbluegreen = [xblue+alpha*radius, xgreen-alpha*radius]
	ybluegreen = np.array([yblue, ygreen])+sh
	ax.add_line(pl.Line2D(xbluegreen, ybluegreen, lw=5., c='k'))
	ax.add_patch(mpatches.Circle(np.array([xbluegreen[1], ybluegreen[1]]), radius/4., fc='k'))
	ax.text((xblue+xgreen)/2.-0.05, (yblue+ygreen)/2.+0.05, repr(c[2])[:6], fontsize=15)

	# 2 green -> blue
	xgreenblue = xbluegreen
	ygreenblue = ybluegreen-2.*sh
	ax.add_line(pl.Line2D(xgreenblue, ygreenblue, lw=5., c='k'))
	
	ax.add_patch(mpatches.Circle(np.array([xgreenblue[0], ygreenblue[0]]), radius/4., fc='k'))

	ax.text((xblue+xgreen)/2.-0.05, (yblue+ygreen)/2.-0.1, repr(c[0])[:6], fontsize=15)

	# 3 green -> red
	xredgreen = np.array([xred+0., xgreen+0.])*0.45+0.375
	yredgreen = np.array([yred+0., ygreen+0.])*0.45+0.2185
	ax.add_line(pl.Line2D(xredgreen, yredgreen, lw=5., c='k'))
	ax.add_patch(mpatches.Circle(np.array([xredgreen[0], yredgreen[0]]), radius/4., fc='k'))
	ax.text((xgreen+xred)/2.+0.015, (ygreen+yred)/2.-0.015, repr(c[5])[:6], fontsize=15, rotation=45)

	# 4 red -> green
	xredgreen = np.array([xred+0., xgreen+0.])*0.45+0.33
	yredgreen = np.array([yred+0., ygreen+0.])*0.45+0.255
	ax.add_line(pl.Line2D(xredgreen, yredgreen, lw=5., c='k'))
	ax.add_patch(mpatches.Circle(np.array([xredgreen[1], yredgreen[1]]), radius/4., fc='k'))
	ax.text((xgreen+xred)/2.-0.1, (ygreen+yred)/2.+0.07, repr(c[3])[:6], fontsize=15, rotation=45)

	# 5 red -> blue
	xbluered = np.array([xblue+0., xred+0.])*0.45+0.17
	ybluered = np.array([yblue+0., yred+0.])*0.45+0.23
	ax.add_line(pl.Line2D(xbluered, ybluered, lw=5., c='k'))
	ax.add_patch(mpatches.Circle(np.array([xbluered[0], ybluered[0]]), radius/4., fc='k'))
	ax.text((xblue+xred)/2.-0.1, (yblue+yred)/2.-0.0, repr(c[1])[:6], fontsize=15, rotation=-55)

	# 6 blue -> red
	xbluered = np.array([xblue+0., xred+0.])*0.45+0.2
	ybluered = np.array([yblue+0., yred+0.])*0.45+0.265
	ax.add_line(pl.Line2D(xbluered, ybluered, lw=5., c='k'))
	ax.add_patch(mpatches.Circle(np.array([xbluered[1], ybluered[1]]), radius/4., fc='k'))
	ax.text((xblue+xred)/2.-0.02, (yblue+yred)/2.+0.1, repr(c[4])[:6], fontsize=15, rotation=-55)

	ax.add_patch(patches[0])
	ax.add_patch(patches[1])
	ax.add_patch(patches[2])

	ax.text(xblue-0.04, yblue-0.05, r'$1$', fontsize=40)
	ax.text(xgreen-0.04, ygreen-0.05, r'$2$', fontsize=40)
	ax.text(xred-0.04, yred-0.05, r'$3$', fontsize=40)

	ax.set_xticks([])
	ax.set_yticks([])
	ax.set_axis_off()
Example #38
0
def draw2d(*objects, origin=True, axes=True, grid=(1,1), nice_aspect_ratio=True,
            width=6, save_as=None):

    all_vectors = list(extract_vectors_2d(objects))
    xs, ys = zip(*all_vectors)

    max_x, max_y, min_x, min_y = max(0,*xs), max(0,*ys), min(0,*xs), min(0,*ys)

    #sizing
    if grid:
        x_padding = max(ceil(0.05*(max_x-min_x)), grid[0])
        y_padding = max(ceil(0.05*(max_y-min_y)), grid[1])

        def round_up_to_multiple(val,size):
            return floor((val + size) / size) * size

        def round_down_to_multiple(val,size):
            return -floor((-val - size) / size) * size

        plt.xlim(floor((min_x - x_padding) / grid[0]) * grid[0],
                ceil((max_x + x_padding) / grid[0]) * grid[0])
        plt.ylim(floor((min_y - y_padding) / grid[1]) * grid[1],
                ceil((max_y + y_padding) / grid[1]) * grid[1])
    else:
        x_padding = 0.05 * (max_x-min_x)
        y_padding = 0.05 * (max_y-min_y)

        plt.xlim(min_x-x_padding,max_x+x_padding)
        plt.ylim(min_y-y_padding,max_y+y_padding)

    if origin:
        plt.scatter([0],[0], color='k', marker='x')

    if grid:
        plt.gca().set_xticks(np.arange(plt.xlim()[0],plt.xlim()[1],grid[0]))
        plt.gca().set_yticks(np.arange(plt.ylim()[0],plt.ylim()[1],grid[1]))
        plt.grid(True)
        plt.gca().set_axisbelow(True)

    if axes:
        plt.gca().axhline(linewidth=2, color='k')
        plt.gca().axvline(linewidth=2, color='k')

    for object in objects:
        if type(object) == Polygon2D:
            if object.color:
                for i in range(0,len(object.vertices)):
                    x1, y1 = object.vertices[i]
                    x2, y2 = object.vertices[(i+1)%len(object.vertices)]
                    plt.plot([x1,x2],[y1,y2], color=object.color)
            if object.fill:
                patches = []
                poly = Polygon(object.vertices, True)
                patches.append(poly)
                p = PatchCollection(patches, color=object.fill)
                plt.gca().add_collection(p)
        elif type(object) == Points2D:
            xs = [v[0] for v in object.vectors]
            ys = [v[1] for v in object.vectors]
            plt.scatter(xs,ys,color=object.color)
        elif type(object) == Arrow2D:
            tip, tail = object.tip, object.tail
            tip_length = (xlim()[1] - xlim()[0]) / 20.
            length = sqrt((tip[1]-tail[1])**2 + (tip[0]-tail[0])**2)
            new_length = length - tip_length
            new_y = (tip[1] - tail[1]) * (new_length / length)
            new_x = (tip[0] - tail[0]) * (new_length / length)
            plt.gca().arrow(tail[0], tail[1], new_x, new_y,
            head_width=tip_length/1.5, head_length=tip_length,
            fc=object.color, ec=object.color)
        elif type(object) == Segment2D:
            x1, y1 = object.start_point
            x2, y2 = object.end_point
            plt.plot([x1,x2],[y1,y2], color=object.color)
        else:
            raise TypeError("Unrecognized object: {}".format(object))

    fig = matplotlib.pyplot.gcf()

    if nice_aspect_ratio:
        coords_height = (ylim()[1] - ylim()[0])
        coords_width = (xlim()[1] - xlim()[0])
        fig.set_size_inches(width , width * coords_height / coords_width)

    if save_as:
        plt.savefig(save_as)

    plt.show()
Example #39
0
    for (lons, lats) in polygons:
        x, y = m(lons, lats)
        xy = zip(x, y)
        area = .5 * sum(
            (xy[i][0] * xy[i + 1][1]) - (xy[i + 1][0] * xy[i][1])
            for i in range(len(xy) - 1)
        )
        cx = 1 / (6 * area) * sum(
            (xy[i][0] + xy[i + 1][0]) * ((xy[i][0] * xy[i + 1][1]) - (xy[i + 1][0] * xy[i][1]))
            for i in range(len(xy) - 1)
        )
        cy = 1 / (6 * area) * sum(
            (xy[i][1] + xy[i + 1][1]) * ((xy[i][0] * xy[i + 1][1]) - (xy[i + 1][0] * xy[i][1]))
            for i in range(len(xy) - 1)
        )
        patches.append(matplotlib.patches.Polygon(xy))
        counts.append(count[name])
        # plt.text(cx, cy, name,
        #          horizontalalignment="center",
        #          verticalalignment="center")

m.set_axes_limits()

x, y = m(positions[1], positions[0])
plt.scatter(x, y, values, "k")

p = matplotlib.collections.PatchCollection(patches, cmap=colors, norm=normalize, alpha=0.7)
p.set_array(np.array(counts))
ax.add_collection(p)
plt.colorbar(p,
             spacing="proportional",