Beispiel #1
0
def make_plot(prefix='wp',
              show_plot=True,
              polygon_sides=3,
              rotation_rho=10,
              spirality_sigma=20,
              N=10,
              glue_tab=False,
              cut_tip=True,
              cut_bottom_func=None,
              angle_offsets=None):

    fig, ax = plt.subplots()
    name = '{}_poly{}_rho{}_sig{}_N{}'.format(prefix, polygon_sides,
                                              int(rotation_rho),
                                              int(spirality_sigma), N)

    exterior_base = 90.0 + rotation_rho / 2.0
    poly = wp_angles()
    poly.beta = 360.0 / polygon_sides
    poly.alpha = (180.0 - poly.beta) / 2.0
    poly.gamma = 2.0 * poly.alpha

    basic = wp_angles()
    basic.beta = exterior_base - poly.alpha
    basic.alpha = spirality_sigma
    basic.gamma = 180.0 - basic.alpha - basic.beta
    print(basic.alpha, basic.beta, basic.gamma)

    #FIXME: Check validity

    # standard whirlpool
    if angle_offsets is None:
        original_angle_offsets = [
            rotation_rho * x for x in list(range(polygon_sides))
        ]
        angle_offsets = [rotation_rho * x for x in list(range(polygon_sides))]

    ac_len = 10.0
    row_origin = [0.0, 0.0]
    rows = []
    triangles = []
    for layer in range(N):
        # create a basic triangle of ac_len with angles given
        path = make_basic_triangle_path(row_origin, ac_len, basic)
        print(path.vertices)
        color = ["red", "green", "blue", "orange", "yellow", "cyan"]
        start = row_origin
        row = []

        for n in range(polygon_sides):
            r = mpl.transforms.Affine2D().rotate_deg_around(
                path.vertices[0][0], path.vertices[0][1], -angle_offsets[n])
            path = path.transformed(r)

            # put triangle in position at the angle_offset and position
            row.append(path)
            print(color[n])
            print(path)

            path = make_basic_triangle_path(origin=path.vertices[2],
                                            ac_len=ac_len,
                                            basic=basic)

        # end poly for
        rows.append(row)  # big matrix of paths so we can make a cut path

        # Calculate angle offsets then move row_origin
        ac_len = distance(row[0].vertices[1], row[1].vertices[1])
        angoff = atan_deg(row[0].vertices[1],
                          row[1].vertices[1]) - original_angle_offsets[1]

        for n in range(polygon_sides):
            angle_offsets[n] = original_angle_offsets[n] + angoff
        b = point(row[0].vertices[1][0], row[0].vertices[1][1])
        a = b.pointFrom(-ac_len, angoff)

        row_origin = [a.x, a.y]
        print(row_origin, ac_len)
        print(angle_offsets)
    # end for each layer of triangles

    # make an outline for cutting, use cut_tip and cut_bottom to control it
    cut_vertices = []
    for r in rows:  # start at 0,0 and go clockwise, adding each A point in the column
        cut_vertices.append(r[0].vertices[0])
    if cut_tip:
        path = rows[-1][0]
        pta = path.vertices[0]
        ptb = path.vertices[1]
        ab_mid = (pta + ptb) / 2.0
        rot = mpl.transforms.Affine2D().rotate_deg_around(
            ab_mid[0], ab_mid[1], 180.0)
        v = path.transformed(rot).vertices[2]
        cut_vertices.append(v)

        for n in range(
                polygon_sides):  # add B points of the top (smallest) row
            cut_vertices.append(rows[-1][n].vertices[1])

    # else calculate the meeting point and use that
    # Fixme: add that
    # calculate the tip point, rho angle and then isoceles triangle
    # will need the vertical scores to tip point, ok to aappend a row to rows
    # add tip point to cut_vertices
    # add B point of the last triangle rows[-1][-1]

    for i in range(N):  # back down the column using the C points on this side
        cut_vertices.append(rows[-(i + 1)][-1].vertices[2])
    if cut_bottom_func is None:
        for n in range(
                polygon_sides):  # along the wide bottom until back to start
            cut_vertices.append(rows[0][-(n + 1)].vertices[0])
    cut_path = Path(cut_vertices)
    patch = patches.PathPatch(cut_path,
                              facecolor='k',
                              alpha=0.05,
                              edgecolor='k')
    ax.add_patch(patch)

    # add all the trangles to the plot
    for r in rows:
        for n in range(polygon_sides):
            patch = patches.PathPatch(r[n],
                                      facecolor=color[n],
                                      alpha=0.75,
                                      edgecolor='k')
            ax.add_patch(patch)

    plt.axis('off')
    plt.box(False)
    ax.set_aspect(1), ax.autoscale()
    plt.savefig(name + ".svg")
    if show_plot: plt.title(name), plt.show()
Beispiel #2
0
fig = plt.figure()
ax = fig.add_subplot(111)

pathdata = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    ]

codes, verts = list(zip(*pathdata))
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='green', edgecolor='red', alpha=0.5, fill=False)
ax.add_patch(patch)


class PathInteractor:
    """
    An path editor.

    Key-bindings

      't' toggle vertex markers on and off.  When vertex markers are on,
          you can move them, delete them


    """
Beispiel #3
0
    def render(self, mode='human', close=False):
        #fig, ax = plt.subplots(1, 1, figsize=(10, 10))

        #x_axis = [x[0] for x in self.ue_path]
        #y_axis = [x[1] for x in self.ue_path]
        #z_axis = self.ue_path_rates
        #plt.plot(x_axis, y_axis)

        #plt.show()

        from matplotlib.path import Path
        import matplotlib.patches as patches

        verts = [(int(x[0]), int(x[1])) for x in self.ue_path]
        #print(self.ue_path)
        #print(verts)

        codes = [Path.LINETO for x in range(len(verts))]
        codes[0] = Path.MOVETO
        codes[-1] = Path.STOP

        path = Path(verts, codes)

        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(111)
        patch = patches.PathPatch(path, facecolor='none', lw=2)
        ax.add_patch(patch)

        xs, ys = zip(*verts)
        ax.plot(xs, ys, 'x--', lw=2, color='black')

        #xdisplay, ydisplay = ax.transData.transform_point((self.ue_xsrc, self.ue_ysrc))

        bbox = dict(boxstyle="round", fc="0.8")
        arrowprops = dict(arrowstyle="->",
                          connectionstyle="angle,angleA=0,angleB=90,rad=10")

        offset = 40
        ax.annotate('Src = (%d, %d)' % (self.ue_xsrc, self.ue_ysrc),
                    (self.ue_xsrc, self.ue_ysrc),
                    xytext=(-2 * offset, offset),
                    textcoords='offset points',
                    bbox=bbox,
                    arrowprops=arrowprops)

        ax.annotate('Dest = (%d, %d)' % (self.ue_xdest[0], self.ue_ydest[0]),
                    (self.ue_xdest[0], self.ue_ydest[0]),
                    xytext=(0.5 * offset, -offset),
                    textcoords='offset points',
                    bbox=bbox,
                    arrowprops=arrowprops)

        offset = 10
        bbox = dict(boxstyle="round", facecolor='yellow', edgecolor='none')
        for i in range(0, len(self.ue_path_rates)):
            ax.annotate('%.2f' % np.around(self.ue_path_rates[i], decimals=2),
                        (verts[i][0], verts[i][1]),
                        xytext=(-2 * offset, offset),
                        textcoords='offset points',
                        bbox=bbox,
                        arrowprops=arrowprops)

        ax.grid()
        ax.set_xticks(self.ue_xloc)
        ax.set_yticks(self.ue_yloc)
        ax.set_title("UAV graph w.r.t gNB [0,0,0]")
        ax.set_xlabel("X direction")
        ax.set_ylabel("Y direction")

        plt.show()

        return
def mps_cc(subject, pathdict, plot=True, verbose=True):

    # Find location of peaks within a single-component radio source via contour counting

    contours = get_contours(subject, pathdict)
    lobe = contours['contours'][0]
    xmax, ymax, xmin, ymin = lobe[0]['bbox']

    parr = []
    valarr = []
    for cl in lobe:
        parr.extend([(p['x'], p['y']) for p in cl['arr']])
        valarr.extend(np.ones(len(cl['arr'])) + cl['level'])

    points = np.array([(px, py) for px, py in parr])
    values = np.array(valarr)

    # Find levels with multiple contours
    # For each of those levels, check if next level up has geometric center within that contour
    # If no, then that level's geometric center is a local maximum
    # If yes, then move up one level and repeat

    k = [l['k'] for l in lobe]
    ck = Counter(k)

    mlarr = []
    for x, y in ck.iteritems():
        if y > 1:
            mlarr.append(x)

    if max(k) not in mlarr:
        mlarr.append(max(k))

    mlarr.sort()

    local_maxima = []
    for m in mlarr:
        levels = [l for l in lobe if l['k'] == m]

        # Is there a higher level?
        if m < max(k):

            upper_levels = [l for l in lobe if l['k'] == m + 1]

            for level in levels:
                within = False
                for ul in upper_levels:

                    gc = centroid(ul['arr'])
                    polygon = make_polygon(level['arr'])
                    result = point_in_poly(gc[0], gc[1], polygon)
                    within += result

                if not within:
                    gc = centroid(level['arr'])
                    local_maxima.append((m, gc))
                    if verbose:
                        print 'Point in poly, m=%i, center=(%.1f,%.1f)' % (
                            m, gc[0], gc[1])

        # If no higher level, centroids = local max
        else:
            for level in levels:
                gc = centroid(level['arr'])
                local_maxima.append((m, gc))
                if verbose:
                    print 'No higher levels, m=%i, center=(%.1f,%.1f)' % (
                        m, gc[0], gc[1])

    # Plot locations of peaks

    npeaks = len(local_maxima)

    if plot:

        xc = [x[1][0] for x in local_maxima]
        yc = [x[1][1] for x in local_maxima]

        fig = plt.figure()
        ax = fig.add_subplot(111)

        verts_all = []
        codes_all = []
        components = contours['contours']

        for comp in components:

            # Order of bounding box components is (xmax,ymax,xmin,ymin)
            comp_xmax, comp_ymax, comp_xmin, comp_ymin = comp[0]['bbox']

            # Only plot radio components identified by the users as the consensus;
            # check on the xmax value to make sure

            for idx, level in enumerate(comp):
                verts = [(p['x'], p['y']) for p in level['arr']]

                codes = np.ones(len(verts), int) * Path.LINETO
                codes[0] = Path.MOVETO

                verts_all.extend(verts)
                codes_all.extend(codes)

        try:
            path = Path(verts_all, codes_all)
            patch_black = patches.PathPatch(path,
                                            facecolor='none',
                                            edgecolor='black',
                                            lw=1)
        except AssertionError:
            print 'Users found no components for consensus match of %s' % zooniverse_id

        # Plot contours identified as the consensus
        ax.add_patch(patch_black)

        ax.plot(xc, yc, 'r*', ms=10)
        ax.set_xlim(0, FIRST_FITS_WIDTH)
        ax.set_ylim(FIRST_FITS_HEIGHT, 0)
        ax.set_aspect('equal')
        #ax.title(subject['zooniverse_id'])

        plt.show()

    return local_maxima
def plot_one_triple(zooniverse_id,
                    pathdict,
                    figno=1,
                    savefig=False,
                    anglepath=''):

    # Make a four-panel plot of the consensus identification with marked bending angle and position angle for a triple source

    cons = consensus.checksum(zooniverse_id)

    subject = subjects.find_one({'zooniverse_id': zooniverse_id})
    contours = get_contours(subject, pathdict)
    radio_components = contours['contours']

    # Plot image

    answer = cons['answer']

    # Download contour data

    sf_x = 500. / contours['width']
    sf_y = 500. / contours['height']

    verts_all = []
    codes_all = []
    components = contours['contours']

    for comp in components:

        # Order of bounding box components is (xmax,ymax,xmin,ymin)
        comp_xmax, comp_ymax, comp_xmin, comp_ymin = comp[0]['bbox']

        # Only plot radio components identified by the users as the consensus;
        # check on the xmax value to make sure
        for v in answer.itervalues():
            if comp_xmax in v['xmax']:

                for idx, level in enumerate(comp):
                    verts = [((p['x']) * sf_x, (p['y'] - 1) * sf_y)
                             for p in level['arr']]

                    codes = np.ones(len(verts), int) * Path.LINETO
                    codes[0] = Path.MOVETO

                    verts_all.extend(verts)
                    codes_all.extend(codes)

    try:
        path = Path(verts_all, codes_all)
        patch_black = patches.PathPatch(path,
                                        facecolor='none',
                                        edgecolor='black',
                                        lw=1)
    except AssertionError:
        print 'Users found no components for consensus match of %s' % zooniverse_id

    # Plot the infrared results

    fig = plt.figure(figno, (15, 4))
    fig.clf()
    ax3 = fig.add_subplot(143)
    ax4 = fig.add_subplot(144)

    colormaparr = [
        cm.hot_r, cm.Blues, cm.RdPu, cm.Greens, cm.PuBu, cm.YlGn, cm.Greys
    ][::-1]
    colorarr = ['r', 'b', 'm', 'g', 'c', 'y', 'k'][::-1]

    if len(answer) > 0:  # At least one galaxy was identified
        for idx, ans in enumerate(answer.itervalues()):

            if ans.has_key('peak_data'):

                # Plot the KDE map
                colormap = colormaparr.pop()
                ax3.imshow(np.rot90(ans['peak_data']['Z']),
                           cmap=colormap,
                           extent=[xmin, xmax, ymin, ymax])

                # Plot individual sources
                color = colorarr.pop()
                x_plot, y_plot = ans['ir_x'], ans['ir_y']
                ax3.scatter(x_plot,
                            y_plot,
                            c=color,
                            marker='o',
                            s=10,
                            alpha=1. / len(x_plot))

                ax4.plot([ans['ir_peak'][0]], [ans['ir_peak'][1]],
                         color=color,
                         marker='*',
                         markersize=12)

            elif ans.has_key('ir'):
                color = colorarr.pop()
                x_plot, y_plot = ans['ir']
                ax3.plot([x_plot], [y_plot],
                         color=color,
                         marker='o',
                         markersize=2)
                ax4.plot([x_plot], [y_plot],
                         color=color,
                         marker='*',
                         markersize=12)

            else:
                ax4.text(550, idx * 25, '#%i - no IR host' % idx, fontsize=11)

    ax3.set_xlim([0, 500])
    ax3.set_ylim([500, 0])
    ax3.set_title(zooniverse_id)
    ax3.set_aspect('equal')

    ax4.set_xlim([0, 500])
    ax4.set_ylim([500, 0])
    ax4.set_title('Consensus (%i/%i users)' %
                  (cons['n_users'], cons['n_total']))

    ax4.set_aspect('equal')

    # Display IR and radio images

    url_standard = subject['location']['standard']
    im_standard = Image.open(
        cStringIO.StringIO(urllib.urlopen(url_standard).read()))
    ax1 = fig.add_subplot(141)
    ax1.imshow(im_standard, origin='upper')
    ax1.set_title('WISE')

    url_radio = subject['location']['radio']
    im_radio = Image.open(cStringIO.StringIO(urllib.urlopen(url_radio).read()))
    ax2 = fig.add_subplot(142)
    ax2.imshow(im_radio, origin='upper')
    ax2.set_title(subject['metadata']['source'])
    ax2.get_yaxis().set_ticklabels([])

    ax3.get_yaxis().set_ticklabels([])

    # Plot contours identified as the consensus
    if len(answer) > 0:
        ax4.add_patch(patch_black)
        # Add centers of bounding boxes
        for comp in components:
            bbox_radio = comp[0]['bbox']
            bbox_ir = bbox_radio_to_ir(bbox_radio)
            xrad = np.median((bbox_ir[0], bbox_ir[2]))
            yrad = np.median((bbox_ir[1], bbox_ir[3]))
            ax4.scatter(xrad, yrad, c='g', marker='s', s=15, alpha=1)

            dbx = [bbox_ir[i] for i in (2, 2, 0, 0, 2)]
            dby = [bbox_ir[i] for i in (3, 1, 1, 3, 3)]
            ax4.plot(dbx, dby, color='g')

        radiobeamsize = 5.  # arcsec
        imagesize = 3.  # arcmin
        imagescale = IMG_HEIGHT_NEW / imagesize / 60.  # pixel / arcsec
        radio_tol = radiobeamsize * imagescale

        for ans in answer:
            if answer[ans].has_key('ir_peak'):
                # Optical counterpart position
                xc, yc = answer[ans]['ir_peak']

                # Measure all positions in radio pixel coordinates
                radio_centroids = pix_radio(components)

                maxdist = 0
                for centroid in radio_centroids:
                    d = pix_dist(xc, yc, centroid[0], centroid[1])
                    maxdist = d if d > maxdist else maxdist
                    if d <= radio_tol:
                        middle_radio = centroid
                        radio_centroids.remove(middle_radio)

                        x1 = radio_centroids[0][0]
                        y1 = radio_centroids[0][1]
                        x2 = radio_centroids[1][0]
                        y2 = radio_centroids[1][1]

                if len(radio_centroids) == 2:

                    m1 = (y1 - yc) / (x1 - xc)
                    b1 = yc - m1 * xc
                    m2 = (y2 - yc) / (x2 - xc)
                    b2 = yc - m2 * xc

                    xedge1 = 0 if x1 < xc else 500
                    yedge1 = y1 - (x1 - xedge1) * (yc - y1) / (xc - x1)

                    xedge2 = 0 if x2 < xc else 500
                    yedge2 = y2 - (x2 - xedge2) * (yc - y2) / (xc - x2)

                    # Draw and annotate the the bending angle

                    ax4.plot([xedge1, xc], [yedge1, yc],
                             color='orange',
                             linestyle='--')
                    ax4.plot([xedge2, xc], [yedge2, yc],
                             color='orange',
                             linestyle='--')
                    alpha_deg = bending_angle(xc, yc, x1, y1, x2,
                                              y2) * 180 / np.pi
                    ax4.text(550,
                             0,
                             r'$\alpha$ = %.1f deg' % alpha_deg,
                             fontsize=11)

                else:
                    print "\tDidn't find match to optical ID for triple radio source %s" % zooniverse_id

            else:
                print "\tNo IR peak for %s" % zooniverse_id

    ax4.yaxis.tick_right()

    ax1.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax2.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax3.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax4.get_xaxis().set_ticks([0, 100, 200, 300, 400, 500])

    plt.subplots_adjust(wspace=0.02)

    # Save hard copy of the figure
    if savefig:
        fig.savefig(
            '{0:}/bending_angles/plots/individual/triples/{1:}ba_{2:}.pdf'.
            format(rgz_dir, anglepath, zooniverse_id))
        plt.close()
    else:
        plt.show()

    # Close figure after it's done; otherwise mpl complains about having thousands of stuff open

    return None
Beispiel #6
0
 codes = [
     Path.MOVETO,
     Path.LINETO,
     Path.LINETO,
     Path.LINETO,
     Path.CLOSEPOLY,
 ]
 verts2_1 = [
     (1., 0.5),  # left, bottom
     (1., 3.5),  # left, top
     (2., 3.5),  # right, top
     (2., 0.5),  # right, bottom
     (0., 0.),  # ignored
 ]
 path2_1 = Path(verts2_1, codes)
 patch2_1 = patches.PathPatch(path2_1, facecolor='mistyrose', lw=0)
 verts2_2 = [
     (3., 1.),  # left, bottom
     (3., 3.),  # left, top
     (4., 3.),  # right, top
     (4., 1.),  # right, bottom
     (0., 0.),  # ignored
 ]
 path2_2 = Path(verts2_2, codes)
 patch2_2 = patches.PathPatch(path2_2, facecolor='honeydew', lw=0)
 plt.clf()
 fig = plt.figure()
 ax = fig.add_subplot(111)
 ax.set_xlabel('x')
 ax.set_ylabel('y')
 fig.tight_layout()
Beispiel #7
0
def plt_catalog(Model_list, File_bg, catalog_file, Run_name, xmin, xmax, ymin,
                ymax, llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,
                completness_file, nb_inter, bining_in_mag, end_year_of_catalog,
                sub_area_file):

    if not os.path.exists(str(Run_name) + '/analysis/figures/catalogue'):
        os.makedirs(str(Run_name) + '/analysis/figures/catalogue')

    catalog_cum_rate = []
    index_model = 0

    for model in Model_list:
        # extract the geometry of the zone ( geometry of the background)
        Lon_bg, Lat_bg = Geom_bg(model, File_bg)
        ColX = Lon_bg
        ColY = Lat_bg
        Poly = []
        for x1, y1 in zip(ColX, ColY):  # creation du polygon de la zone
            Poly.append((x1, y1))
        bbPath = mplPath.Path(Poly)

        bbPath_sub_areas = []
        if os.path.exists(sub_area_file):
            read_sub_area_file = open(sub_area_file, 'rU')
            lines_sub_area = read_sub_area_file.readlines()
            sub_area_names = []
            sub_area_coord = []
            sub_area_lon = []
            sub_area_lat = []
            for line in lines_sub_area:
                model_sub_area = line.split('\t')[0]
                if model == model_sub_area:
                    sub_area_names.append(line.split('\t')[1])
                    sub_area_coord.append(line.split('\t')[2:])
                    sub_area_lon_i = []
                    sub_area_lat_i = []
                    for sub_area_coord_i in line.split('\t')[2:]:
                        if not '\n' in sub_area_coord_i.split(','):
                            if not '' in sub_area_coord_i.split(','):
                                sub_area_lon_i.append(
                                    float(sub_area_coord_i.split(',')[1]))
                                sub_area_lat_i.append(
                                    float(sub_area_coord_i.split(',')[0]))
                    sub_area_lon.append(sub_area_lon_i)
                    sub_area_lat.append(sub_area_lat_i)
                    if not os.path.exists(
                            str(Run_name) +
                            '/analysis/figures/catalogue/sub_area'):
                        os.makedirs(
                            str(Run_name) +
                            '/analysis/figures/catalogue/sub_area')

                    Poly_sub = []
                    for x1, y1 in zip(
                            sub_area_lon_i,
                            sub_area_lat_i):  # creation du polygon de la zone
                        Poly_sub.append((x1, y1))
                    bbPath_sub_areas.append(mplPath.Path(Poly_sub))

        cat_data = np.genfromtxt(catalog_file,
                                 dtype=[('S100'), ('S100'), ('S100'), ('S100'),
                                        ('S100'), ('S100'), ('S100'), ('S100'),
                                        ('S100')],
                                 skip_header=1)
        cat_lon = list(
            map(lambda i: float(cat_data[i][5]), range(len(cat_data))))
        cat_lat = list(
            map(lambda i: float(cat_data[i][4]), range(len(cat_data))))
        cat_depth = list(
            map(lambda i: float(cat_data[i][6]), range(len(cat_data))))
        cat_Mw = list(
            map(lambda i: float(cat_data[i][7]), range(len(cat_data))))
        cat_sig_Mw = list(
            map(lambda i: float(cat_data[i][8]), range(len(cat_data))))
        cat_Yr = list(
            map(lambda i: float(cat_data[i][0]), range(len(cat_data))))

        #selects only the earthquakes that are in the subarea
        indexes_in = []
        for index_cat in range(len(cat_lon)):
            if bbPath.contains_point(
                (cat_lon[index_cat], cat_lat[index_cat]
                 )) == 1:  #test pour savoir si la zone contient le point
                indexes_in.append(index_cat)
        cat_lon = np.take(cat_lon, indexes_in)
        cat_lat = np.take(cat_lat, indexes_in)
        cat_depth = np.take(cat_depth, indexes_in)
        cat_Mw = np.take(cat_Mw, indexes_in)
        cat_sig_Mw = np.take(cat_sig_Mw, indexes_in)
        cat_Yr = np.take(cat_Yr, indexes_in)

        #extracting the completeness time of the catalogue
        completness = []
        weights_completness = []
        read_comp_file = open(completness_file, 'rU')
        lines_of_the_file = read_comp_file.readlines()
        #lines_of_the_file.remove('\n')
        line_number = 0
        for i in range(int(len(lines_of_the_file) / 2)):
            if len(lines_of_the_file[line_number].split('\t')) != 0:
                binning_comp_i = lines_of_the_file[line_number].split('\t')
                if '\r\n' in binning_comp_i:
                    binning_comp_i.remove('\r\n')
                if '\n' in binning_comp_i:
                    binning_comp_i.remove('\n')
                binning_comp = []
                for magnitudes in binning_comp_i[1:]:
                    mag = magnitudes.split(',')
                    binning_comp.append(float(mag[0]))
                    binning_comp.append(float(mag[1]))
                #binning_comp = [float(x) for x in binning_comp]
                binning_comp.append(bining_in_mag[-1])
                comp_value_i = lines_of_the_file[line_number + 1].split('\t')
                if '\r\n' in comp_value_i:
                    comp_value_i.remove('\r\n')
                if '\n' in comp_value_i:
                    comp_value_i.remove('\n')
                comp_value = []
                for value in comp_value_i[1:]:
                    comp_value.append(float(value))
                    comp_value.append(float(value))
                #comp_value = [float(x) for x in comp_value]
                comp_value.append(comp_value[-1])

                completeness_interpolate = interp1d(binning_comp, comp_value)
                completness_i = []
                for mag in bining_in_mag:
                    try:
                        completness_i.append(completeness_interpolate(mag))
                    except ValueError:
                        print(
                            '!!!!!!!!!!!!\n\n\nERROR in completeness file\n your minimum magnitude might not be low enough\n\n\n!!!!!!!!!!!!'
                        )
                line_number += 2
                completness.append(completness_i)
                weights_completness.append(float(comp_value_i[0]))
        seismological_moment_rate = []

        number_of_earthquakes_for_rate = [
        ]  #nuMber of earthquake greater than this magnitude
        number_of_earthquakes_for_rate_sub_area = [
        ]  #nuMber of earthquake greater than this magnitude in the sub areas
        for poly_sub_area_i in bbPath_sub_areas:
            number_of_earthquakes_for_rate_sub_area.append([])

        #variables for the plot on the map
        file_catalog_for_map = open(
            str(Run_name) + '/analysis/figures/catalogue/catalog_for_map_' +
            str(model) + '.txt', 'w')
        earthquake_for_map = []
        nb_time_picked = [
        ]  #number of time this earthquake has been kept in the complete catalog

        #self.rate_SHARE_WCR_cum_kdeplot = []
        rate_SHARE_WCR_cum_density = []

        #for the sub_areas
        rate_in_sub_area_cum = []
        for poly_sub_area_i in bbPath_sub_areas:
            rate_in_sub_area_cum.append([])

        #loop on the interations to explore the uncertainties
        for i in range(nb_inter):
            #cat_SHARE_WCR_i = []
            cat_model_bin = np.zeros(len(bining_in_mag))
            rate_SHARE_WCR = np.zeros(len(bining_in_mag))
            seismological_moment_rate_i = 0.  #moment rate calculated using the catalog
            test_if_eq_here = [
            ]  #will be checked if the earthquake is not count twice

            #random picking of the completness used
            index_completness = np.random.choice(len(weights_completness),
                                                 1,
                                                 p=weights_completness)[0]
            completness_used = completness[index_completness]

            #for the sub areas
            cat_sub_area_bin = []
            rate_sub_area = []
            for poly_sub_area_i in bbPath_sub_areas:
                cat_sub_area_bin.append(np.zeros(len(bining_in_mag)))
                rate_sub_area.append(np.zeros(len(bining_in_mag)))

            #random pick of the earthquakes magnitudes
            envents_magnitude = []
            index_cat = 0
            for Yr in cat_Yr:  #loop on all the earthquakes in the catalogue to pick the magnitude
                if cat_sig_Mw[index_cat] == 0:
                    event_magnitude = cat_Mw[index_cat]
                elif cat_sig_Mw[index_cat] <= 3.:
                    event_magnitude = np.random.triangular(
                        cat_Mw[index_cat] - cat_sig_Mw[index_cat] / 2.,
                        cat_Mw[index_cat],
                        cat_Mw[index_cat] + cat_sig_Mw[index_cat] / 2.)
#                else :
#                    event_magnitude = np.random.triangular(cat_sig_Mw[index_cat],cat_Mw[index_cat],cat_sig_Mw_plus[index_cat])
                envents_magnitude.append(event_magnitude)
                index_cat += 1

            index_mag = 0
            #for mag_i,completness_i,sigma_completness_i in zip(bining_in_mag,completeness,sigma_completness) :
            for mag_i, completness_i in zip(bining_in_mag, completness_used):
                #loop on the magnitudes
                index_cat = 0

                #picked_completness = completness_i + random_factor * sigma_completness_i
                picked_completness = completness_i

                index_cat = 0
                for Yr in cat_Yr:  #loop on all the earthquakes in the catalogue
                    if cat_depth[index_cat] < 30. or math.isnan(
                            cat_depth[index_cat]
                    ):  #check if the event is not on the subduction interface for Corinth
                        if Yr >= picked_completness and Yr <= end_year_of_catalog:
                            event_magnitude = envents_magnitude[index_cat]
                            if event_magnitude >= mag_i and event_magnitude < mag_i + 0.099:
                                if bbPath.contains_point(
                                    (cat_lon[index_cat], cat_lat[index_cat])
                                ) == 1:  #test pour savoir si la zone contient le point
                                    if not (str(Yr) + str(cat_lon[index_cat]) +
                                            str(cat_lat[index_cat]) +
                                            str(cat_sig_Mw[index_cat])
                                            ) in test_if_eq_here:
                                        #cat_SHARE_WCR_i.append(event_magnitude)
                                        test_if_eq_here.append(
                                            str(Yr) + str(cat_lon[index_cat]) +
                                            str(cat_lat[index_cat]))

                                        cat_model_bin[index_mag] += 1

                                        #for the map
                                        string_for_map = str(Yr) + '\t' + str(
                                            cat_Mw[index_cat]) + '\t' + str(
                                                cat_lon[index_cat]
                                            ) + '\t' + str(cat_lat[index_cat])
                                        if not string_for_map in earthquake_for_map:  #the earthquake has not been pîcked in an earlier iteration
                                            earthquake_for_map.append(
                                                string_for_map)
                                            nb_time_picked.append(1)
                                        else:
                                            index_in_cat_for_map = np.where(
                                                np.array(earthquake_for_map) ==
                                                string_for_map)[0][0]
                                            nb_time_picked[
                                                index_in_cat_for_map] += 1  #if earthquake arealy there, we count it one more time

                                        #for the sub areas
                                        index_sub_area = 0
                                        for poly_sub_area_i in bbPath_sub_areas:
                                            if poly_sub_area_i.contains_point(
                                                (cat_lon[index_cat],
                                                 cat_lat[index_cat])
                                            ) == 1:  #test pour savoir si la zone contient le point
                                                cat_sub_area_bin[
                                                    index_sub_area][
                                                        index_mag] += 1
                                            index_sub_area += 1

                    index_cat += 1
                rate_SHARE_WCR[index_mag] = cat_model_bin[index_mag] / (
                    end_year_of_catalog - picked_completness)
                M0 = 10.**(1.5 * mag_i + 9.1)  #calculation of the moment
                rate_M0 = M0 * rate_SHARE_WCR[index_mag]
                seismological_moment_rate_i += rate_M0

                #for the sub areas
                index_sub_area = 0
                for poly_sub_area_i in bbPath_sub_areas:
                    rate_sub_area[index_sub_area][
                        index_mag] = cat_sub_area_bin[index_sub_area][
                            index_mag] / (end_year_of_catalog -
                                          picked_completness)
                    index_sub_area += 1

                index_mag += 1

            seismological_moment_rate.append(seismological_moment_rate_i)

            number_of_earthquakes_for_rate_i = []
            for i in range(len(cat_model_bin)
                           ):  #calculate the cumulative number of earthquake
                number_of_earthquakes_for_rate_i.append(
                    int(
                        np.sum(
                            np.array(cat_model_bin)[-(len(cat_model_bin) -
                                                      i):])))
            number_of_earthquakes_for_rate.append(
                number_of_earthquakes_for_rate_i)

            #for the sub areas
            index_sub_area = 0
            for poly_sub_area_i in bbPath_sub_areas:
                number_of_earthquakes_for_rate_i = []
                for i in range(
                        len(cat_model_bin
                            )):  #calculate the cumulative number of earthquake
                    number_of_earthquakes_for_rate_i.append(
                        int(
                            np.sum(
                                np.array(cat_sub_area_bin[index_sub_area])
                                [-(len(cat_sub_area_bin[index_sub_area]) -
                                   i):])))
                number_of_earthquakes_for_rate_sub_area[index_sub_area].append(
                    number_of_earthquakes_for_rate_i)
                index_sub_area += 1

            rate_SHARE_WCR_cum = []
            for i in range(
                    len(rate_SHARE_WCR)):  #calculate the cumulative rate
                rate_SHARE_WCR_cum.append(
                    np.sum(
                        np.array(rate_SHARE_WCR)[-(len(rate_SHARE_WCR) - i):]))
            rate_SHARE_WCR_cum_density.append(rate_SHARE_WCR_cum)

            #for the sub areas
            index_sub_area = 0
            for poly_sub_area_i in bbPath_sub_areas:
                rate_sub_area_i_cum = []
                for i in range(len(rate_sub_area[index_sub_area])
                               ):  #calculate the cumulative rate
                    rate_sub_area_i_cum.append(
                        np.sum(
                            np.array(rate_sub_area[index_sub_area])
                            [-(len(rate_sub_area[index_sub_area]) - i):]))
                rate_in_sub_area_cum[index_sub_area].append(
                    rate_sub_area_i_cum)
                index_sub_area += 1

            plt.scatter(bining_in_mag,
                        rate_SHARE_WCR_cum,
                        c='brown',
                        marker='_',
                        s=50,
                        alpha=0.2)  #, linewidth = 0

        axes = plt.gca()
        axes.set_xlim([xmin, xmax])
        axes.set_ylim([ymin, ymax])
        mean_nb_eq_in_cat = np.mean(number_of_earthquakes_for_rate, axis=0)
        for index_mag in range(len(bining_in_mag)):

            #does a simulation of the catalog in order to check the statistical validity

            nb_eq = mean_nb_eq_in_cat[index_mag]
            if completness[0][index_mag] == min(
                    completness[0]
            ):  #if it's the last completness period, do the statistical représentativity
                time_obs = int(
                    round(end_year_of_catalog - completness[0][index_mag]))

                rate = float(nb_eq) / float(time_obs)

                time_simu = 1000000

                nb_sample = 50

                cat = []
                #build the catalog
                for i in range(time_simu):
                    test = np.random.uniform(0., 1.)
                    if test <= rate:
                        cat.append(1)
                    else:
                        cat.append(0)

                rates_simu = []
                for i in range(nb_sample):
                    yrs_start = random.choice(range(time_simu - time_obs))
                    cat_sampled = cat[yrs_start:yrs_start + time_obs]
                    #print sum(cat_sampled), sum(cat_sampled)/float(time_obs)
                    rates_simu.append(sum(cat_sampled) / float(time_obs))

    #            rate_plus = np.percentile(rate_SHARE_WCR_cum_density,84,axis=0)[index_mag]
    #            rate_minus = np.percentile(rate_SHARE_WCR_cum_density,16,axis=0)[index_mag]
                unc_rate = (np.std(rate_SHARE_WCR_cum_density,
                                   axis=0)[index_mag]) / (np.square(
                                       mean_nb_eq_in_cat[index_mag]))
                unc_rate = np.std(rates_simu)
                #print(bining_in_mag[index_mag],nb_eq,time_obs,round(np.array(rate_SHARE_WCR_cum_density).mean(axis=0)[index_mag],6),round(unc_rate,6))
                rate_plus = np.array(rate_SHARE_WCR_cum_density).mean(
                    axis=0)[index_mag] + unc_rate
                rate_minus = np.array(rate_SHARE_WCR_cum_density).mean(
                    axis=0)[index_mag] - unc_rate
                if rate_minus < 0.:  # in order not to have negative values
                    rate_minus = np.array(rate_SHARE_WCR_cum_density).mean(
                        axis=0)[index_mag] / 10.

            else:  #if it's another period, use the percentiles of the distribution
                rate_plus = np.percentile(rate_SHARE_WCR_cum_density,
                                          84,
                                          axis=0)[index_mag]
                rate_minus = np.percentile(rate_SHARE_WCR_cum_density,
                                           16,
                                           axis=0)[index_mag]

            mag = bining_in_mag[index_mag]
            mag_plus = mag + 0.05
            mag_minus = mag - 0.05
            verts = [(mag_minus, rate_minus), (mag_minus, rate_plus),
                     (mag_plus, rate_plus), (mag_plus, rate_minus),
                     (mag_minus, rate_minus)]
            codes = [
                Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                Path.CLOSEPOLY
            ]

            path_poly = Path(verts, codes)

            patch = patches.PathPatch(path_poly,
                                      facecolor='k',
                                      lw=0.,
                                      alpha=0.15)
            axes.add_patch(patch)

#        plt.scatter(bining_in_mag,np.percentile(rate_SHARE_WCR_cum_density,50,axis=0),
#                c='k', s=5, edgecolor='',marker = 'o',alpha = 0.8)
#        plt.scatter(bining_in_mag,np.percentile(rate_SHARE_WCR_cum_density,16,axis=0),
#            c='k', s=5, edgecolor='',marker = '+',alpha = 0.8)
#        plt.scatter(bining_in_mag,np.percentile(rate_SHARE_WCR_cum_density,84,axis=0),
#                    c='k', s=5, edgecolor='',marker = '+',alpha = 0.8)
#        plt.scatter(bining_in_mag,np.percentile(rate_SHARE_WCR_cum_density,5,axis=0),
#            c='k', s=4, edgecolor='',marker = 'o',alpha = 0.8)
#        plt.scatter(bining_in_mag,np.percentile(rate_SHARE_WCR_cum_density,95,axis=0),
#                    c='k', s=4, edgecolor='',marker = 'o',alpha = 0.8)
        plt.scatter(bining_in_mag,
                    np.array(rate_SHARE_WCR_cum_density).mean(axis=0),
                    c='k',
                    s=20,
                    edgecolor='',
                    marker='s',
                    alpha=0.95)

        plt.yscale('log')
        plt.title('earthquake catalog')
        plt.grid(alpha=0.3)
        plt.savefig(str(Run_name) + '/analysis/figures/catalogue/catalogue_' +
                    str(model) + '.png',
                    dpi=180,
                    transparent=True)
        #plt.show()
        plt.close()

        #for the sub areas
        index_sub_area = 0
        for poly_sub_area_i in bbPath_sub_areas:

            axes = plt.gca()
            axes.set_xlim([xmin, xmax])
            axes.set_ylim([ymin, ymax])
            mean_nb_eq_in_cat = np.mean(
                number_of_earthquakes_for_rate_sub_area[index_sub_area],
                axis=0)
            for index_mag in range(len(bining_in_mag)):

                #does a simulation of the catalog in order to check the statistical validity

                nb_eq = mean_nb_eq_in_cat[index_mag]
                time_obs = int(
                    round(end_year_of_catalog - completness[0][index_mag]))

                rate = float(nb_eq) / float(time_obs)

                time_simu = 1000000

                nb_sample = 50

                cat = []
                #build the catalog
                for i in range(time_simu):
                    test = np.random.uniform(0., 1.)
                    if test <= rate:
                        cat.append(1)
                    else:
                        cat.append(0)

                rates_simu = []
                for i in range(nb_sample):
                    yrs_start = random.choice(range(time_simu - time_obs))
                    cat_sampled = cat[yrs_start:yrs_start + time_obs]
                    #print sum(cat_sampled), sum(cat_sampled)/float(time_obs)
                    rates_simu.append(sum(cat_sampled) / float(time_obs))

                unc_rate = np.std(rates_simu)
                rate_plus = np.array(
                    rate_in_sub_area_cum[index_sub_area]).mean(
                        axis=0)[index_mag] + unc_rate
                rate_minus = np.array(
                    rate_in_sub_area_cum[index_sub_area]).mean(
                        axis=0)[index_mag] - unc_rate
                if rate_minus < 0.:  # in order not to have negative values
                    rate_minus = np.array(
                        rate_in_sub_area_cum[index_sub_area]).mean(
                            axis=0)[index_mag] / 10.
                mag = bining_in_mag[index_mag]
                mag_plus = mag + 0.05
                mag_minus = mag - 0.05
                verts = [(mag_minus, rate_minus), (mag_minus, rate_plus),
                         (mag_plus, rate_plus), (mag_plus, rate_minus),
                         (mag_minus, rate_minus)]
                codes = [
                    Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO,
                    Path.CLOSEPOLY
                ]

                path_poly = Path(verts, codes)

                patch = patches.PathPatch(path_poly,
                                          facecolor='k',
                                          lw=0.,
                                          alpha=0.15)
                axes.add_patch(patch)

            for i in range(nb_inter):
                plt.scatter(bining_in_mag,
                            rate_in_sub_area_cum[index_sub_area][i],
                            c='brown',
                            marker='_',
                            s=50,
                            alpha=0.2)  #, linewidth = 0

#            plt.scatter(bining_in_mag,np.percentile(rate_in_sub_area_cum[index_sub_area],50,axis=0),
#                    c='k', s=15, edgecolor='',marker = 'o',alpha = 0.8)
#            plt.scatter(bining_in_mag,np.percentile(rate_in_sub_area_cum[index_sub_area],16,axis=0),
#                c='k', s=15, edgecolor='',marker = '+',alpha = 0.8)
#            plt.scatter(bining_in_mag,np.percentile(rate_in_sub_area_cum[index_sub_area],84,axis=0),
#                        c='k', s=15, edgecolor='',marker = '+',alpha = 0.8)
#            plt.scatter(bining_in_mag,np.percentile(rate_in_sub_area_cum[index_sub_area],5,axis=0),
#                c='k', s=5, edgecolor='',marker = 'o',alpha = 0.8)
#            plt.scatter(bining_in_mag,np.percentile(rate_in_sub_area_cum[index_sub_area],95,axis=0),
#                        c='k', s=5, edgecolor='',marker = 'o',alpha = 0.8)
            plt.scatter(bining_in_mag,
                        np.array(
                            rate_in_sub_area_cum[index_sub_area]).mean(axis=0),
                        c='k',
                        s=15,
                        edgecolor='',
                        marker='s',
                        alpha=0.95)

            axes = plt.gca()
            axes.set_xlim([xmin, xmax])
            axes.set_ylim([ymin, ymax])
            plt.grid()
            plt.yscale('log')
            plt.title('catalogue sub area ' + sub_area_names[index_sub_area])
            plt.savefig(
                str(Run_name) +
                '/analysis/figures/catalogue/sub_area/catalogue_sub_area_' +
                sub_area_names[index_sub_area] + ' Model ' + str(model) +
                '.png',
                dpi=180,
                transparent=True)
            #plt.show()
            plt.close()

            index_sub_area += 1
        #export the rates of the catalogue for future comparisons
        #line_cat_for model = [model, rate_SHARE_WCR_cum_density]
        catalog_cum_rate.append(rate_SHARE_WCR_cum_density)

        #print 'Number of earthquake for the rate in catalogue'
        file_nb_eq_in_cat = open(
            str(Run_name) + '/analysis/figures/catalogue/nb_eq_in_cat_' +
            str(model) + '.txt', 'w')
        file_nb_eq_in_cat.write(
            'Number of earthquake for the rate in catalogue' + '\n')
        mean_nb_eq_in_cat = np.mean(number_of_earthquakes_for_rate, axis=0)
        for i in range(len(bining_in_mag)):
            #print bining_in_mag[i],int(round(mean_nb_eq_in_cat[i],0))
            file_nb_eq_in_cat.write(
                str(bining_in_mag[i]) + '\t' +
                str(round(mean_nb_eq_in_cat[i], 0)) + '\n')
        file_nb_eq_in_cat.close()

        plt.scatter(bining_in_mag, mean_nb_eq_in_cat)
        plt.axhline(y=1)
        plt.axhline(y=2)
        plt.axhline(y=5)
        plt.axhline(y=10)
        plt.title('nb of earthquakes (m>M) in the catalogue')
        plt.savefig(str(Run_name) + '/analysis/figures/catalogue/' +
                    'nb_of_EQ_in_catalogue.png',
                    dpi=180,
                    transparent=True)
        plt.grid()
        plt.close()

        for string, nb in zip(earthquake_for_map, nb_time_picked):
            #print string,nb
            #if nb >= nb_inter/2 : #we write in the catalog only if selected more than half the time
            file_catalog_for_map.write(string + '\t' + str(nb) + '\n')

        file_catalog_for_map.close()

        #for the sub areas
        index_sub_area = 0
        for poly_sub_area_i in bbPath_sub_areas:
            plt.scatter(
                bining_in_mag,
                np.mean(
                    number_of_earthquakes_for_rate_sub_area[index_sub_area],
                    axis=0))
            plt.axhline(y=1)
            plt.axhline(y=2)
            plt.axhline(y=5)
            plt.axhline(y=10)
            plt.title('nb of earthquakes (m>M) in the catalogue ' +
                      sub_area_names[index_sub_area])
            plt.savefig(
                str(Run_name) + '/analysis/figures/catalogue/sub_area/' +
                'nb_of_EQ_in_ ' + sub_area_names[index_sub_area] + '.png',
                dpi=180,
                transparent=True)
            plt.grid()
            plt.close()
            index_sub_area += 1

        ###### map plot of the catalog #####
        if mean_nb_eq_in_cat[0] > 3:
            catalog_for_map = np.genfromtxt(
                str(Run_name) +
                '/analysis/figures/catalogue/catalog_for_map_' + str(model) +
                '.txt',
                dtype=[('f8'), ('f8'), ('f8'), ('f8'), ('f8')])
            yr_cat_for_map = list(
                map(lambda i: round(float(catalog_for_map[i][0])),
                    range(len(catalog_for_map))))
            M_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][1]),
                    range(len(catalog_for_map))))
            lon_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][2]),
                    range(len(catalog_for_map))))
            lat_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][3]),
                    range(len(catalog_for_map))))
            nb_time_picked = list(
                map(lambda i: float(catalog_for_map[i][4]),
                    range(len(catalog_for_map))))

            m = Basemap(projection='mill',
                        llcrnrlon=llcrnrlon,
                        llcrnrlat=llcrnrlat,
                        urcrnrlon=urcrnrlon,
                        urcrnrlat=urcrnrlat,
                        resolution='i')

            for (Yr, M, lon, lat, nb) in zip(yr_cat_for_map, M_cat_for_map,
                                             lon_cat_for_map, lat_cat_for_map,
                                             nb_time_picked):
                x, y = m(lon, lat)
                # color scale
                if M < 5.5:
                    s = 6
                    c = 'grey'
                elif M < 6.0:
                    s = 8
                    c = 'yellow'
                elif M < 6.5:
                    s = 10
                    c = 'orange'
                else:
                    s = 12
                    c = 'red'

                if nb >= 2 * nb_inter / 3:
                    alpha = 1.
                if nb <= 2 * nb_inter / 3:
                    alpha = 0.8
                if nb <= 1 * nb_inter / 2:
                    alpha = 0.3
                if nb < 1 * nb_inter / 3:
                    alpha = 0.1

                c = plt.cm.jet((M - min(M_cat_for_map)) /
                               (max(M_cat_for_map) - min(M_cat_for_map)))

                m.plot(x,
                       y,
                       'o',
                       markersize=s,
                       linewidth=0.2,
                       color=c,
                       alpha=alpha)

                x_text, y_text = m(lon + 0.005, lat + 0.005)
                plt.text(x_text,
                         y_text,
                         str(int(Yr)) + ',' + str(int(nb)),
                         fontsize=4)

            m.drawcoastlines(linewidth=0.1)
            #m.fillcontinents(color='grey',lake_color='w',alpha = 0.2)
            plt.gca().set_title('Earthquake catalog - Complete period')
            plt.savefig(str(Run_name) + '/analysis/figures/catalogue/' +
                        'earthquake_map_' + str(model) + '.png',
                        dpi=180,
                        transparent=True)
            #plt.show()
            plt.close()

            ###### map plot of the catalog #####

            catalog_for_map = np.genfromtxt(
                str(Run_name) +
                '/analysis/figures/catalogue/catalog_for_map_' + str(model) +
                '.txt',
                dtype=[('f8'), ('f8'), ('f8'), ('f8'), ('f8')])
            yr_cat_for_map = list(
                map(lambda i: round(float(catalog_for_map[i][0])),
                    range(len(catalog_for_map))))
            M_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][1]),
                    range(len(catalog_for_map))))
            lon_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][2]),
                    range(len(catalog_for_map))))
            lat_cat_for_map = list(
                map(lambda i: float(catalog_for_map[i][3]),
                    range(len(catalog_for_map))))
            nb_time_picked = list(
                map(lambda i: float(catalog_for_map[i][4]),
                    range(len(catalog_for_map))))

            m = Basemap(projection='mill',
                        llcrnrlon=llcrnrlon,
                        llcrnrlat=llcrnrlat,
                        urcrnrlon=urcrnrlon,
                        urcrnrlat=urcrnrlat,
                        resolution='l')

            for (Yr, M, lon, lat) in zip(yr_cat_for_map, M_cat_for_map,
                                         lon_cat_for_map, lat_cat_for_map):
                x, y = m(lon, lat)
                # color scale
                if M < 5.5:
                    s = 6
                    c = 'grey'
                elif M < 6.0:
                    s = 8
                    c = 'yellow'
                elif M < 6.5:
                    s = 10
                    c = 'orange'
                else:
                    s = 12
                    c = 'red'

                if nb >= 2 * nb_inter / 3:
                    alpha = 1.
                if nb <= 2 * nb_inter / 3:
                    alpha = 0.8
                if nb <= 1 * nb_inter / 2:
                    alpha = 0.3
                if nb < 1 * nb_inter / 3:
                    alpha = 0.001

                c = plt.cm.jet((M - min(M_cat_for_map)) /
                               (max(M_cat_for_map) - min(M_cat_for_map)))

                m.plot(x,
                       y,
                       'o',
                       markersize=s,
                       linewidth=0.2,
                       color=c,
                       alpha=0.5)

            plt.savefig(str(Run_name) + '/analysis/figures/catalogue/' +
                        'earthquake_map_just_EQ_' + str(model) + '.png',
                        dpi=180,
                        transparent=True)
            #plt.show()
            plt.close()

    index_model += 1

    return seismological_moment_rate, catalog_cum_rate  #,yr_cat_for_map,M_cat_for_map,lon_cat_for_map,lat_cat_for_map
Beispiel #8
0
def as_mpl_artists(shape_list,
                   properties_func=None,
                   text_offset=5.0,
                   origin=1):
    """
    Converts a region list to a list of patches and a list of artists.


    Optional Keywords:
    [ text_offset ] - If there is text associated with the regions, add
    some vertical offset (in pixels) to the text so that it doesn't overlap
    with the regions.

    Often, the regions files implicitly assume the lower-left corner
    of the image as a coordinate (1,1). However, the python convetion
    is that the array index starts from 0. By default (origin = 1),
    coordinates of the returned mpl artists have coordinate shifted by
    (1, 1). If you do not want this shift, set origin=0.
    """

    patch_list = []
    artist_list = []

    if properties_func is None:
        properties_func = properties_func_default

    # properties for continued(? multiline?) regions
    saved_attrs = None

    for shape in shape_list:

        patches = []

        if saved_attrs is None:
            _attrs = [], {}
        else:
            _attrs = copy.copy(saved_attrs[0]), copy.copy(saved_attrs[1])

        kwargs = properties_func(shape, _attrs)

        if shape.name == "composite":
            saved_attrs = shape.attr
            continue

        if saved_attrs is None and shape.continued:
            saved_attrs = shape.attr


#         elif (shape.name in shape.attr[1]):
#             if (shape.attr[1][shape.name] != "ignore"):
#                 saved_attrs = shape.attr

        if not shape.continued:
            saved_attrs = None

        # text associated with the shape
        txt = shape.attr[1].get("text")

        if shape.name == "polygon":
            xy = np.array(shape.coord_list)
            xy.shape = -1, 2

            # -1 for change origin to 0,0
            patches = [mpatches.Polygon(xy - origin, closed=True, **kwargs)]

        elif shape.name == "rotbox" or shape.name == "box":
            xc, yc, w, h, rot = shape.coord_list
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            _box = np.array([[-w / 2., -h / 2.], [-w / 2., h / 2.],
                             [w / 2., h / 2.], [w / 2., -h / 2.]])
            box = _box + [xc, yc]
            rotbox = rotated_polygon(box, xc, yc, rot)
            patches = [mpatches.Polygon(rotbox, closed=True, **kwargs)]

        elif shape.name == "ellipse":
            xc, yc = shape.coord_list[:2]
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            angle = shape.coord_list[-1]

            maj_list, min_list = shape.coord_list[2:-1:2], shape.coord_list[
                3:-1:2]

            patches = [mpatches.Ellipse((xc, yc), 2*maj, 2*min,
                                        angle=angle, **kwargs) \
                       for maj, min in zip(maj_list, min_list)]

        elif shape.name == "annulus":
            xc, yc = shape.coord_list[:2]
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            r_list = shape.coord_list[2:]

            patches = [mpatches.Ellipse((xc, yc), 2*r, 2*r,
                                        **kwargs) \
                       for r in r_list]

        elif shape.name == "circle":
            xc, yc, major = shape.coord_list
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            patches = [
                mpatches.Ellipse((xc, yc),
                                 2 * major,
                                 2 * major,
                                 angle=0,
                                 **kwargs)
            ]

        elif shape.name == "panda":
            xc, yc, a1, a2, an, r1, r2, rn = shape.coord_list
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            patches = [mpatches.Arc((xc, yc), rr*2, rr*2, angle=0,
                                    theta1=a1, theta2=a2, **kwargs) \
                       for rr in np.linspace(r1, r2, rn+1)]

            for aa in np.linspace(a1, a2, an + 1):
                xx = np.array([r1, r2]) * np.cos(aa / 180. * np.pi) + xc
                yy = np.array([r1, r2]) * np.sin(aa / 180. * np.pi) + yc
                p = Path(np.transpose([xx, yy]))
                patches.append(mpatches.PathPatch(p, **kwargs))

        elif shape.name == "pie":
            xc, yc, r1, r2, a1, a2 = shape.coord_list
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin

            patches = [mpatches.Arc((xc, yc), rr*2, rr*2, angle=0,
                                   theta1=a1, theta2=a2, **kwargs) \
                       for rr in [r1, r2]]

            for aa in [a1, a2]:
                xx = np.array([r1, r2]) * np.cos(aa / 180. * np.pi) + xc
                yy = np.array([r1, r2]) * np.sin(aa / 180. * np.pi) + yc
                p = Path(np.transpose([xx, yy]))
                patches.append(mpatches.PathPatch(p, **kwargs))

        elif shape.name == "epanda":
            xc, yc, a1, a2, an, r11, r12, r21, r22, rn, angle = shape.coord_list
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin

            # mpl takes angle a1, a2 as angle as in circle before
            # transformation to ellipse.

            x1, y1 = cos(a1 / 180. * pi), sin(a1 / 180. * pi) * r11 / r12
            x2, y2 = cos(a2 / 180. * pi), sin(a2 / 180. * pi) * r11 / r12

            a1, a2 = atan2(y1, x1) / pi * 180., atan2(y2, x2) / pi * 180.

            patches = [mpatches.Arc((xc, yc), rr1*2, rr2*2,
                                    angle=angle, theta1=a1, theta2=a2,
                                  **kwargs) \
                       for rr1, rr2 in zip(np.linspace(r11, r21, rn+1),
                                           np.linspace(r12, r22, rn+1))]

            for aa in np.linspace(a1, a2, an + 1):
                xx = np.array([r11, r21]) * np.cos(aa / 180. * np.pi)
                yy = np.array([r11, r21]) * np.sin(aa / 180. * np.pi)
                p = Path(np.transpose([xx, yy]))
                tr = Affine2D().scale(1,
                                      r12 / r11).rotate_deg(angle).translate(
                                          xc, yc)
                p2 = tr.transform_path(p)
                patches.append(mpatches.PathPatch(p2, **kwargs))

        elif shape.name == "text":
            xc, yc = shape.coord_list[:2]
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin

            if txt:
                _t = _get_text(txt, xc, yc, 0, 0, **kwargs)
                artist_list.append(_t)

        elif shape.name == "point":
            xc, yc = shape.coord_list[:2]
            # -1 for change origin to 0,0
            xc, yc = xc - origin, yc - origin
            artist_list.append(Line2D([xc], [yc], **kwargs))

            if txt:
                textshape = copy.copy(shape)
                textshape.name = "text"
                textkwargs = properties_func(textshape, _attrs)
                _t = _get_text(txt,
                               xc,
                               yc,
                               0,
                               text_offset,
                               va="bottom",
                               **textkwargs)
                artist_list.append(_t)

        elif shape.name in ["line", "vector"]:
            if shape.name == "line":
                x1, y1, x2, y2 = shape.coord_list[:4]
                # -1 for change origin to 0,0
                x1, y1, x2, y2 = x1 - origin, y1 - origin, x2 - origin, y2 - origin

                a1, a2 = shape.attr[1].get("line", "0 0").strip().split()[:2]

                arrowstyle = "-"
                if int(a1):
                    arrowstyle = "<" + arrowstyle
                if int(a2):
                    arrowstyle = arrowstyle + ">"

            else:  # shape.name == "vector"
                x1, y1, l, a = shape.coord_list[:4]
                # -1 for change origin to 0,0
                x1, y1 = x1 - origin, y1 - origin
                x2, y2 = x1 + l * np.cos(a / 180. * np.pi), y1 + l * np.sin(
                    a / 180. * np.pi)
                v1 = int(shape.attr[1].get("vector", "0").strip())

                if v1:
                    arrowstyle = "->"
                else:
                    arrowstyle = "-"

            patches = [
                mpatches.FancyArrowPatch(posA=(x1, y1),
                                         posB=(x2, y2),
                                         arrowstyle=arrowstyle,
                                         arrow_transmuter=None,
                                         connectionstyle="arc3",
                                         patchA=None,
                                         patchB=None,
                                         shrinkA=0,
                                         shrinkB=0,
                                         connector=None,
                                         **kwargs)
            ]

        else:
            warnings.warn(
                "'as_mpl_artists' does not know how to convert '%s' to mpl artist"
                % (shape.name, ))

        patch_list.extend(patches)

        if txt and patches:
            # the text associated with a shape uses different
            # matplotlib keywords than the shape itself for, e.g.,
            # color
            textshape = copy.copy(shape)
            textshape.name = "text"
            textkwargs = properties_func(textshape, _attrs)

            # calculate the text position
            _bb = [p.get_window_extent() for p in patches]

            # this is to work around backward-incompatible change made
            # in matplotlib 1.2. This change is later reverted so only
            # some versions are affected. With affected version of
            # matplotlib, get_window_extent method calls get_transform
            # method which sets the _transformSet to True, which is
            # not desired.
            for p in patches:
                p._transformSet = False

            _bbox = Bbox.union(_bb)
            x0, y0, x1, y1 = _bbox.extents
            xc = .5 * (x0 + x1)

            _t = _get_text(txt,
                           xc,
                           y1,
                           0,
                           text_offset,
                           va="bottom",
                           **textkwargs)
            artist_list.append(_t)

    return patch_list, artist_list
def trans2d(x,y,tx,ty,phi):
    xx = x*np.cos(phi) - y*np.sin(phi) + tx
    yy = x*np.sin(phi) + y*np.cos(phi) + ty
    return(xx,yy)

t = np.linspace(0,2*pi,6).reshape(6,1)
limb_len = 1
x,y = pol2cart(t,1)

num_square = 50
theta = pi/num_square
phi = pi/5

fig, ax = plt.subplots()
cmap = matplotlib.cm.get_cmap('hsv')

Path = mpath.Path
codes = [Path.MOVETO] + [Path.LINETO]*4 + [Path.CLOSEPOLY]

for n in range(0, num_square):
    verts = np.hstack((x, y))
    path = mpath.Path(limb_len*verts, codes)
    pathpatch = mpatches.PathPatch(path, facecolor=cmap((1.0*n)/num_square), edgecolor='white', linewidth=0.5)
    ax.add_patch(pathpatch)
    limb_len = limb_len*np.cos(phi)/np.cos(phi-theta)
    x,y = trans2d(x,y,0,0,theta)

ax.axis('equal')
plt.show()
Beispiel #10
0
nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5,0] = left
verts[0::5,1] = bottom
verts[1::5,0] = left
verts[1::5,1] = top
verts[2::5,0] = right
verts[2::5,1] = top
verts[3::5,0] = right
verts[3::5,1] = bottom

barpath = path.Path(verts, codes)
patch = patches.PathPatch(barpath, facecolor='blue', edgecolor='cyan', alpha=0.75)
ax.add_patch(patch)

ax.set_xlim(left[0], right[-1])
ax.set_ylim(bottom.min(), top.max())

def animate(i):
    # simulate new data coming in
    x = data[1:i]
    n, bins = np.histogram(x, np.append(left,right[-1]))
    top = bottom + n
    verts[1::5,1] = top
    verts[2::5,1] = top

ani = animation.FuncAnimation(fig, animate, frames=iters, interval=5, repeat=False)
plt.show()
Beispiel #11
0
def bell2(ax, x, y, px, py, w1, w2, h, phi, **kwargs):

    x = px

    w1 *= 2

    r_ = np.r_
    c_ = np.c_
    d1 = 1
    d2 = 1
    d3 = .2
    d4 = .5
    d4L = .6

    d5 = .1
    d6 = .3
    d7 = .5 + d4 + d4L
    w2 = w1 * 1.1  # Breite oben
    p1 = r_[x, y]
    p2 = r_[x - d1, y - d2]

    p3_0 = r_[x + w1, y]
    dp3 = r_[d1, -d2]
    p3 = p3_0 + dp3
    p4 = r_[x + w1, y]  # Ende ex-Kreis

    p5 = p3_0 - .1 * dp3
    p6 = r_[x + w1, y + d4 - d3]
    p7 = r_[x + w1, y + d4]

    p7b = r_[x + w1, y + d4 + d4L]  # Endpunkt Linie

    p8 = r_[x + w1, p7b[1] + d5]  # Kontrollpunkt
    p9 = r_[x + w2, y + d7 - d6]
    p10 = r_[x + w2, y + d7]  # obere rechte Ecke

    w3 = -(w2 - w1)
    p11 = r_[x + w3, y + d7]  # obere linke Ecke

    p12 = r_[x + w3, p9[1]]  # Kontrollpunkt
    p13 = r_[x, p8[1]]  # Kontrollpunkt
    p14 = r_[x, p7b[1]]  # S-Kurve Endpunkt

    p14b = r_[x, p7[1]]  # Linie-Endpunkt

    p15 = r_[x, p6[1]]  # senkrechter Konrollpunkt
    p16 = r_[x, y] + .1 * dp3 * r_[1, -1]  # schräger Konrollpunkt
    p17 = r_[x, y]  # schräger Konrollpunkt

    if 0:
        plot(p5, 'rx', ms=5)
        plot(p6, 'rx', ms=5)
        plot(p7, 'ro', ms=5)
        plot(p7b, 'go', ms=5)
        plot(p8, 'bo', ms=5)
        plot(p9, 'mo', ms=5)
        plot(p10, 'yo', ms=5)

    pathdata = [(Path.MOVETO, p1), (Path.CURVE4, p2), (Path.CURVE4, p3),
                (Path.CURVE4, p4), (Path.CURVE4, p5), (Path.CURVE4, p6),
                (Path.CURVE4, p7), (Path.LINETO, p7b), (Path.CURVE4, p8),
                (Path.CURVE4, p9), (Path.CURVE4, p10), (Path.LINETO, p11),
                (Path.CURVE4, p12), (Path.CURVE4, p13), (Path.CURVE4, p14),
                (Path.LINETO, p14b), (Path.CURVE4, p15), (Path.CURVE4, p16),
                (Path.CURVE4, p17), (Path.CLOSEPOLY, (x, y))]

    codes, verts = list(zip(*pathdata))

    verts = np.array(verts).T
    verts[0, :] -= w1 / 2.0  # correct x

    pivot = np.array([[px, py]]).T

    #    plot(pivot, 'ro', ms = 8)
    #    plot([x,y], 'go', ms = 8)

    verts = np.dot(rotZ(phi), verts - pivot) + pivot
    verts = verts.T

    path = mpath.Path(verts, codes)
    patch = mpatches.PathPatch(path, **dark)

    ax.add_patch(patch)
Beispiel #12
0
        
        for geom in feat.GetGeometryRef():
            x = [geom.GetX(j) for j in range(geom.GetPointCount())]
            y = [geom.GetY(j) for j in range(geom.GetPointCount())]
            print(y)
            codes += [mpath.Path.MOVETO] + \
                             (len(x)-1)*[mpath.Path.LINETO]
            all_x += x
            all_y += y
        path = mpath.Path(np.column_stack((all_x,all_y)), codes)
        paths.append(path)
                
        # Add paths as patches to axes
        for path in paths:
            if idx==0:
                ax.add_patch(mpatches.PathPatch(path,color='C0'))
            else:
                ax.add_patch(mpatches.PathPatch(path,color='C1'))
                
        xBounds.append([np.min(all_x),np.max(all_x)])
        yBounds.append([np.min(all_y),np.max(all_y)])
       

ax.set_xlim(np.min(np.array(xBounds)[:,0]),np.max(np.array(xBounds)[:,1]))
ax.set_ylim(np.min(np.array(yBounds)[:,0]),np.max(np.array(yBounds)[:,1]))


legend = [mpatches.Patch(color='C0', label='Train'),mpatches.Patch(color='C1', label='Valid')]
plt.legend(handles=legend)

plt.show()
Beispiel #13
0
def plot_skymap_tract(skyMap, tract=0, title=None, ax=None, nvisits_tab=None):
    """
    Plot a tract from a skyMap.
    
    Parameters
    ----------
    skyMap: lsst.skyMap.SkyMap
        The SkyMap object containing the tract and patch information.
    tract: int [0]
        The tract id of the desired tract to plot.
    title: str [None]
        Title of the tract plot.  If None, the use `tract <id>`.
    ax: matplotlib.axes._subplots.AxesSubplot [None]
        The subplot object to contain the tract plot.  If None, then make a new one.

    Returns
    -------
    matplotlib.axes._subplots.AxesSubplot: The subplot containing the tract plot.
    """
    if title is None:
        title = 'tract {}'.format(tract)
    tractInfo = skyMap[tract]
    tractBox = afwgeom.Box2D(tractInfo.getBBox())
    tractPosList = tractBox.getCorners()
    wcs = tractInfo.getWcs()
    xNum, yNum = tractInfo.getNumPatches()

    if ax is None:
        fig = plt.figure(figsize=(12,8))
        ax = fig.add_subplot(111)

    tract_center = wcs.pixelToSky(tractBox.getCenter())\
                      .getPosition(afw_geom.degrees)
    ax.text(tract_center[0], tract_center[1], '%d' % tract, size=16,
            ha="center", va="center", color='blue')
    for x in range(xNum):
        for y in range(yNum):
            patchInfo = tractInfo.getPatchInfo([x, y])
            patchBox = afwgeom.Box2D(patchInfo.getOuterBBox())
            pixelPatchList = patchBox.getCorners()
            path = make_patch(pixelPatchList, wcs)
            patch = patches.PathPatch(path, alpha=0.1, lw=1)
            ax.add_patch(patch)
            center = wcs.pixelToSky(patchBox.getCenter())\
                        .getPosition(afw_geom.degrees)
            if nvisits_tab is not None:
                nvisits = nvisits_tab[(nvisits_tab.tract==tract)&(nvisits_tab.patch_x==x)&(nvisits_tab.patch_y==y)].nvisits
                ax.text(center[0], center[1], '%d'%nvisits, size=6,
                        ha="center", va="center")
            else:
                ax.text(center[0], center[1], '%d,%d'%(x,y), size=6,
                        ha="center", va="center")

    skyPosList = [wcs.pixelToSky(pos).getPosition(afw_geom.degrees)
                  for pos in tractPosList]
    ax.set_xlim(max(coord[0] for coord in skyPosList) + 1,
                min(coord[0] for coord in skyPosList) - 1)
    ax.set_ylim(min(coord[1] for coord in skyPosList) - 1,
                max(coord[1] for coord in skyPosList) + 1)
    ax.grid(ls=':',color='gray')
    ax.set_xlabel("RA (deg.)")
    ax.set_ylabel("Dec (deg.)")
    ax.set_title(title)
    return ax
Beispiel #14
0
def plot_focal_plane_fast(butler, visit, ax, color='red', opsimdb=None):
    """
    Plot the CCDs in the LSST focal plane using CCD coordinates derived from the pointing
    info using the lsst.sims code.  
    
    Notes
    -----
    This function assumes that the obs_lsstSims package was used to define the camera geometry 
    for the analysis of the simulated image data.

    Parameters
    ----------
    butler: lsst.daf.persistence.Butler
        The data butler serving up data from the desired repo.
    visit: int
        The visit or obsHistID number.
    ax: matplotlib.axes._subplots.AxesSubplot
        The matplotlib subplot object onto which to plot the focal plane.
    color: str ['red']
        Color to use for plotting the individual CCDs.
    opsimDb: str [None]
        Filename of the OpSim sqlite database.  If None, then the dithered opsim db for Run1.1p
        is used.

    Returns
    -------
    matplotlib.axes._subplots.AxesSubplot: The subplot object used for plotting.
    """
    if opsimdb is None:
        opsimdb = '/global/projecta/projectdirs/lsst/groups/SSim/DC2/minion_1016_desc_dithered_v4.db'
    conn = sqlite3.connect(opsimdb)
    obs_gen = ObservationMetaDataGenerator(database=opsimdb, driver='sqlite')

    # The dithered pointing info was added to the baseline minion_1016 db.  We query for the values
    # used for the desired visit.
    curs = conn.execute('''select descDitheredRA, descDitheredDec, descDitheredRotTelPos
                        from summary where obshistid={}'''.format(visit))
    ra, dec, rottelpos = [np.degrees(x) for x in curs][0]
    
    # An ObservationMetaData object used to pass the pointing info to the function in
    # lsst.sims.coordUtils that provides the CCD coordinates.
    obs_md = obs_gen.getObservationMetaData(obsHistID=visit, boundType='circle', boundLength=0.1)[0]
    obs_md.pointingRA = ra
    obs_md.pointingDec = dec
    obs_md.OpsimMetaData['rotTelPos'] = rottelpos

    # Convert the rotation angle of the sky relative to the telescope to the sky angle relative to
    # the camera.
    obs_md.rotSkyPos = getRotSkyPos(ra, dec, obs_md, rottelpos)
    
    # Use the butler to get the camera appropriate for this observation.  If the data were from a
    # different camera, e.g., DECam or HSC, the corresponding camera objects with the associated
    # CCD geometries would be returned.
    camera = butler.get('camera')
    
    # Grab one of the calexps via its dataref so that we can ask for its filename and thereby infer
    # the location on disk of all of the calexps for this visit.
    dataref = list(butler.subset('calexp', visit=visit))[0]
    calexp_path = os.path.dirname(os.path.dirname(dataref.get('calexp_filename')[0]))
    
    # The following code is specific to the obs_lsstSim package and how it names CCDs
    # (e.g., "R:2,2 S:1,1") and formulates the path components for writing to disk.  This
    # code would not work for a different obs_ package/camera implementation.
    
    # Re-order the CCD vertex list returned by the lsst_sims code so that a rectangle is plotted.
    corner_index = (np.array([0, 1, 3, 2]),)
    for det in camera:
        # Skip the WAVEFRONT and GUIDER CCDs
        if det.getType() != cameraGeom.SCIENCE:
            continue
        detname = det.getName()
        raft, sensor = re.match(r'R:?(\d,?\d)[_ ]S:?(\d,?\d)', detname).groups()
        raft = 'R' + raft.replace(',', '')
        sensor = 'S{}.fits'.format(sensor.replace(',', ''))
        if os.path.isfile(os.path.join(calexp_path, raft, sensor)):
            corners = np.array(lsst.sims.coordUtils.getCornerRaDec(detname, camera, obs_md))
            path = make_patch(corners[corner_index])
            ccd = patches.PathPatch(path, alpha=0.2, lw=1, color=color)
            ax.add_patch(ccd)
    
    return ax
Beispiel #15
0
        #col = 'tab:red'
        col = 'azure'
        #circ = Circle((B3_pix[0][ind], B3_pix[1][ind]), radius=10, fill=False, color=col)    
        #ax.add_patch(circ)
        #ax.plot(B3_pix[0][ind], B3_pix[1][ind], marker = 'x', linestyle='')

        cent_x = B3_pix[0][ind]
        cent_y = B3_pix[1][ind]
        Path = mpath.Path
        path_data = [(Path.MOVETO, [cent_x-5, cent_y+5]),
                     (Path.LINETO, [cent_x+5, cent_y-5]),
                     (Path.MOVETO, [cent_x-5, cent_y-5]),
                     (Path.LINETO, [cent_x+5, cent_y+5])]
        codes, verts = zip(*path_data)
        path = mpath.Path(verts, codes)
        patch = mpatches.PathPatch(path, fill=False, color=col)
        patch.set_path_effects([PathEffects.Stroke(linewidth=2, foreground="black"), PathEffects.Normal()])
        ax.add_patch(patch)

        
    if did not in IRid and did not in coupid and did not in Fbid and did not in new_srcs:
        #col = 'tab:blue'
        col = 'lavenderblush'
        circ = Circle((B3_pix[0][ind], B3_pix[1][ind]), radius=8, fill=False, color=col)
        circ.set_path_effects([PathEffects.Stroke(linewidth=2, foreground="black"), PathEffects.Normal()])
        ax.add_patch(circ)
        
        
    #circ = Circle((B3_pix[0][ind], B3_pix[1][ind]), radius=10, fill=False, color=col)    
    #ax.add_patch(circ)
Beispiel #16
0
def crop(ax):
    try:
        from IPython.html import widgets
        from IPython.display import display, Javascript
        from IPython.utils.traitlets import Unicode, Integer
    except ImportError:
        raise ImportError("You need IPython 2.0+ to use this feature.")
    try:
        import mpld3
        from mpld3._display import NumpyEncoder
        from mpld3.urls import MPLD3_URL, D3_URL
        from mpld3.utils import get_id
        from mpld3.mplexporter import Exporter
        from mpld3.mpld3renderer import MPLD3Renderer
    except ImportError:
        raise ImportError("You need mpld3 v0.3 to use this feature.")

    fig = None
    if isinstance(ax, mpl.figure.Figure):
        fig = ax
        ax = fig.axes[0]

    xmin, xmax = ax.get_xlim()
    ymin, ymax = ax.get_ylim()
    Path = mpath.Path
    path_data = [
        (Path.MOVETO, (xmin + 0.25 * (xmax - xmin),
                       ymin + 0.25 * (ymax - ymin))),
        (Path.LINETO, (xmin + 0.25 * (xmax - xmin),
                       ymin + 0.75 * (ymax - ymin))),
        (Path.LINETO, (xmin + 0.75 * (xmax - xmin),
                       ymin + 0.75 * (ymax - ymin))),
        (Path.LINETO, (xmin + 0.75 * (xmax - xmin),
                       ymin + 0.25 * (ymax - ymin))),
        (Path.CLOSEPOLY, (xmin + 0.75 * (xmax - xmin),
                          ymin + 0.25 * (ymax - ymin))),
    ]
    codes, verts = zip(*path_data)
    path = mpath.Path(verts, codes)
    patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
    ax.add_patch(patch)
    fig = ax.figure
    # plot control points and connecting lines
    x, y = zip(*path.vertices[:-1])
    points = ax.plot(x, y, 'go', ms=10)
    line = ax.plot(x, y, '-k')

    ax.set_title("Drag Points to Change Path", fontsize=18)

    mpld3.plugins.connect(ax.figure, LinkedDragPlugin(points[0], line[0],
                                                      patch))

    renderer = MPLD3Renderer()
    Exporter(renderer, close_mpl=False).run(fig)
    fig, figure_json, extra_css, extra_js = renderer.finished_figures[0]

    my_widget = FigureWidget()
    my_widget.figure_json = json.dumps(figure_json, cls=NumpyEncoder)
    my_widget.extra_js = extra_js
    my_widget.extra_css = extra_css
    my_widget.figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10))
    my_widget.idpts = mpld3.utils.get_id(points[0], 'pts')
    my_widget.x1 = xmin + 0.25 * (xmax - xmin)
    my_widget.x2 = xmin + 0.25 * (xmax - xmin)
    my_widget.x3 = xmin + 0.75 * (xmax - xmin)
    my_widget.x4 = xmin + 0.75 * (xmax - xmin)
    my_widget.y1 = ymin + 0.25 * (ymax - ymin)
    my_widget.y2 = ymin + 0.75 * (ymax - ymin)
    my_widget.y3 = ymin + 0.75 * (ymax - ymin)
    my_widget.y4 = ymin + 0.75 * (ymax - ymin)

    # Copy over preservation of axis information if looking at a FlowML
    # generated figure.
    if hasattr(fig, '_flowml_axis'):
        my_widget._flowml_axis = fig._flowml_axis

    display(Javascript(JAVASCRIPT))
    fig.clf()

    return my_widget
Beispiel #17
0
def draw(g, layout=None, labels=False, figsize=(8,2), h_edge_draw='blue', rows=None):
    if not isinstance(g, BaseGraph):
        g = g.to_graph(zh=True)
    fig1 = plt.figure(figsize=figsize)
    ax = fig1.add_axes([0, 0, 1, 1], frameon=False)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    vs_on_row = dict()  # count the vertices on each row
    for v in g.vertices():
        vs_on_row[g.row(v)] = vs_on_row.get(g.row(v), 0) + 1

    if not layout:
        layout = circuit_layout(g)

    if rows:
        minrow,maxrow = rows
        vertices = [v for v in g.vertices() if (minrow<=g.row(v) and g.row(v) <=maxrow)]
        edges = [e for e in g.edges() if g.edge_s(e) in vertices and g.edge_t(e) in vertices]
    else:
        vertices = g.vertices()
        edges = g.edges()
    
    for e in edges:
        sp = layout[g.edge_s(e)]
        tp = layout[g.edge_t(e)]
        et = g.edge_type(e)
        n_row = vs_on_row.get(g.row(g.edge_s(e)), 0)

        
        dx = tp[0] - sp[0]
        dy = tp[1] - sp[1]
        bend_wire = (dx == 0) and h_edge_draw == 'blue' and n_row > 2
        ecol = '#0099ff' if h_edge_draw == 'blue' and et == 2 else 'black'

        if bend_wire:
            bend = 0.25
            mid = (sp[0] + 0.5 * dx + bend * dy, sp[1] + 0.5 * dy - bend * dx)

            pth = path.Path([sp,mid,tp], [path.Path.MOVETO, path.Path.CURVE3, path.Path.LINETO])
            patch = patches.PathPatch(pth, edgecolor=ecol, linewidth=0.8, fill=False)
            ax.add_patch(patch)
        else:
            pos = 0.5 if dx == 0 or dy == 0 else 0.4
            mid = (sp[0] + pos*dx, sp[1] + pos*dy)
            ax.add_line(lines.Line2D([sp[0],tp[0]],[sp[1],tp[1]], color=ecol, linewidth=0.8, zorder=0))

        if h_edge_draw == 'box' and et == 2: #hadamard edge
            w = 0.2
            h = 0.15
            diag = math.sqrt(w*w+h*h)
            angle = math.atan2(dy,dx)
            angle2 = math.atan2(h,w)
            centre = (mid[0] - diag/2*math.cos(angle+angle2),
                      mid[1] - diag/2*math.sin(angle+angle2))
            ax.add_patch(patches.Rectangle(centre,w,h,angle=angle/math.pi*180,facecolor='yellow',edgecolor='black'))

        #plt.plot([sp[0],tp[0]],[sp[1],tp[1]], 'k', zorder=0, linewidth=0.8)
    
    for v in vertices:
        p = layout[v]
        t = g.type(v)
        a = g.phase(v)
        a_offset = 0.5

        if t == VertexType.Z:
            ax.add_patch(patches.Circle(p, 0.2, facecolor='green', edgecolor='black', zorder=1))
        elif t == VertexType.X:
            ax.add_patch(patches.Circle(p, 0.2, facecolor='red', edgecolor='black', zorder=1))
        elif t == VertexType.H_BOX:
            ax.add_patch(patches.Rectangle((p[0]-0.1, p[1]-0.1), 0.2, 0.2, facecolor='yellow', edgecolor='black'))
            a_offset = 0.25
        else:
            ax.add_patch(patches.Circle(p, 0.1, facecolor='black', edgecolor='black', zorder=1))

        if labels: plt.text(p[0]+0.25, p[1]+0.25, str(v), ha='center', color='gray', fontsize=5)
        if a: plt.text(p[0], p[1]-a_offset, phase_to_s(a, t), ha='center', color='blue', fontsize=8)
    
    ax.axis('equal')
    plt.close()
    return fig1
def artist_reference():
    import matplotlib.path as mpath
    import matplotlib.lines as mlines
    import matplotlib.patches as mpatches
    from matplotlib.collections import PatchCollection

    def label(xy, text):
        y = xy[
            1] - 0.15  # shift y-value for label so that it's below the artist
        plt.text(xy[0], y, text, ha="center", family='sans-serif',
                 size=14)  # ha = horizontalalignment

    fig, ax = plt.subplots()
    grid = np.mgrid[0.2:0.8:0.3, 0.2:0.8:0.3].reshape(2, -1).T
    patches = []
    # add a circle
    circle = mpatches.Circle(grid[0], 0.1, ec="none")
    patches.append(circle)
    label(grid[0], "Circle")
    # add a rectangle
    rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none")
    patches.append(rect)
    label(grid[1], "Rectangle")
    # add a wedge
    wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none")
    patches.append(wedge)
    label(grid[2], "Wedge")
    # add a Polygon
    polygon = mpatches.RegularPolygon(grid[3], 5, 0.1)
    patches.append(polygon)
    label(grid[3], "Polygon")
    # add an ellipse
    ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1)
    patches.append(ellipse)
    label(grid[4], "Ellipse")
    # add an arrow
    arrow = mpatches.Arrow(grid[5, 0] - 0.05,
                           grid[5, 1] - 0.05,
                           0.1,
                           0.1,
                           width=0.1)
    patches.append(arrow)
    label(grid[5], "Arrow")
    # add a path patch
    Path = mpath.Path
    path_data = [(Path.MOVETO, [0.018, -0.11]), (Path.CURVE4, [-0.031,
                                                               -0.051]),
                 (Path.CURVE4, [-0.115, 0.073]), (Path.CURVE4, [-0.03, 0.073]),
                 (Path.LINETO, [-0.011, 0.039]), (Path.CURVE4, [0.043, 0.121]),
                 (Path.CURVE4, [0.075, -0.005]), (Path.CURVE4, [0.035,
                                                                -0.027]),
                 (Path.CLOSEPOLY, [0.018, -0.11])]
    codes, verts = zip(*path_data)
    path = mpath.Path(verts + grid[6], codes)
    patch = mpatches.PathPatch(path)
    patches.append(patch)
    label(grid[6], "PathPatch")
    # add a fancy box
    fancybox = mpatches.FancyBboxPatch(grid[7] - [0.025, 0.05],
                                       0.05,
                                       0.1,
                                       boxstyle=mpatches.BoxStyle("Round",
                                                                  pad=0.02))
    patches.append(fancybox)
    label(grid[7], "FancyBboxPatch")
    # add a line
    x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]])
    line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3)
    label(grid[8], "Line2D")
    colors = np.linspace(0, 1, len(patches))
    collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
    collection.set_array(np.array(colors))
    ax.add_collection(collection)
    ax.add_line(line)
    plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
    plt.axis('equal')
    plt.axis('off')
    plt.show()
    pass
Beispiel #19
0
def map(h2: Histogram2D,
        ax: Axes,
        *,
        show_zero: bool = True,
        show_values: bool = False,
        show_colorbar: bool = True,
        x=None,
        y=None,
        **kwargs):
    """Coloured-rectangle plot of 2D histogram.

    Parameters
    ----------
    show_zero : Whether to show coloured box for bins with 0 frequency (otherwise background).
    show_values : Whether to show labels with frequencies/densities in the middle of the bin


    text_color : Optional
        Colour of text descriptions
    text_alpha : Optional[float]
        Alpha for the text labels only
    x : Optional[Callable]
        Transformation of x bin coordinates
    y : Optional[Callable]
        Transformation of y bin coordinates
    zorder : float
        z-order in the axis (higher number above lower)

    See Also
    --------
    image, polar_map, surface_map

    Notes
    -----
    If you transform axes using x or y parameters, the deduction of axis limits
    does not work well automatically. Please, make sure to attend to it yourself.
    The densities in transformed maps are calculated from original bins.
    """
    # Detect transformation
    transformed = False
    if x is not None or y is not None:
        if not x:
            x = lambda x, y: x
        if not y:
            y = lambda x, y: y
        transformed = True

    value_format = kwargs.pop("value_format", lambda x: str(x))
    # TODO: Implement correctly the text_kwargs

    if isinstance(value_format, str):
        format_str = "{0:" + value_format + "}"
        value_format = lambda x: format_str.format(x)

    rect_args = {}
    if "zorder" in kwargs:
        rect_args["zorder"] = kwargs.pop("zorder")

    data = get_data(h2,
                    cumulative=False,
                    flatten=True,
                    density=kwargs.pop("density", False))

    cmap = _get_cmap(kwargs)
    norm, cmap_data = _get_cmap_data(data, kwargs)
    colors = cmap(cmap_data)

    xpos, ypos = (arr.flatten() for arr in h2.get_bin_left_edges())
    dx, dy = (arr.flatten() for arr in h2.get_bin_widths())
    text_x, text_y = (arr.flatten() for arr in h2.get_bin_centers())

    _apply_xy_lims(ax, h2, data=data, kwargs=kwargs)
    _add_labels(ax, h2, kwargs)

    ax.autoscale_view()

    alphas = _get_alpha_data(cmap_data, kwargs)
    if np.isscalar(alphas):
        alphas = np.ones_like(data) * alphas

    for i in range(len(xpos)):
        bin_color = colors[i]
        alpha = alphas[i]

        if data[i] != 0 or show_zero:
            if not transformed:
                rect = plt.Rectangle([xpos[i], ypos[i]],
                                     dx[i],
                                     dy[i],
                                     facecolor=bin_color,
                                     edgecolor=kwargs.get(
                                         "grid_color", cmap(0.5)),
                                     lw=kwargs.get("lw", 0.5),
                                     alpha=alpha,
                                     **rect_args)
                tx, ty = text_x[i], text_y[i]

            else:
                # See http://matplotlib.org/users/path_tutorial.html
                points = ((xpos[i], ypos[i]), (xpos[i] + dx[i], ypos[i]),
                          (xpos[i] + dx[i], ypos[i] + dy[i]),
                          (xpos[i], ypos[i] + dy[i]), (xpos[i], ypos[i]))

                verts = [(x(*p), y(*p)) for p in points]

                codes = [
                    path.Path.MOVETO,
                    path.Path.LINETO,
                    path.Path.LINETO,
                    path.Path.LINETO,
                    path.Path.CLOSEPOLY,
                ]

                rect_path = path.Path(verts, codes)
                rect = patches.PathPatch(rect_path,
                                         facecolor=bin_color,
                                         edgecolor=kwargs.get(
                                             "grid_color", cmap(0.5)),
                                         lw=kwargs.get("lw", 0.5),
                                         alpha=alpha,
                                         **rect_args)

                tx = x(text_x[i], text_y[i])
                ty = y(text_x[i], text_y[i])
            ax.add_patch(rect)

            if show_values:
                text = value_format(data[i])
                yiq_y = np.dot(bin_color[:3], [0.299, 0.587, 0.114])

                text_color = kwargs.get("text_color", None)
                if not text_color:
                    if yiq_y > 0.5:
                        text_color = (0.0, 0.0, 0.0,
                                      kwargs.get("text_alpha", alpha))
                    else:
                        text_color = (1.0, 1.0, 1.0,
                                      kwargs.get("text_alpha", alpha))
                ax.text(tx,
                        ty,
                        text,
                        horizontalalignment='center',
                        verticalalignment='center',
                        color=text_color,
                        clip_on=True,
                        **rect_args)

    if show_colorbar:
        _add_colorbar(ax, cmap, cmap_data, norm)
Beispiel #20
0
    def _add_solids(self, X, Y, C):
        """
        Draw the colors using :class:`~matplotlib.patches.Patch`;
        optionally add separators.
        """
        # Save, set, and restore hold state to keep pcolor from
        # clearing the axes. Ordinarily this will not be needed,
        # since the axes object should already have hold set.
        _hold = self.ax.ishold()
        self.ax.hold(True)

        kw = {
            'alpha': self.alpha,
        }

        n_segments = len(C)

        # ensure there are sufficent hatches
        hatches = self.mappable.hatches * n_segments

        patches = []
        for i in xrange(len(X) - 1):
            val = C[i][0]
            hatch = hatches[i]

            xy = np.array([[X[i][0], Y[i][0]], [X[i][1], Y[i][0]],
                           [X[i + 1][1], Y[i + 1][0]],
                           [X[i + 1][0], Y[i + 1][1]]])

            if self.orientation == 'horizontal':
                # if horizontal swap the xs and ys
                xy = xy[..., ::-1]

            patch = mpatches.PathPatch(mpath.Path(xy),
                                       facecolor=self.cmap(self.norm(val)),
                                       hatch=hatch,
                                       edgecolor='none',
                                       linewidth=0,
                                       antialiased=False,
                                       **kw)

            self.ax.add_patch(patch)
            patches.append(patch)

        if self.solids_patches:
            for solid in self.solids_patches:
                solid.remove()

        self.solids_patches = patches

        if self.dividers is not None:
            self.dividers.remove()
            self.dividers = None

        if self.drawedges:
            self.dividers = collections.LineCollection(
                self._edges(X, Y),
                colors=(mpl.rcParams['axes.edgecolor'], ),
                linewidths=(0.5 * mpl.rcParams['axes.linewidth'], ))
            self.ax.add_collection(self.dividers)

        self.ax.hold(_hold)
Beispiel #21
0
def locfdr(zz, bre = 120, df = 7, pct = 0., pct0 = 1./4, nulltype = 1, type = 0, plot = 1, mult = None, mlests = None, 
		main = ' ', sw = 0, verbose = True, showplot = True, saveplot = False, saveroot = 'locfdr', saveext = 'pdf', savestamp = False):
	"""Computes local false discovery rates.

	This is Abhinav Nellore's Python implementation of the R function locfdr() v1.1.7, originally written by Bradley Efron, 
	Brit B. Turnbull, and Balasubramanian Narasimhan; and later enhanced by Alyssa Frazee, Leonardo Collado-Torres, and Jeffrey Leek 
	(see https://github.com/alyssafrazee/derfinder/blob/master/R/locfdrFit.R ). It is licensed under the GNU GPL v2.
	See COPYING for more information.
	
	The port is relatively faithful. Variable names are almost precisely the same; if the original variable name contained a period, that
	period is replaced by an underscore here. (So 'Cov2.out' in the R is 'Cov2_out' in the Python.)
	To access returned values:
	(in R)        --- results = locfdr(...)
					  results$fdr
			          results$z.2
	(in Python)   --- results = locfdr(...)
					  results['fdr']
					  results['z_2']
	Some returned values are pandas Series and DataFrames. An introduction to pandas data structures is available at
	http://pandas.pydata.org/pandas-docs/dev/dsintro.html .

	A nearly complete description of arguments and returned values may be found at 
	http://cran.r-project.org/web/packages/locfdr/vignettes/locfdr-example.pdf .

	Additional arguments in this version:
		 verbose: (True or False) --- If True, outputs warnings.
	     showplot: (True or False) --- If True, displays plot. Ignored if plot = 0.
	     saveplot: (True or False) --- If True, saves plot according to constraints specified by saveroot, saveext, and savestamp.
	     							   Ignored if plot = 0.
	     saveroot: (Any string that constitutes a valid filename.) --- Specifies prefix of file to save. Ignored if saveplot = False.
	     saveext: (Most valid image file extensions work here. Try 'png', 'pdf', 'ps', 'eps', or 'svg'.) --- Selects file format and extension.
	     	Ignored if saveplot = False.
	     savestamp: (True or False) --- If True, date/timestamp is appended to filename prefix; this helps prevent overwriting old saves.
	     	Ignored if saveplot = False.

	 Additional returned values in this version:
		yt: Heights of pink histogram bars that appear on the plots (i.e., heights of alt. density's histogram).
		x: Locations of pinkfl histogram bars that appear on the plots (locations of alt. density's histogram).
		mlest_lo AND mlest_hi: If the function outputs a warning message that reads "please rerun with mlest parameters = ...",
			these parameters are contained in mlest_lo and mlest_hi .
		needsfix: 1 if a rerun warning is output; otherwise 0.
		nulldens: y-values of estimated null distribution density.
		nulldens: y-values of estimated full (mixture) density."""
	call = it.stack()
	zz = np.array(zz)
	mlest_lo = None
	mlest_hi = None
	yt = None
	x = None
	needsfix = 0
	try:
		brelength = len(bre)
		lo = min(bre)
		up = max(bre)
		bre = brelength
	except TypeError:
		try:
			len(pct)
			lo = pct[0]
			up = pct[1]
			# the following line is present to mimic how R handles [if (pct > 0)] (see code below) when pct is an array
			pct = pct[0]
		except TypeError:
			if pct == 0:
				lo = min(zz)
				up = max(zz)
			elif pct < 0:
				med = np.median(zz)
				lo = med + (1 - pct) * (min(zz) - med)
				up = med + (1 - pct) * (max(zz) - med)
			elif pct > 0:
				lo = np.percentile(zz, pct * 100)
				up = np.percentile(zz, (1 - pct) * 100)
	zzz = np.array([max(min(el, up), lo) for el in zz])
	breaks = np.linspace(lo, up, bre)
	x = (breaks[1:] + breaks[0:-1]) / 2.
	y = np.histogram(zzz, bins = len(breaks) - 1)[0]
	yall = y
	K = len(y)
	N = len(zz)
	if pct > 0:
		y[0] = min(y[0], 1.)
		y[K-1] = min(y[K-1], 1)
	if not type:
		basismatrix = rf.ns(x, df)
		X = np.ones((basismatrix.shape[0], basismatrix.shape[1]+1), dtype=np.float64)
		X[:, 1:] = basismatrix
		f = glm("y ~ basismatrix", data = dict(y=np.matrix(y).transpose(), basismatrix=basismatrix), 
				family=families.Poisson()).fit().fittedvalues
	else:
		basismatrix = rf.poly(x, df)
		X = np.ones((basismatrix.shape[0], basismatrix.shape[1]+1), dtype=np.float64)
		X[:, 1:] = basismatrix
		f = glm("y ~ basismatrix", data = dict(y=np.matrix(y).transpose(), basismatrix=basismatrix), 
			family=families.Poisson()).fit().fittedvalues
	fulldens = f
	l = np.log(f)
	Fl = f.cumsum()
	Fr = f[::-1].cumsum()
	D = ((y - f) / np.sqrt((f + 1)))
	D = sum(np.power(D[1:(K-1)], 2)) / (K - 2 - df)
	if D > 1.5:
		wa.warn("f(z) misfit = " + str(round(D,1)) + ". Rerun with larger df.")
	if nulltype == 3:
		fp0 = pd.DataFrame(np.zeros((6,4)).fill(np.nan), index=['thest', 'theSD', 'mlest', 'mleSD', 'cmest', 'cmeSD'], 
			columns=['delta', 'sigleft', 'p0', 'sigright'])
	else:
		fp0 = pd.DataFrame(np.zeros((6,3)).fill(np.nan), index=['thest', 'theSD', 'mlest', 'mleSD', 'cmest', 'cmeSD'], 
			columns=['delta', 'sigma', 'p0'])
	fp0.loc['thest'][0:2] = np.array([0,1])
	fp0.loc['theSD'][0:2] = 0
	imax = np.where(max(l)==l)[0][0]
	xmax = x[imax]
	try:
		len(pct)
		pctlo = pct0[0]
		pctup = pct0[1]
	except TypeError:
		pctup = 1 - pct0
		pctlo = pct0
	lo0 = np.percentile(zz, pctlo*100)
	hi0 = np.percentile(zz, pctup*100)
	nx = len(x)
	i0 = np.array([i for i, el in enumerate(x) if el > lo0 and el < hi0])
	x0 = np.array([el for el in x if el > lo0 and el < hi0])
	y0 = np.array([el for i,el in enumerate(l) if x[i] > lo0 and x[i] < hi0])
	xsubtract = x0 - xmax
	X00 = np.zeros((2, len(xsubtract)))
	if nulltype == 3:
		X00[0, :] = np.power(xsubtract, 2)
		X00[1, :] = [max(el, 0)*max(el, 0) for el in xsubtract]
	else:
		X00[0, :] = xsubtract
		X00[1, :] = np.power(xsubtract, 2)
	X00 = X00.transpose()
	co = glm("y0 ~ X00", data = dict(y0=y0, X00=X00)).fit().params
	# these errors may not be necessary
	if nulltype == 3 and ((pd.isnull(co[1]) or pd.isnull(co[2])) or (co[1] >= 0 or co[1] + co[2] >= 0)):
			raise EstimationError('CM estimation failed. Rerun with nulltype = 1 or 2.')
	elif pd.isnull(co[2]) or co[2] >= 0:
		if nulltype == 2:
			raise EstimationError('CM estimation failed. Rerun with nulltype = 1.')
		elif nulltype != 3:
			xsubtract2 = x - xmax
			X0 = np.ones((3, len(xsubtract2)))
			X0[1, :] = xsubtract2
			X0[2, :] = np.power(xsubtract2, 2)
			X0 = X0.transpose()
			wa.warn('CM estimation failed; middle of histogram nonnormal')
	else:
		xsubtract2 = x - xmax
		X0 = np.ones((3, len(xsubtract2)))
		if nulltype == 3:
			X0[1, :] = np.power(xsubtract2, 2)
			X0[2, :] = [max(el, 0)*max(el, 0) for el in xsubtract2]
			sigs = np.array([1/np.sqrt(-2*co[1]), 1/np.sqrt(-2*(co[1]+co[2]))])
			fp0.loc['cmest'][0] = xmax
			fp0.loc['cmest'][1] = sigs[0]
			fp0.loc['cmest'][3] = sigs[1]
		else:
			X0[1, :] = xsubtract2
			X0[2, :] = np.power(xsubtract2, 2)
			xmaxx = -co[1] / (2 * co[2]) + xmax
			sighat = 1 / np.sqrt(-2 * co[2])
			fp0.loc['cmest'][[0,1]] = [xmaxx, sighat]
		X0 = X0.transpose()
		l0 = np.array((X0 * np.matrix(co).transpose()).transpose())[0]
		f0 = np.exp(l0)
		p0 = sum(f0) / float(sum(f))
		f0 = f0 / p0
		fp0.loc['cmest'][2] = p0
	b = 4.3 * np.exp(-0.26 * np.log10(N))
	if mlests == None:
		med = np.median(zz)
		sc = (np.percentile(zz, 75) - np.percentile(zz, 25)) / (2 * stats.norm.ppf(.75))
		mlests = lf.locmle(zz, xlim = np.array([med, b * sc]))
		if N > 5e05:
			if verbose:
				wa.warn('length(zz) > 500,000: an interval wider than the optimal one was used for maximum likelihood estimation. To use the optimal interval, rerun with mlests = [' + str(mlests[0]) + ', ' + str(b * mlests[1]) + '].')
			mlest_lo = mlests[0]
			mlest_hi = b * mlests[1]
			needsfix = 1
			mlests = lf.locmle(zz, xlim = [med, sc])
	if not pd.isnull(mlests[0]):
		if N > 5e05:
			b = 1
		if nulltype == 1:
			Cov_in = {'x' : x, 'X' : X, 'f' : f, 'sw' : sw}
			ml_out = lf.locmle(zz, xlim = [mlests[0], b * mlests[1]], d = mlests[0], s = mlests[1], Cov_in = Cov_in)
			mlests = ml_out['mle']
		else:
			mlests = lf.locmle(zz, xlim = [mlests[0], b * mlests[1]], d = mlests[0], s = mlests[1])
		fp0.loc['mlest'][0:3] = mlests[0:3]
		fp0.loc['mleSD'][0:3] = mlests[3:6]
	if (not (pd.isnull(fp0.loc['mlest'][0]) or pd.isnull(fp0.loc['mlest'][1]) or pd.isnull(fp0.loc['cmest'][0]) or pd.isnull(fp0.loc['cmest'][1]))) and nulltype > 1:
		if abs(fp0.loc['cmest'][0] - mlests[0]) > 0.05 or abs(np.log(fp0.loc['cmest'][1] / mlests[1])) > 0.05:
			wa.warn('Discrepancy between central matching and maximum likelihood estimates. Consider rerunning with nulltype = 1.')
	if pd.isnull(mlests[0]):
		if nulltype == 1:
			if pd.isnull(fp0.loc['cmest'][1]):
				raise EstimationError('CM and ML estimation failed; middle of histogram is nonnormal.')
			else:
				raise EstimationError('ML estimation failed. Rerun with nulltype = 2.')
		else:
			wa.warn('ML estimation failed.')
	if nulltype < 2:
		xmaxx = mlests[0]
		xmax = mlests[0]
		delhat = mlests[0]
		sighat = mlests[1]
		p0 = mlests[2]
		f0 = np.array([stats.norm.pdf(el, delhat, sighat) for el in x])
		f0 = (sum(f) * f0) / sum(f0)
	fdr = np.array([min(el, 1) for el in (p0 * (f0 / f))])
	f00 = np.exp(-np.power(x, 2) / 2)
	f00 = (f00 * sum(f)) / sum(f00)
	p0theo = sum(f[i0]) / sum(f00[i0])
	fp0.loc['thest'][2] = p0theo
	fdr0 = np.array([min(el, 1) for el in ((p0theo * f00) / f)])
	f0p = p0 * f0
	if nulltype == 0:
		f0p = p0theo * f00
	F0l = f0p.cumsum()
	F0r = f0p[::-1].cumsum()
	Fdrl = F0l / Fl
	Fdrr = (F0r / Fr)[::-1]
	Int = (1 - fdr) * f * (fdr < 0.9)
	if np.any([x[i] <= xmax and fdr[i] == 1 for i in xrange(len(fdr))]):
		xxlo = min([el for i,el in enumerate(x) if el <= xmax and fdr[i] == 1])
	else:
		xxlo = xmax
	if np.any([x[i] >= xmax and fdr[i] == 1 for i in xrange(len(fdr))]):
		xxhi = max([el for i,el in enumerate(x) if el >= xmax and fdr[i] == 1])
	else:
		xxhi = xmax
	indextest = [i for i,el in enumerate(x) if el >= xxlo and el <= xxhi]
	if len(indextest) > 0:
		fdr[indextest] = 1
	indextest = [i for i,el in enumerate(x) if el <= xmax and fdr0[i] == 1]
	if len(indextest) > 0:
		xxlo = min(x[indextest])
	else:
		xxlo = xmax
	indextest = [i for i,el in enumerate(x) if el >= xmax and fdr0[i] == 1]
	if len(indextest) > 0:
		xxhi = max(x[indextest])
	else:
		xxhi = xmax
	indextest = [i for i,el in enumerate(x) if el >= xxlo and el <= xxhi]
	if len(indextest) > 0:
		fdr0[indextest] = 1
	if nulltype == 1:
		indextest = [i for i,el in enumerate(x) if el >= mlests[0] - mlests[1] and el <= mlests[0] + mlests[1]]
		fdr[indextest] = 1
		fdr0[indextest] = 1
	p1 = sum((1 - fdr) * f) / N
	p1theo = sum((1 - fdr0) * f) / N
	fall = f + (yall - y)
	Efdr = sum((1 - fdr) * fdr * fall) / sum((1 - fdr) * fall)
	Efdrtheo = sum((1 - fdr0) * fdr0 * fall) / sum((1 - fdr0) * fall)
	iup = [i for i,el in enumerate(x) if el >= xmax]
	ido = [i for i,el in enumerate(x) if el <= xmax]
	Eleft = sum((1 - fdr[ido]) * fdr[ido] * fall[ido]) / sum((1 - fdr[ido]) * fall[ido])
	Eleft0 = sum((1 - fdr0[ido]) * fdr0[ido] * fall[ido])/sum((1 - fdr0[ido]) * fall[ido])
	Eright = sum((1 - fdr[iup]) * fdr[iup] * fall[iup])/sum((1 - fdr[iup]) * fall[iup])
	Eright0 = sum((1 - fdr0[iup]) * fdr0[iup] * fall[iup])/sum((1 - fdr0[iup]) * fall[iup])
	Efdr = np.array([Efdr, Eleft, Eright, Efdrtheo, Eleft0, Eright0])
	for i,el in enumerate(Efdr):
		if pd.isnull(el):
			Efdr[i] = 1
	Efdr = pd.Series(Efdr, index=['Efdr', 'Eleft', 'Eright', 'Efdrtheo', 'Eleft0', 'Eright0'])
	if nulltype == 0:
		f1 = (1 - fdr0) * fall
	else:
		f1 = (1 - fdr) * fall
	if mult != None:
		try:
			mul = np.ones(len(mult) + 1)
			mul[1:] = mult
		except TypeError:
			mul = np.array([1, mult])
		EE = np.zeros(len(mul))
		for m in xrange(len(EE)):
			xe = np.sqrt(mul[m]) * x
			f1e = rf.approx(xe, f1, x, rule = 2, ties = 'mean')
			f1e = (f1e * sum(f1)) / sum(f1e)
			f0e = f0
			p0e = p0
			if nulltype == 0:
				f0e = f00
				p0e = p0theo
			fdre = (p0e * f0e) / (p0e * f0e + f1e)
			EE[m] = sum(f1e * fdre) / sum(f1e)
		EE = EE / EE[0]
		EE = pd.Series(EE, index=mult)
	Cov2_out = lf.loccov2(X, X0, i0, f, fp0.loc['cmest'], N)
	Cov0_out = lf.loccov2(X, np.ones((len(x), 1)), i0, f, fp0.loc['thest'], N)
	if sw == 3:
		if nulltype == 0:
			Ilfdr = Cov0_out['Ilfdr']
		elif nulltype == 1:
			Ilfdr = ml_out['Ilfdr']
		elif nulltype == 2:
			Ilfdr = Cov2_out['Ilfdr']
		else:
			raise InputError('When sw = 3, nulltype must be 0, 1, or 2.')
		return Ilfdr
	if nulltype == 0:
		Cov = Cov0_out['Cov']
	elif nulltype == 1:
		Cov = ml_out['Cov_lfdr']
	else:
		Cov = Cov2_out['Cov']
	lfdrse = np.sqrt(np.diag(Cov))
	fp0.loc['cmeSD'][0:3] = Cov2_out.loc['stdev'][[1,2,0]]
	if nulltype == 3:
		fp0.loc['cmeSD'][3] = fp0['cmeSD'][1]
	fp0.loc['theSD'][2] = Cov0_out['stdev'][0]
	if sw == 2:
		if nulltype == 0:
			pds = fp0.loc['thest'][[2, 0, 1]]
			stdev = fp0.loc['theSD'][[2, 0, 1]]
			pds_ = Cov0_out['pds_'].transpose()
		elif nulltype == 1:
			pds = fp0.loc['mlest'][[2, 0, 1]]
			stdev = fp0.loc['mleSD'][[2, 0, 1]]
			pds_ = ml_out['pds_'].transpose()
		elif nulltype == 2:
			pds = fp0.loc['cmest'][[2, 0, 1]]
			stdev = fp0.loc['cmeSD'][[2, 0, 1]]
			pds_ = Cov2_out['pds_'].transpose()
		else:
			raise InputError('When sw = 2, nulltype must equal 0, 1, or 2.')
		pds_ = pd.DataFrame(pds_, columns=['p0', 'delhat', 'sighat'])
		pds = pd.Series(pds, index=['p0', 'delhat', 'sighat'])
 		stdev = pd.Series(stdev, index=['sdp0', 'sddelhat', 'sdsighat'])
		return pd.Series({'pds': pds, 'x': x, 'f': f, 'pds_' : pds_, 'stdev' : stdev})
	p1 = np.arange(0.01, 1, 0.01)
	cdf1 = np.zeros((2,99))
	cdf1[0, :] = p1
	if nulltype == 0:
		fd = fdr0
	else:
		fd = fdr
	for i in xrange(99):
		cdf1[1, i] = sum([el for j,el in enumerate(f1) if fd[j] <= p1[i]])
	cdf1[1, :] = cdf1[1, :] / cdf1[1, -1]
	cdf1 = cdf1.transpose()
	if nulltype != 0:
		mat = pd.DataFrame(np.vstack((x, fdr, Fdrl, Fdrr, f, f0, f00, fdr0, yall, lfdrse, f1)), 
			index=['x', 'fdr', 'Fdrleft', 'Fdrright', 'f', 'f0', 'f0theo', 'fdrtheo', 'counts', 'lfdrse', 'p1f1'])
	else:
		mat = pd.DataFrame(np.vstack((x, fdr, Fdrl, Fdrr, f, f0, f00, fdr0, yall, lfdrse, f1)), 
			index=['x', 'fdr', 'Fdrltheo', 'Fdrrtheo', 'f', 'f0', 'f0theo', 'fdrtheo', 'counts', 'lfdrsetheo', 'p1f1'])
	z_2 = np.array([np.nan, np.nan])
	m = sorted([(i, el) for i, el in enumerate(fd)], key=lambda nn: nn[1])[-1][0]
	if fd[-1] < 0.2:
		z_2[1] = rf.approx(fd[m:], x[m:], 0.2, ties = 'mean')
	if fd[0] < 0.2:
		z_2[0] = rf.approx(fd[0:m], x[0:m], 0.2, ties = 'mean')
	if nulltype == 0:
		nulldens = p0theo * f00
	else:
		nulldens = p0 * f0
	yt = np.array([max(el, 0) for el in (yall * (1 - fd))])
	# construct plots
	if plot > 0:
		try:
			import matplotlib.pyplot as plt
			import matplotlib.patches as patches
			import matplotlib.path as path
		except ImportError:
			print 'matplotlib is required for plotting, but it was not found. Rerun with plot = 0 to turn off plots.'
			print 'locfdr-python was tested on matplotlib 1.3.0.'
			raise
		fig = plt.figure(figsize=(14, 8))
		if plot == 4:
			histplot = fig.add_subplot(131)
			fdrFdrplot = fig.add_subplot(132)
			f1cdfplot = fig.add_subplot(133)
		elif plot == 2 or plot == 3:
			histplot = fig.add_subplot(121)
			if plot == 2:
				fdrFdrplot = fig.add_subplot(122)
			else:
				f1cdfplot = fig.add_subplot(122)
		elif plot == 1:
			histplot = fig.add_subplot(111)
		# construct histogram
		leftplt = breaks[:-1]
		rightplt = breaks[1:]
		bottomplt = np.zeros(len(leftplt))
		topplt = bottomplt + y
		XYplt = np.array([[leftplt,leftplt,rightplt,rightplt], [bottomplt,topplt,topplt,bottomplt]]).transpose()
		barpath = path.Path.make_compound_path_from_polys(XYplt)
		patch = patches.PathPatch(barpath, facecolor='white', edgecolor='#302f2f')
		histplot.add_patch(patch)
		histplot.set_xlim(leftplt[0], rightplt[-1])
		histplot.set_ylim(-1.5, (topplt.max()+1.5) * 0.1 + topplt.max())
		histplot.set_title(main)
		for k in xrange(K):
			histplot.plot([x[k], x[k]], [0, yt[k]], color='#e31d76', linewidth = 2)
		if nulltype == 3:
			histplot.set_xlabel('delta = ' + str(round(xmax, 3)) + ', sigleft = ' + str(round(sigs[0], 3))  
				+ ', sigright = ' + str(round(sigs[1], 3)) + ', p0 = ' + str(round(fp0.loc['cmest'][2], 3)))
		if nulltype == 1 or nulltype == 2:
			histplot.set_xlabel('MLE: delta = ' + str(round(mlests[0], 3)) + ', sigma = ' + str(round(mlests[1], 3))  
				+ ', p0 = ' + str(round(mlests[2], 3)) + '\nCME: delta = ' + str(round(fp0.loc['cmest'][0], 3)) 
				+  ', sigma = ' + str(round(fp0.loc['cmest'][1], 3)) + ', p0 = ' + str(round(fp0.loc['cmest'][2], 3)))
		histplot.set_ylabel('Frequency')
		histplot.plot(x, f, color='#3bbf53', linewidth = 3)
		if nulltype == 0:
			histplot.plot(x, p0theo * f00, linewidth = 3, linestyle = 'dashed', color = 'blue')
		else:
			histplot.plot(x, p0 * f0, linewidth = 3, linestyle = 'dashed', color = 'blue')
		if not pd.isnull(z_2[1]): 
			histplot.plot([z_2[1]], [-0.5], marker = '^', markersize = 16, markeredgecolor = 'red', markeredgewidth = 1.3, color = 'yellow')
		if not pd.isnull(z_2[0]): 
			histplot.plot([z_2[0]], [-0.5], marker = '^', markersize = 16, markeredgecolor = 'red', markeredgewidth = 1.3, color = 'yellow')
		if nulltype == 1 or nulltype == 2:
			Ef = Efdr[0]
		elif nulltype == 0: 
			Ef = Efdr[3]
		# construct fdr + Fdr plot
		if plot == 2 or plot == 4:
			if nulltype == 0:
				fdd = fdr0
			else:
				fdd = fdr
			fdrFdrplot.plot(x, fdd, linewidth = 3, color = 'black')
			fdrFdrplot.plot(x, Fdrl, linewidth = 3, color = 'red', linestyle = 'dashed')
			fdrFdrplot.plot(x, Fdrr, linewidth = 3, color = 'green', linestyle = 'dashed')
			fdrFdrplot.set_ylim(-0.05, 1.1)
			fdrFdrplot.set_title('fdr (solid); Fdr\'s (dashed)')
			fdrFdrplot.set_xlabel('Efdr = ' + str(round(Ef, 3)))
			fdrFdrplot.set_ylabel('fdd (black), Fdrl (red), and Fdrr (green)')
			fdrFdrplot.plot([0, 0], [0, 1], linestyle = 'dotted', color = 'red')
			fdrFdrplot.axhline(linestyle = 'dotted', color = 'red')
		# construct plot of f1 cdf of estimated fdr curve
		if plot == 3 or plot == 4:
			if sum([1 for el in cdf1[:, 1] if pd.isnull(el)]) == cdf1.shape[0]:
				wa.warning('cdf1 is not available.')
			else:
				f1cdfplot.plot(cdf1[:, 0], cdf1[:, 1], linewidth = 3, color = 'black')
				f1cdfplot.set_xlabel('fdr level\nEfdr = ' + str(round(Ef, 3)))
				f1cdfplot.set_ylabel('f1 proportion < fdr level')
				f1cdfplot.set_title('f1 cdf of estimated fdr')
				f1cdfplot.set_ylim(0, 1)
				f1cdfplot.plot([0.2, 0.2], [0, cdf1[19, 1]], color = 'blue', linestyle = 'dashed')
				f1cdfplot.plot([0, 0.2], [cdf1[19, 1], cdf1[19, 1]], color = 'blue', linestyle = 'dashed')
				f1cdfplot.text(0.05, cdf1[19, 1], str(round(cdf1[19, 1], 2)))
		if saveplot:
			if savestamp:
				import time, datetime
				plt.savefig(saveroot + '_' + '-'.join(str(el) for el in list(tuple(datetime.datetime.now().timetuple())[:6])) + '.' + saveext)
			else:
				plt.savefig(saveroot + '.' + saveext)
		if showplot:
			plt.show()
	if nulltype == 0:
		ffdr = rf.approx(x, fdr0, zz, rule = 2, ties = 'ordered')
	else:
		ffdr = rf.approx(x, fdr, zz, rule = 2, ties = 'ordered')
	if mult != None:
		return {'fdr' : ffdr, 'fp0' : fp0, 'Efdr' : Efdr, 'cdf1' : cdf1, 'mat' : mat, 'z_2' : z_2, 'yt' : yt, 'call' : call, 'x' : x, 'mlest_lo' : mlest_lo, 'mlest_hi' : mlest_hi, 'needsfix' : needsfix, 'nulldens' : nulldens, 'fulldens' : fulldens, 'mult' : EE}
	return {'fdr' : ffdr, 'fp0' : fp0, 'Efdr' : Efdr, 'cdf1' : cdf1, 'mat' : mat, 'z_2' : z_2, 'yt' : yt, 'call' : call, 'x' : x, 'mlest_lo' : mlest_lo, 'mlest_hi' : mlest_hi, 'needsfix' : needsfix, 'nulldens' : nulldens, 'fulldens' : fulldens}
import rectangle

codes = [
    Path.MOVETO,
    Path.LINETO,
    Path.LINETO,
    Path.LINETO,
    Path.CLOSEPOLY,
]

path = Path(rectangle.verts, codes)

fig = plt.figure()
ax = fig.add_subplot()
ax.set_title('BFP/kg')
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch)

fit = pd.read_csv("fit.csv", float_precision='high')

fit['weight'] = (
    fit['weight'].str.split()).apply(lambda x: float(x[0].replace(',', '.')))
fit['weight'] = fit['weight'].astype(float)

fit['bfp'] = (
    fit['bfp'].str.split()).apply(lambda x: float(x[0].replace(',', '.')))
fit['bfp'] = fit['bfp'].astype(float)

# plt.scatter(fit['weight'][0], fit['bfp'][0], color='orange', marker='*')

for i in range(len(fit.index) - 1):
def plot_one_double(zooniverse_id,
                    pathdict,
                    figno=1,
                    savefig=False,
                    anglepath='',
                    dbltype='radio'):

    # Make a four-panel plot of the consensus identification with marked bending angle and position angle for a double source

    cons = consensus.checksum(zooniverse_id)

    subject = subjects.find_one({'zooniverse_id': zooniverse_id})
    contours = get_contours(subject, pathdict)
    radio_components = contours['contours']

    # Plot image

    answer = cons['answer']

    # Download contour data

    sf_x = 500. / contours['width']
    sf_y = 500. / contours['height']

    verts_all = []
    codes_all = []
    components = contours['contours']

    for comp in components:

        # Order of bounding box components is (xmax,ymax,xmin,ymin)
        comp_xmax, comp_ymax, comp_xmin, comp_ymin = comp[0]['bbox']

        # Only plot radio components identified by the users as the consensus;
        # check on the xmax value to make sure
        for v in answer.itervalues():
            if comp_xmax in v['xmax']:

                for idx, level in enumerate(comp):
                    verts = [((p['x']) * sf_x, (p['y'] - 1) * sf_y)
                             for p in level['arr']]

                    codes = np.ones(len(verts), int) * Path.LINETO
                    codes[0] = Path.MOVETO

                    verts_all.extend(verts)
                    codes_all.extend(codes)

    try:
        path = Path(verts_all, codes_all)
        patch_black = patches.PathPatch(path,
                                        facecolor='none',
                                        edgecolor='black',
                                        lw=1)
    except AssertionError:
        print 'Users found no components for consensus match of %s' % zooniverse_id

    # Plot the infrared results

    fig = plt.figure(figno, (15, 4))
    fig.clf()
    ax3 = fig.add_subplot(143)
    ax4 = fig.add_subplot(144)

    colormaparr = [
        cm.hot_r, cm.Blues, cm.RdPu, cm.Greens, cm.PuBu, cm.YlGn, cm.Greys
    ][::-1]
    colorarr = ['r', 'b', 'm', 'g', 'c', 'y', 'k'][::-1]

    if len(answer) > 0:  # At least one galaxy was identified
        for idx, ans in enumerate(answer.itervalues()):

            if ans.has_key('peak_data'):

                # Plot the KDE map
                colormap = colormaparr.pop()
                ax3.imshow(np.rot90(ans['peak_data']['Z']),
                           cmap=colormap,
                           extent=[xmin, xmax, ymin, ymax])

                # Plot individual sources
                color = colorarr.pop()
                '''
                x_plot = [xt * 500./424 for xt in ans['ir_x'] if xt != -99.0]
                y_plot = [yt * 500./424 for yt in ans['ir_y'] if yt != -99.0]
                '''
                x_plot, y_plot = ans['ir_x'], ans['ir_y']
                ax3.scatter(x_plot,
                            y_plot,
                            c=color,
                            marker='o',
                            s=10,
                            alpha=1. / len(x_plot))

                ax4.plot([ans['ir_peak'][0]], [ans['ir_peak'][1]],
                         color=color,
                         marker='*',
                         markersize=12)

            elif ans.has_key('ir'):
                color = colorarr.pop()
                x_plot, y_plot = ans['ir']
                ax3.plot([x_plot], [y_plot],
                         color=color,
                         marker='o',
                         markersize=2)
                ax4.plot([x_plot], [y_plot],
                         color=color,
                         marker='*',
                         markersize=12)
            else:
                ax4.text(550, idx * 25, '#%i - no IR host' % idx, fontsize=11)

    ax3.set_xlim([0, 500])
    ax3.set_ylim([500, 0])
    ax3.set_title(zooniverse_id)
    ax3.set_aspect('equal')

    ax4.set_xlim([0, 500])
    ax4.set_ylim([500, 0])
    ax4.set_title('Consensus (%i/%i users)' %
                  (cons['n_users'], cons['n_total']))

    ax4.set_aspect('equal')

    # Display IR and radio images

    url_standard = subject['location']['standard']
    im_standard = Image.open(
        cStringIO.StringIO(urllib.urlopen(url_standard).read()))
    ax1 = fig.add_subplot(141)
    ax1.imshow(im_standard, origin='upper')
    ax1.set_title('WISE')

    url_radio = subject['location']['radio']
    im_radio = Image.open(cStringIO.StringIO(urllib.urlopen(url_radio).read()))
    ax2 = fig.add_subplot(142)
    ax2.imshow(im_radio, origin='upper')
    ax2.set_title(subject['metadata']['source'])
    ax2.get_yaxis().set_ticklabels([])

    ax3.get_yaxis().set_ticklabels([])

    # Plot contours identified as the consensus
    if len(answer) > 0:
        ax4.add_patch(patch_black)
        radio_centers = []
        for component in components:
            bbox = component[0]['bbox']

            # Draw centers of bounding boxes
            xradiocen = np.median((bbox[0], bbox[2])) / first_ir_scale_x
            yradiocen = np.median((bbox[1], bbox[3])) / first_ir_scale_y
            radio_centers.append((xradiocen, yradiocen))

            ax4.scatter(xradiocen, yradiocen, c='g', marker='s', s=15, alpha=1)

            # Draw edge of bounding box

            xradiomin = bbox[2] / first_ir_scale_x
            xradiomax = bbox[0] / first_ir_scale_x
            yradiomin = bbox[3] / first_ir_scale_y
            yradiomax = bbox[1] / first_ir_scale_y
            ax4.plot([xradiomin, xradiomin, xradiomax, xradiomax, xradiomin],
                     [yradiomin, yradiomax, yradiomax, yradiomin, yradiomin],
                     color='g')

        for ans in answer:
            if answer[ans].has_key('ir_peak'):
                # Optical counterpart position
                xc, yc = answer[ans]['ir_peak']

                # Position of radio sources for multi-peaked, single-component subjects
                if dbltype == "mps":
                    local_maxima = mps_cc(subject,
                                          pathdict,
                                          plot=False,
                                          verbose=False)
                    suffix = '' if len(local_maxima) == 1 else 's'
                    assert len(local_maxima) >= 2, \
                        "%i peak%s in first radio component of %s; must have exactly 2 peaks to plot bending angle using mps method." % (len(local_maxima),suffix,zooniverse_id)
                    x1 = local_maxima[0][1][0] / first_ir_scale_x
                    y1 = local_maxima[0][1][1] / first_ir_scale_y
                    x2 = local_maxima[1][1][0] / first_ir_scale_x
                    y2 = local_maxima[1][1][1] / first_ir_scale_y
                    ax4.scatter(x1,
                                y1,
                                color='darkorange',
                                marker='s',
                                s=15,
                                alpha=1)
                    ax4.scatter(x2,
                                y2,
                                color='darkorange',
                                marker='s',
                                s=15,
                                alpha=1)

                # Position of radio sources for double-lobed, two-component subjects
                elif len(radio_centers) == 2:
                    x1, y1 = radio_centers[0]
                    x2, y2 = radio_centers[1]
                else:
                    raise ValueError("Centers of radio boxes not defined.")

                m1 = (y1 - yc) / (x1 - xc)
                b1 = yc - m1 * xc
                m2 = (y2 - yc) / (x2 - xc)
                b2 = yc - m2 * xc

                xedge1 = 0 if x1 < xc else 500
                yedge1 = y1 - (x1 - xedge1) * (yc - y1) / (xc - x1)

                xedge2 = 0 if x2 < xc else 500
                yedge2 = y2 - (x2 - xedge2) * (yc - y2) / (xc - x2)

                # Draw and annotate the the bending angle

                ax4.plot([xedge1, xc], [yedge1, yc],
                         color='orange',
                         linestyle='--')
                ax4.plot([xedge2, xc], [yedge2, yc],
                         color='orange',
                         linestyle='--')
                alpha_deg = bending_angle(xc, yc, x1, y1, x2, y2) * 180 / np.pi
                ax4.text(550,
                         0,
                         r'$\alpha$ = %.1f deg' % alpha_deg,
                         fontsize=11)

                # Draw vector pointing north

                # Draw the bisector vector
                '''
                yd = y_bisect(xc,yc,xedge1,yedge1,xedge2,yedge2)
                ax4.arrow(xc,yc,-xc,yd-yc,head_width=20, head_length=40, fc='blue', ec='blue')
                '''

                # Compute the position angle with respect to north
                phi_deg = position_angle(xc, 500 - yc, x1, 500 - y1, x2,
                                         500 - y2) * 180 / np.pi
                ax4.text(550, 50, r'$\phi$ = %.1f deg' % phi_deg, fontsize=11)
                ax4.arrow(xc,
                          yc,
                          0,
                          -yc,
                          head_width=20,
                          head_length=40,
                          fc='grey',
                          ec='grey',
                          ls='dotted')

            else:
                print "No peak for %s" % zooniverse_id

    ax4.yaxis.tick_right()

    ax1.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax2.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax3.get_xaxis().set_ticks([0, 100, 200, 300, 400])
    ax4.get_xaxis().set_ticks([0, 100, 200, 300, 400, 500])

    plt.subplots_adjust(wspace=0.02)

    # Save hard copy of the figure
    if savefig:
        fig.savefig('%s/bending_angles/plots/individual/%sba_%s.pdf' %
                    (rgz_dir, anglepath, zooniverse_id))
        plt.close()
    else:
        plt.show()

    # Close figure after it's done; otherwise mpl complains about having thousands of stuff open

    return None
Beispiel #24
0
import matplotlib.pyplot as plt


fig, ax = plt.subplots()

Path = mpath.Path

path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.LINETO, (0.35, -1.1)),
    (Path.LINETO, (-1.75, 2.0)),
    (Path.LINETO, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.LINETO, (2.2, 3.2)),
    (Path.LINETO, (3, 0.05)),
    (Path.LINETO, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
]

codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='orange', alpha=0.152343)
ax.add_patch(patch)

# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'b-')

ax.grid()
ax.axis('equal')
plt.show()
Beispiel #25
0
def sankey(ax,
           outputs=[100.],
           outlabels=None,
           inputs=[100.],
           inlabels='',
           dx=40,
           dy=10,
           outangle=45,
           w=3,
           inangle=30,
           offset=2,
           **kwargs):
    """Draw a Sankey diagram.

    outputs: array of outputs, should sum up to 100%
    outlabels: output labels (same length as outputs),
    or None (use default labels) or '' (no labels)
    inputs and inlabels: similar for inputs
    dx: horizontal elongation
    dy: vertical elongation
    outangle: output arrow angle [deg]
    w: output arrow shoulder
    inangle: input dip angle
    offset: text offset
    **kwargs: propagated to Patch (e.g., fill=False)

    Return (patch,[intexts,outtexts]).
    """
    import matplotlib.patches as mpatches
    from matplotlib.path import Path

    outs = np.absolute(outputs)
    outsigns = np.sign(outputs)
    outsigns[-1] = 0  # Last output

    ins = np.absolute(inputs)
    insigns = np.sign(inputs)
    insigns[0] = 0  # First input

    assert sum(outs) == 100, "Outputs don't sum up to 100%"
    assert sum(ins) == 100, "Inputs don't sum up to 100%"

    def add_output(path, loss, sign=1):
        # Arrow tip height
        h = (loss / 2 + w) * np.tan(outangle / 180. * np.pi)
        move, (x, y) = path[-1]  # Use last point as reference
        if sign == 0:  # Final loss (horizontal)
            path.extend([
                (Path.LINETO, [x + dx, y]),
                (Path.LINETO, [x + dx, y + w]),
                (Path.LINETO, [x + dx + h, y - loss / 2]),  # Tip
                (Path.LINETO, [x + dx, y - loss - w]),
                (Path.LINETO, [x + dx, y - loss])
            ])
            outtips.append((sign, path[-3][1]))
        else:  # Intermediate loss (vertical)
            path.extend([
                (Path.CURVE4, [x + dx / 2, y]),
                (Path.CURVE4, [x + dx, y]),
                (Path.CURVE4, [x + dx, y + sign * dy]),
                (Path.LINETO, [x + dx - w, y + sign * dy]),
                # Tip
                (Path.LINETO, [x + dx + loss / 2, y + sign * (dy + h)]),
                (Path.LINETO, [x + dx + loss + w, y + sign * dy]),
                (Path.LINETO, [x + dx + loss, y + sign * dy]),
                (Path.CURVE3, [x + dx + loss, y - sign * loss]),
                (Path.CURVE3, [x + dx / 2 + loss, y - sign * loss])
            ])
            outtips.append((sign, path[-5][1]))

    def add_input(path, gain, sign=1):
        h = (gain / 2) * np.tan(inangle / 180. * np.pi)  # Dip depth
        move, (x, y) = path[-1]  # Use last point as reference
        if sign == 0:  # First gain (horizontal)
            path.extend([
                (Path.LINETO, [x - dx, y]),
                (Path.LINETO, [x - dx + h, y + gain / 2]),  # Dip
                (Path.LINETO, [x - dx, y + gain])
            ])
            xd, yd = path[-2][1]  # Dip position
            indips.append((sign, [xd - h, yd]))
        else:  # Intermediate gain (vertical)
            path.extend([
                (Path.CURVE4, [x - dx / 2, y]),
                (Path.CURVE4, [x - dx, y]),
                (Path.CURVE4, [x - dx, y + sign * dy]),
                # Dip
                (Path.LINETO, [x - dx - gain / 2, y + sign * (dy - h)]),
                (Path.LINETO, [x - dx - gain, y + sign * dy]),
                (Path.CURVE3, [x - dx - gain, y - sign * gain]),
                (Path.CURVE3, [x - dx / 2 - gain, y - sign * gain])
            ])
            xd, yd = path[-4][1]  # Dip position
            indips.append((sign, [xd, yd + sign * h]))

    outtips = []  # Output arrow tip dir. and positions
    urpath = [(Path.MOVETO, [0, 100])]  # 1st point of upper right path
    lrpath = [(Path.LINETO, [0, 0])]  # 1st point of lower right path
    for loss, sign in zip(outs, outsigns):
        add_output(sign >= 0 and urpath or lrpath, loss, sign=sign)

    indips = []  # Input arrow tip dir. and positions
    llpath = [(Path.LINETO, [0, 0])]  # 1st point of lower left path
    ulpath = [(Path.MOVETO, [0, 100])]  # 1st point of upper left path
    for gain, sign in reversed(list(zip(ins, insigns))):
        add_input(sign <= 0 and llpath or ulpath, gain, sign=sign)

    def revert(path):
        """A path is not just revertable by path[::-1] because of Bezier
        curves."""
        rpath = []
        nextmove = Path.LINETO
        for move, pos in path[::-1]:
            rpath.append((nextmove, pos))
            nextmove = move
        return rpath

    # Concatenate subpathes in correct order
    path = urpath + revert(lrpath) + llpath + revert(ulpath)

    codes, verts = zip(*path)
    verts = np.array(verts)

    # Path patch
    path = Path(verts, codes)
    patch = mpatches.PathPatch(path, **kwargs)
    ax.add_patch(patch)

    if False:  # DEBUG
        print("urpath", urpath)
        print("lrpath", revert(lrpath))
        print("llpath", llpath)
        print("ulpath", revert(ulpath))
        xs, ys = zip(*verts)
        ax.plot(xs, ys, 'go-')

    # Labels

    def set_labels(labels, values):
        """Set or check labels according to values."""
        if labels == '':  # No labels
            return labels
        elif labels is None:  # Default labels
            return ['%2d%%' % val for val in values]
        else:
            assert len(labels) == len(values)
            return labels

    def put_labels(labels, positions, output=True):
        """Put labels to positions."""
        texts = []
        lbls = output and labels or labels[::-1]
        for i, label in enumerate(lbls):
            s, (x, y) = positions[i]  # Label direction and position
            if s == 0:
                t = ax.text(x + offset,
                            y,
                            label,
                            ha=output and 'left' or 'right',
                            va='center')
            elif s > 0:
                t = ax.text(x, y + offset, label, ha='center', va='bottom')
            else:
                t = ax.text(x, y - offset, label, ha='center', va='top')
            texts.append(t)
        return texts

    outlabels = set_labels(outlabels, outs)
    outtexts = put_labels(outlabels, outtips, output=True)

    inlabels = set_labels(inlabels, ins)
    intexts = put_labels(inlabels, indips, output=False)

    # Axes management
    ax.set_xlim(verts[:, 0].min() - dx, verts[:, 0].max() + dx)
    ax.set_ylim(verts[:, 1].min() - dy, verts[:, 1].max() + dy)
    ax.set_aspect('equal', adjustable='datalim')

    return patch, [intexts, outtexts]
def get_random_shape():
    out = []
    black_type = random.randint(0, 9)
    if black_type == 0:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        point_num = 10
        point_list = []
        left_x = random.randint(0, 127)
        left_y = random.randint(0, 127)
        for i in range(point_num):
            center_x = random.randint(0, 5)
            center_y = random.randint(0, 5)
            point_list.append((left_x + center_x, left_y + center_y))
        point_list = np.array(point_list)
        hull = cv.convexHull(point_list)
        # print(hull)
        src_tmp = cv.drawContours(src_tmp, [hull], 0, 255, -1)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, hull[0][0])
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 1:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        point_num = 15
        point_list = []
        left_x = random.randint(0, 127)
        left_y = random.randint(0, 127)
        for i in range(point_num):
            center_x = random.randint(0, 8)
            center_y = random.randint(0, 8)
            point_list.append((left_x + center_x, left_y + center_y))
        point_list = np.array(point_list)
        hull = cv.convexHull(point_list)
        # print(hull)
        src_tmp = cv.drawContours(src_tmp, [hull], 0, 255, -1)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, hull[0][0])
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 2 or black_type == 8:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        point_num = 15
        point_list = []
        left_x = random.randint(0, 127)
        left_y = random.randint(0, 127)
        for i in range(point_num):
            center_x = random.randint(0, 10)
            center_y = random.randint(0, 30)
            point_list.append((left_x + center_x, left_y + center_y))
        point_list = np.array(point_list)
        hull = cv.convexHull(point_list)
        src_tmp = cv.drawContours(src_tmp, [hull], 0, 255, -1)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, hull[0][0])
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 9:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        point_num = 15
        point_list = []
        left_x = random.randint(0, 127)
        left_y = random.randint(0, 127)
        for i in range(point_num):
            center_x = random.randint(0, 30)
            center_y = random.randint(0, 30)
            point_list.append((left_x + center_x, left_y + center_y))
        point_list = np.array(point_list)
        hull = cv.convexHull(point_list)
        src_tmp = cv.drawContours(src_tmp, [hull], 0, 255, -1)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, hull[0][0])
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 3 or black_type == 6:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        point_num = 10
        point_list = []
        left_x = random.randint(0, 127)
        left_y = random.randint(0, 127)
        for i in range(point_num):
            center_x = random.randint(0, 30)
            center_y = random.randint(0, 1)
            point_list.append((left_x + center_x, left_y + center_y))
        point_list = np.array(point_list)
        hull = cv.convexHull(point_list)
        # print(hull)
        src_tmp = cv.drawContours(src_tmp, [hull], 0, 255, -1)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, hull[0][0])
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 4:
        src_tmp = np.array(np.zeros((128, 128)), dtype='uint8')
        left_x = random.randint(0, 50)
        left_y = random.randint(0, 50)
        right_x = random.randint(80, 127)
        right_y = random.randint(80, 127)
        src_tmp = cv.line(src_tmp, (left_x, left_y), (right_x, right_y),
                          255,
                          random.randint(1, 2),
                          lineType=cv.LINE_AA)
        src_tmp = rotato(src_tmp, random.randint(0, 360), 1, (64, 64))
        out = src_tmp > 125
        return np.where(out, 1.0, 0)
    elif black_type == 5 or black_type == 7:
        n = random.randint(3, 5)
        r = 0.7
        N = n * 3 + 1  # number of points in the Path
        # There is the initial point and 3 points per cubic bezier curve. Thus, the curve will only pass though n points, which will be the sharp edges, the other 2 modify the shape of the bezier curve

        angles = np.linspace(0, 2 * np.pi, N)
        codes = np.full(N, Path.CURVE4)
        codes[0] = Path.MOVETO

        verts = np.stack((np.cos(angles), np.sin(angles))).T * (
            2 * r * np.random.random(N) + 1 - r)[:, None]
        verts[-1, :] = verts[
            0, :]  # Using this instad of Path.CLOSEPOLY avoids an innecessary straight line
        path = Path(verts, codes)

        fig = plt.figure()
        ax = fig.add_subplot(111)
        patch = patches.PathPatch(path, facecolor='none', lw=2)
        ax.add_patch(patch)

        ax.set_xlim(np.min(verts) * 1.1, np.max(verts) * 1.1)
        ax.set_ylim(np.min(verts) * 1.1, np.max(verts) * 1.1)
        ax.axis('off')  # removes the axis to leave only the shape
        plt.savefig('./1.png')
        plt.close()
        img = cv.imread('1.png', 0)
        try:
            _, c, h = cv.findContours(img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
        except:
            c, h = cv.findContours(img, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
        temp = np.zeros(img.shape, np.uint8) * 255

        cv.drawContours(temp, c, 1, 255, -1)
        temp = cv.resize(temp, (128, 128))
        temp = np.where(temp > 128, get_weight((64, 64)), 0.)
        src_tmp = rotato(temp,
                         random.randint(0, 360),
                         random.randint(4, 8) / 10,
                         center=(random.randint(30,
                                                100), random.randint(30, 100)))
        return src_tmp
 def print_diff(self, pca_modes, anm_modes):
     print("here I am in DIFF")
     import matplotlib.pyplot as plt
     from matplotlib.path import Path
     import matplotlib.patches as patches
     residues = self.ref_chain.getResnums()
     print_offset = residues[0]
     #Paper01:PCA-X-Ray:
     print_offset = 738
     plt.rcParams.update({'font.size': 24}) 
     plt.rcParams['xtick.major.pad'] = 10
     plt.rcParams['ytick.major.pad'] = 10
     
     a3d_pca = ((pca_modes[0].getArrayNx3())**2).sum(axis=1)**0.5
     a3d_anm = ((anm_modes[0].getArrayNx3())**2).sum(axis=1)**0.5
     a3d_all = a3d_pca - a3d_anm
     for count in range(1,6):
         #array with lenghts of vectors
         a3d_pca = ((pca_modes[count].getArrayNx3())**2).sum(axis=1)**0.5
         a3d_anm = ((anm_modes[count].getArrayNx3())**2).sum(axis=1)**0.5
         a3d_all = a3d_all + a3d_pca - a3d_anm
         
         
     show = plt.plot(a3d_all[:], label=("Difference"), lw=1.5)
     plt.xlabel('Residue index')
     plt.ylabel('|PCA| - |ANM|')         
     locs,labels = plt.xticks()
     new_labels = ['%d' % (a+print_offset) for a in locs]
     plt.xticks(locs,new_labels)
     lgd = plt.legend(loc='center right', bbox_to_anchor=(1.65,0.5))
     ##add boxes
     codes = [Path.MOVETO,
               Path.LINETO,
               Path.LINETO,
               Path.LINETO,
               Path.CLOSEPOLY,
               ]
     ### light green
     verts = [
              (95, -2.0), # left, bottom
              (95, 2.0), # left, top
              (115, 2.0), # right, top
              (115, -2.0), # right, bottom
              (0., 0.), # ignored
              ]
     path = Path(verts, codes)
     #add box around area of interest
     ax = plt.subplot()
     patch = patches.PathPatch(path, facecolor='#CCFFCC', lw=1)
     #patch = patches.PathPatch(path, facecolor='lightgreen', lw=1)
     ax.add_patch(patch)
     plt.axhline(y=0.0,xmin=0,xmax=3,c="black",linewidth=1.0,zorder=0)
     plt.savefig(str(pca_modes)+"_all_DIFF.pdf", bbox_extra_artists=(lgd, ), bbox_inches='tight')
     plt.clf()   
     
     
     for count in range(6):
         #array with lenghtes of vectors         
         a3d = ((pca_modes[count].getArrayNx3())**2).sum(axis=1)**0.5 - ((anm_modes[count].getArrayNx3())**2).sum(axis=1)**0.5         
         show = plt.plot(a3d[:], label=("Mode "+str(count+1)), lw=1.5)
     plt.xlabel('Residue index')
     plt.ylabel('|PCA| - |ANM|')   
     locs,labels = plt.xticks()
     new_labels = ['%d' % (a+print_offset) for a in locs]
     plt.xticks(locs,new_labels)
     lgd = plt.legend(loc='center right', bbox_to_anchor=(1.65,0.5))
     
     ##add boxes
     codes = [Path.MOVETO,
               Path.LINETO,
               Path.LINETO,
               Path.LINETO,
               Path.CLOSEPOLY,
               ]
     ### light green
     verts = [
              (95, -0.7), # left, bottom
              (95, 0.7), # left, top
              (115, 0.7), # right, top
              (115, -0.7), # right, bottom
              (0., 0.), # ignored
              ]
     
     path = Path(verts, codes)
     #add box around area of interest
     ax = plt.subplot()
     patch = patches.PathPatch(path, facecolor='#CCFFCC', lw=1)
     ax.add_patch(patch)
     plt.axhline(y=0.0,xmin=0,xmax=3,c="black",linewidth=1.0,zorder=0)
     plt.savefig(str(pca_modes)+"_ANM_PCA_DIFF.pdf", bbox_extra_artists=(lgd, ), bbox_inches='tight')
                verts = list(polygon.exterior.coords)
                codes = [Path.LINETO] * len(verts)
                codes[0] = Path.MOVETO
                codes[-1] = Path.CLOSEPOLY

                path = Path(verts, codes)
                return path

            p_min = sess.run(concepts[label].p_min)
            p_max = sess.run(concepts[label].p_max)
            cuboids = zip(p_min, p_max)
            if not isnan(p_min[0][0]):
                core_path = _path_for_core(cuboids, 0, 1)
                core_patch = patches.PathPatch(core_path,
                                               facecolor='grey',
                                               lw=2,
                                               alpha=0.4)
                ax.add_patch(core_patch)
        elif ltn.default_type == "prototype":
            # plot the prototype
            prototypes = sess.run(concepts[label].prototypes)
            for p in prototypes:
                ax.scatter(p[0], p[1], marker='x')
        ax.set_title(label)
        yg = ax.scatter(xs, ys, c=colors, marker='o')
        cb = fig.colorbar(colmap)
        counter += 1

    plt.show()

elif args.plot and config["num_dimensions"] == 3:
Beispiel #29
0
def render_and_save(Verts,
                    Codes,
                    line_width=5,
                    imsize=8,
                    canvas_size=600,
                    session_id='SESSION_ID',
                    age='AGE',
                    trial_num='TRIAL_NUM',
                    category='CATEGORY',
                    save=False):
    '''
    input: 
        line_width: how wide of strokes do we want? (int)
        imsize: how big of a picture do we want? (setting the size of the figure) 
        canvas_size: original canvas size on tablet?
        out_path: where do you want to save your images? currently hardcoded below.        
    output:
        rendered sketches into nested directories
    
    '''
    ## where do you want to save your cumulative drawings?
    out_path = os.path.join('./cumulative_drawings',
                            '{}_{}'.format(session_id, age),
                            '{}_{}'.format(trial_num, category))
    if not os.path.exists('./cumulative_drawings'):
        os.makedirs('./cumulative_drawings')
    if not os.path.exists(
            os.path.join('cumulative_drawings', '{}_{}'.format(
                session_id, age))):
        os.makedirs(
            os.path.join('cumulative_drawings',
                         '{}_{}'.format(session_id, age)))

    verts = Verts[0]
    codes = Codes[0]
    for i, verts in enumerate(Verts):
        codes = Codes[i]
        fig = plt.figure(figsize=(imsize, imsize))
        ax = plt.subplot(111)
        ax.axis('off')
        ax.set_xlim(0, canvas_size)
        ax.set_ylim(0, canvas_size)
        ### render sketch so far
        if len(verts) > 0:
            path = Path(verts, codes)
            patch = patches.PathPatch(path, facecolor='none', lw=line_width)
            ax.add_patch(patch)
            plt.gca().invert_yaxis(
            )  # y values increase as you go down in image
            plt.show()

        ## save out as png
        ## maybe to make it not render every single thing, use plt.ioff
        if save == True:
            if not os.path.exists(out_path):
                os.makedirs(out_path)
            fname = '{}_{}_{}_{}.png'.format(session_id, trial_num, category,
                                             i)
            filepath = os.path.join(out_path, fname)
            print filepath
            fig.savefig(filepath, bbox_inches='tight')
            plt.close(fig)
Beispiel #30
0
def plot_connectivity_circle(con, node_names, indices=None, n_lines=None,
                             node_angles=None, node_width=None,
                             node_colors=None, facecolor='black',
                             textcolor='white', node_edgecolor='black',
                             linewidth=1.5, colormap='hot', vmin=None,
                             vmax=None, colorbar=True, title=None,
                             colorbar_size=0.2, colorbar_pos=(-0.3, 0.1),
                             fontsize_title=12, fontsize_names=8,
                             fontsize_colorbar=8, padding=6.,
                             fig=None, subplot=111, interactive=True,
                             node_linewidth=2., show=True):
    """Visualize connectivity as a circular graph.

    Parameters
    ----------
    con : array
        Connectivity scores. Can be a square matrix, or a 1D array. If a 1D
        array is provided, "indices" has to be used to define the connection
        indices.
    node_names : list of str
        Node names. The order corresponds to the order in con.
    indices : tuple of arrays | None
        Two arrays with indices of connections for which the connections
        strenghts are defined in con. Only needed if con is a 1D array.
    n_lines : int | None
        If not None, only the n_lines strongest connections (strength=abs(con))
        are drawn.
    node_angles : array, shape=(len(node_names,)) | None
        Array with node positions in degrees. If None, the nodes are equally
        spaced on the circle. See mne.viz.circular_layout.
    node_width : float | None
        Width of each node in degrees. If None, the minimum angle between any
        two nodes is used as the width.
    node_colors : list of tuples | list of str
        List with the color to use for each node. If fewer colors than nodes
        are provided, the colors will be repeated. Any color supported by
        matplotlib can be used, e.g., RGBA tuples, named colors.
    facecolor : str
        Color to use for background. See matplotlib.colors.
    textcolor : str
        Color to use for text. See matplotlib.colors.
    node_edgecolor : str
        Color to use for lines around nodes. See matplotlib.colors.
    linewidth : float
        Line width to use for connections.
    colormap : str
        Colormap to use for coloring the connections.
    vmin : float | None
        Minimum value for colormap. If None, it is determined automatically.
    vmax : float | None
        Maximum value for colormap. If None, it is determined automatically.
    colorbar : bool
        Display a colorbar or not.
    title : str
        The figure title.
    colorbar_size : float
        Size of the colorbar.
    colorbar_pos : 2-tuple
        Position of the colorbar.
    fontsize_title : int
        Font size to use for title.
    fontsize_names : int
        Font size to use for node names.
    fontsize_colorbar : int
        Font size to use for colorbar.
    padding : float
        Space to add around figure to accommodate long labels.
    fig : None | instance of matplotlib.pyplot.Figure
        The figure to use. If None, a new figure with the specified background
        color will be created.
    subplot : int | 3-tuple
        Location of the subplot when creating figures with multiple plots. E.g.
        121 or (1, 2, 1) for 1 row, 2 columns, plot 1. See
        matplotlib.pyplot.subplot.
    interactive : bool
        When enabled, left-click on a node to show only connections to that
        node. Right-click shows all connections.
    node_linewidth : float
        Line with for nodes.
    show : bool
        Show figure if True.

    Returns
    -------
    fig : instance of matplotlib.pyplot.Figure
        The figure handle.
    axes : instance of matplotlib.axes.PolarAxesSubplot
        The subplot handle.

    Notes
    -----
    This code is based on the circle graph example by Nicolas P. Rougier
    http://www.labri.fr/perso/nrougier/coding/.

    By default, :func:`matplotlib.pyplot.savefig` does not take ``facecolor``
    into account when saving, even if set when a figure is generated. This
    can be addressed via, e.g.::

    >>> fig.savefig(fname_fig, facecolor='black') # doctest:+SKIP

    If ``facecolor`` is not set via :func:`matplotlib.pyplot.savefig`, the
    figure labels, title, and legend may be cut off in the output figure.
    """
    import matplotlib.pyplot as plt
    import matplotlib.path as m_path
    import matplotlib.patches as m_patches

    n_nodes = len(node_names)

    if node_angles is not None:
        if len(node_angles) != n_nodes:
            raise ValueError('node_angles has to be the same length '
                             'as node_names')
        # convert it to radians
        node_angles = node_angles * np.pi / 180
    else:
        # uniform layout on unit circle
        node_angles = np.linspace(0, 2 * np.pi, n_nodes, endpoint=False)

    if node_width is None:
        # widths correspond to the minimum angle between two nodes
        dist_mat = node_angles[None, :] - node_angles[:, None]
        dist_mat[np.diag_indices(n_nodes)] = 1e9
        node_width = np.min(np.abs(dist_mat))
    else:
        node_width = node_width * np.pi / 180

    if node_colors is not None:
        if len(node_colors) < n_nodes:
            node_colors = cycle(node_colors)
    else:
        # assign colors using colormap
        try:
            spectral = plt.cm.spectral
        except AttributeError:
            spectral = plt.cm.Spectral
        node_colors = [spectral(i / float(n_nodes))
                       for i in range(n_nodes)]

    # handle 1D and 2D connectivity information
    if con.ndim == 1:
        if indices is None:
            raise ValueError('indices has to be provided if con.ndim == 1')
    elif con.ndim == 2:
        if con.shape[0] != n_nodes or con.shape[1] != n_nodes:
            raise ValueError('con has to be 1D or a square matrix')
        # we use the lower-triangular part
        indices = np.tril_indices(n_nodes, -1)
        con = con[indices]
    else:
        raise ValueError('con has to be 1D or a square matrix')

    # get the colormap
    if isinstance(colormap, string_types):
        colormap = plt.get_cmap(colormap)

    # Make figure background the same colors as axes
    if fig is None:
        fig = plt.figure(figsize=(8, 8), facecolor=facecolor)

    # Use a polar axes
    if not isinstance(subplot, tuple):
        subplot = (subplot,)
    axes = plt.subplot(*subplot, polar=True)
    _set_ax_facecolor(axes, facecolor)

    # No ticks, we'll put our own
    plt.xticks([])
    plt.yticks([])

    # Set y axes limit, add additional space if requested
    plt.ylim(0, 10 + padding)

    # Remove the black axes border which may obscure the labels
    axes.spines['polar'].set_visible(False)

    # Draw lines between connected nodes, only draw the strongest connections
    if n_lines is not None and len(con) > n_lines:
        con_thresh = np.sort(np.abs(con).ravel())[-n_lines]
    else:
        con_thresh = 0.

    # get the connections which we are drawing and sort by connection strength
    # this will allow us to draw the strongest connections first
    con_abs = np.abs(con)
    con_draw_idx = np.where(con_abs >= con_thresh)[0]

    con = con[con_draw_idx]
    con_abs = con_abs[con_draw_idx]
    indices = [ind[con_draw_idx] for ind in indices]

    # now sort them
    sort_idx = np.argsort(con_abs)
    con_abs = con_abs[sort_idx]
    con = con[sort_idx]
    indices = [ind[sort_idx] for ind in indices]

    # Get vmin vmax for color scaling
    if vmin is None:
        vmin = np.min(con[np.abs(con) >= con_thresh])
    if vmax is None:
        vmax = np.max(con)
    vrange = vmax - vmin

    # We want to add some "noise" to the start and end position of the
    # edges: We modulate the noise with the number of connections of the
    # node and the connection strength, such that the strongest connections
    # are closer to the node center
    nodes_n_con = np.zeros((n_nodes), dtype=np.int)
    for i, j in zip(indices[0], indices[1]):
        nodes_n_con[i] += 1
        nodes_n_con[j] += 1

    # initialize random number generator so plot is reproducible
    rng = np.random.mtrand.RandomState(seed=0)

    n_con = len(indices[0])
    noise_max = 0.25 * node_width
    start_noise = rng.uniform(-noise_max, noise_max, n_con)
    end_noise = rng.uniform(-noise_max, noise_max, n_con)

    nodes_n_con_seen = np.zeros_like(nodes_n_con)
    for i, (start, end) in enumerate(zip(indices[0], indices[1])):
        nodes_n_con_seen[start] += 1
        nodes_n_con_seen[end] += 1

        start_noise[i] *= ((nodes_n_con[start] - nodes_n_con_seen[start]) /
                           float(nodes_n_con[start]))
        end_noise[i] *= ((nodes_n_con[end] - nodes_n_con_seen[end]) /
                         float(nodes_n_con[end]))

    # scale connectivity for colormap (vmin<=>0, vmax<=>1)
    con_val_scaled = (con - vmin) / vrange

    # Finally, we draw the connections
    for pos, (i, j) in enumerate(zip(indices[0], indices[1])):
        # Start point
        t0, r0 = node_angles[i], 10

        # End point
        t1, r1 = node_angles[j], 10

        # Some noise in start and end point
        t0 += start_noise[pos]
        t1 += end_noise[pos]

        verts = [(t0, r0), (t0, 5), (t1, 5), (t1, r1)]
        codes = [m_path.Path.MOVETO, m_path.Path.CURVE4, m_path.Path.CURVE4,
                 m_path.Path.LINETO]
        path = m_path.Path(verts, codes)

        color = colormap(con_val_scaled[pos])

        # Actual line
        patch = m_patches.PathPatch(path, fill=False, edgecolor=color,
                                    linewidth=linewidth, alpha=1.)
        axes.add_patch(patch)

    # Draw ring with colored nodes
    height = np.ones(n_nodes) * 1.0
    bars = axes.bar(node_angles, height, width=node_width, bottom=9,
                    edgecolor=node_edgecolor, lw=node_linewidth,
                    facecolor='.9', align='center')

    for bar, color in zip(bars, node_colors):
        bar.set_facecolor(color)

    # Draw node labels
    angles_deg = 180 * node_angles / np.pi
    for name, angle_rad, angle_deg in zip(node_names, node_angles, angles_deg):
        if angle_deg >= 270:
            ha = 'left'
        else:
            # Flip the label, so text is always upright
            angle_deg += 180
            ha = 'right'

        axes.text(angle_rad, 10.4, name, size=fontsize_names,
                  rotation=angle_deg, rotation_mode='anchor',
                  horizontalalignment=ha, verticalalignment='center',
                  color=textcolor)

    if title is not None:
        plt.title(title, color=textcolor, fontsize=fontsize_title,
                  axes=axes)

    if colorbar:
        sm = plt.cm.ScalarMappable(cmap=colormap,
                                   norm=plt.Normalize(vmin, vmax))
        sm.set_array(np.linspace(vmin, vmax))
        cb = plt.colorbar(sm, ax=axes, use_gridspec=False,
                          shrink=colorbar_size,
                          anchor=colorbar_pos)
        cb_yticks = plt.getp(cb.ax.axes, 'yticklabels')
        cb.ax.tick_params(labelsize=fontsize_colorbar)
        plt.setp(cb_yticks, color=textcolor)

    # Add callback for interaction
    if interactive:
        callback = partial(_plot_connectivity_circle_onpick, fig=fig,
                           axes=axes, indices=indices, n_nodes=n_nodes,
                           node_angles=node_angles)

        fig.canvas.mpl_connect('button_press_event', callback)

    plt_show(show)
    return fig, axes