コード例 #1
1
def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

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

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

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

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

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

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

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

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

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

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max+10)
    fig.save('metrics', fileformat='pdf')
コード例 #2
0
ファイル: geometry.py プロジェクト: mcapllonch/SenseBackSim
	def draw(self, ax, colour='k', alpha=1., linestyle='-', linewidth=1., 
		markers=None, facecolor='none', dashes=(1, 1), zorder=0):
		"""
		Draw the polygon on ax
		"""
		# Add the last point
		ptstoplot = self.verts.tolist()
		ptstoplot.append(ptstoplot[0])
		ptstoplot = np.array(ptstoplot)
		if facecolor == 'none':
			try:
				if linestyle == '--':
					ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha,
						ls=linestyle, dashes=dashes, lw=linewidth, marker=markers, zorder=zorder)
				else:
					ax.plot(ptstoplot[:, 0], ptstoplot[:, 1], c=colour, alpha=alpha,
						ls=linestyle, lw=linewidth, marker=markers, zorder=zorder)
			except IndexError:
				pass
		else:
			patches = []
			filled_pol = mp.Polygon(self.verts)
			patches.append(filled_pol)
			collection = PatchCollection(patches, facecolors=facecolor)
			ax.add_collection(collection)
			collection.set_alpha(alpha)
			collection.set_edgecolor(colour)
			collection.set_linewidth(linewidth)
			collection.set_linestyle(linestyle)
コード例 #3
0
def data2fig(data, X, options, legend_title, xlabel, ylabel=r'Reachability~$\reachability$'):
    if options['grayscale']:
        colors = options['graycm'](pylab.linspace(0, 1, len(data.keys())))
    else:
        colors = options['color'](pylab.linspace(0, 1, len(data.keys())))
    fig = MyFig(options, figsize=(10, 8), xlabel=r'Sources~$\sources$', ylabel=ylabel, grid=False, aspect='auto', legend=True)
    for j, nhdp_ht in enumerate(sorted(data.keys())):
        d = data[nhdp_ht]
        try:
            mean_y = [scipy.mean(d[n]) for n in X]
        except KeyError:
            logging.warning('key \"%s\" not found, continuing...', nhdp_ht)
            continue
        confs_y = [confidence(d[n])[2] for n in X]
        poly = [conf2poly(X, list(numpy.array(mean_y)+numpy.array(confs_y)), list(numpy.array(mean_y)-numpy.array(confs_y)), color=colors[j])]
        patch_collection = PatchCollection(poly, match_original=True)
        patch_collection.set_alpha(0.3)
        patch_collection.set_linestyle('dashed')
        fig.ax.add_collection(patch_collection)
        fig.ax.plot(X, mean_y, label='$%d$' % nhdp_ht, color=colors[j])
    fig.ax.set_xticks(X)
    fig.ax.set_xticklabels(['$%s$' % i for i in X])
    fig.ax.set_ylim(0,1)
    fig.legend_title = legend_title
    return fig
コード例 #4
0
    def add_circles(self, ax, centers, radis):
        circles = []
        for c, r in zip(centers, radis):
            circles.append(patches.Circle(tuple(c), r))

        patch_collection = PatchCollection(circles)
        patch_collection.set_facecolor("none")
        patch_collection.set_edgecolor("blue")
        patch_collection.set_linewidth(1.5)
        patch_collection.set_linestyle("dashed")
        ax.add_collection(patch_collection)
        print "added %d circles" % len(circles)
コード例 #5
0
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Probability $p_s$', ylabel=r'Reachability~$\reachability$', aspect='auto')
    fig_vs = MyFig(options, figsize=(10, 8), legend=True, grid=False, xlabel=r'Fraction of Forwarded Packets~$\forwarded$', ylabel=r'Reachability~$\reachability$', aspect='auto')

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

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

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

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

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

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0,1)
    fig_vs.ax.set_ylim(0,1)
    fig_vs.save('vs_pb')
コード例 #6
0
             count = params[1]
             vecs = params[2:]
             x = vecs[::2]
             y = np.array(vecs[1::2])
             polygon = Polygon(np.array([x, y]).transpose(),
                               True,
                               color='gray')
             patches_polygon.append(polygon)
     pcc = PatchCollection(patches_circle, match_original=False)
     pcp = PatchCollection(patches_polygon, match_original=False)
     if args.collision_status:
         pcc.set_color('#85878b')
         pcp.set_color('#85878b')
         pcc.set_alpha(0.3)
         pcp.set_alpha(0.3)
         pcc.set_linestyle('dashed')
         pcp.set_linestyle('dashed')
         pcc.set_edgecolor('#73cdc9')
         pcp.set_edgecolor('#73cdc9')
         pcc.set_linewidth(0.4)
         pcp.set_linewidth(0.4)
         pcc.set_joinstyle('round')
         pcp.set_joinstyle('round')
     else:
         pcc.set_color('gray')
         pcp.set_color('gray')
     ax.add_collection(pcc)
     ax.add_collection(pcp)
 if args.safety_certificate:
     xyrs = []
     for line in open(args.safety_certificate, 'r').readlines():
コード例 #7
0
def plot_bond_site(options):
    options['prefix'] = 'bond_site'
    epsilon = numpy.finfo(numpy.float).eps

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            fig_fw_pb.ax.set_xlim(0,1)
            fig_fw_pb.ax.set_ylim(0,1)
            fig_fw_pb.legend_title = '$p_b$'
            fig_fw_pb.save('fw_pb')
コード例 #8
0
def show_annotated(imgid, anns_by_loss, gt, img_output_path):
    #import pdb; pdb.set_trace(); 1
    common_categories = set()
    for loss, anns in anns_by_loss.iteritems():
        #c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
        gtcolor = [1.0, .25, .5]
        #import pdb; pdb.set_trace(); 1
        categories = [a['category_id'] for a in anns['dt'] if a['score'] > 0.8]
        common_categories.update(categories)

    common_categories = list(common_categories)
    if len(common_categories) < 1:
        return

    for loss, anns in anns_by_loss.iteritems():
        ax = plt.gca()
        ax.set_autoscale_on(False)
        dtcolor = COLORS[loss]
        for category_id in common_categories:
            gt_polygons = []
            dt_polygons = []
            color = []
            gta = [a for a in anns['gt'] if a['category_id'] == category_id]
            if len(gta) < 1:
                continue
            gtbbox = gta[0]['bbox']
            #x,y,w,h
            gtpoly = Rectangle((gtbbox[0], gtbbox[1]), gtbbox[2], gtbbox[3])
            gt_polygons.append(gtpoly)
            color.append(COLORS['white'])

            dt = [a for a in anns['dt'] if a['category_id'] == category_id]
            if len(dt) < 1:
                continue
            dt = sorted(dt, key=lambda a: a['score'])
            dtbbox = dt[0]['bbox']
            #x,y,w,h
            dtpoly = Rectangle((dtbbox[0], dtbbox[1]), dtbbox[2], dtbbox[3])
            dt_polygons.append(dtpoly)
            color.append(COLORS['white'])

            # top, left, bottom, right
            gtbb = gtbbox[1], gtbbox[
                0], gtbbox[1] + gtbbox[3], gtbbox[0] + gtbbox[2]
            dtbb = dtbbox[1], dtbbox[
                0], dtbbox[1] + dtbbox[3], dtbbox[0] + dtbbox[2]

            iou = iou_utils.iou(gtbb, dtbb)
            giou = iou_utils.giou(gtbb, dtbb)

            txt = ax.text(0.5,
                          0.1,
                          "IoU: %.3f, GIoU: %.3f" % (iou, giou),
                          horizontalalignment='center',
                          verticalalignment='center',
                          transform=ax.transAxes,
                          color=COLORS['white'],
                          family='serif',
                          size=26)
            txt.set_path_effects(
                [PathEffects.withStroke(linewidth=4, foreground='black')])

            #p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
            #ax.add_collection(p)
            # gt
            p = PatchCollection(gt_polygons,
                                facecolor='none',
                                edgecolors=color,
                                linewidths=4)
            p.set_linestyle('solid')
            ax.add_collection(p)

            # dt
            p = PatchCollection(dt_polygons,
                                facecolor='none',
                                edgecolors=color,
                                linewidths=4)
            p.set_linestyle('dashed')
            ax.add_collection(p)

            #1 category only
            break

        #import pdb; pdb.set_trace(); 1
        imgfname = gt.imgs[imgid]['file_name']
        _, split, _ = imgfname.split('_')
        src_img = "{}/coco/coco/images/{}/{}".format(DATASETS, split, imgfname)
        img = mpimg.imread(src_img)
        #ax.add_image(img)
        #ax.figure.figimage(img)
        ax.autoscale()
        ax.imshow(img)
        ax.axes.get_xaxis().set_visible(False)
        ax.axes.get_yaxis().set_visible(False)
        ax.set_frame_on(False)
        #import pdb; pdb.set_trace(); 1
        imgpath = "{}/{}_category-{}-{}.jpg".format(img_output_path, imgid,
                                                    common_categories[0], loss)
        print("imgpath: {}".format(imgpath))
        ax.figure.savefig(imgpath, dpi=400, bbox_inches='tight', pad_inches=0)
        plt.clf()
コード例 #9
0
def draw(options):
    files = [f for f in os.listdir(options['outdir']) if f.endswith('.data')]

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

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

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

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

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

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

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

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

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

    fig.ax.set_xlim(0, options['duration'])
    y_max = max(max(degrees), max(diameters), max(velocities))
    fig.ax.set_ylim(0, y_max + 10)
    fig.save('metrics', fileformat='pdf')
コード例 #10
0
def show_annotated(imgid,
                   anns_by_loss,
                   gt,
                   img_output_path,
                   txt_output_path,
                   network='yolo'):
    global colormod
    #import pdb; pdb.set_trace(); 1
    common_categories = set()
    for loss, anns in anns_by_loss.iteritems():
        #c = (np.random.random((1, 3))*0.6+0.4).tolist()[0]
        gtcolor = [1.0, .25, .5]
        #import pdb; pdb.set_trace(); 1
        categories = [a['category_id'] for a in anns['dt']]
        common_categories.update(categories)

    common_categories = list(common_categories)
    if len(common_categories) < 1:
        return

    avggious = dict(mse=False, iou=False, giou=False)
    avgious = dict(mse=False, iou=False, giou=False)
    biggestboxscores = {}
    for loss, anns in anns_by_loss.iteritems():
        avggious[loss] = []
        avgious[loss] = []
        ax = plt.gca()
        ax.set_autoscale_on(False)
        gcolor = []
        dcolor = []
        dtcolor = COLORS[loss]
        bbox_txt = []

        #for cidx, category_id in enumerate(common_categories):
        gt_polygons = []
        dt_polygons = []
        #gta = [a for a in anns['gt'] if a['category_id'] == category_id]
        gta = anns['gt']
        if len(gta) < 1:
            continue
        gtbboxes = [b['bbox'] for b in gta]
        #dt = [a for a in anns['dt'] if a['category_id'] == category_id]
        dt = anns['dt']
        dtbboxes = [b['bbox'] for b in dt]
        # gious shape(dt, gt)
        gious = np.zeros((len(gtbboxes), len(dtbboxes)))
        for i, g in enumerate(gtbboxes):
            for j, d in enumerate(dtbboxes):
                # top, left, bottom, right
                gtbb = g[1], g[0], g[1] + g[3], g[0] + g[2]
                dtbb = d[1], d[0], d[1] + d[3], d[0] + d[2]
                gious[i, j] = iou_utils.giou(gtbb, dtbb)

        #sortby = np.diagonal(gious)
        #gtbboxes_s = [x for _, x in sorted(zip(sortby,gtbboxes), key=lambda pair: pair[0])]
        #dtbboxes_s = [x for _, x in sorted(zip(sortby,dtbboxes), key=lambda pair: pair[0])]

        for i, gtbbox in enumerate(gtbboxes):
            gann = anns['gt'][i]
            category_id = gann['category_id']
            print("category_id: {}".format(category_id))
            # find gt
            dann = anns['dt'][np.argmax(gious[i])]
            dtbbox = dtbboxes[np.argmax(gious[i])]
            #x,y,w,h
            #colormod += 1
            c = color_names[category_id % len(color_names)]

            det_c = c
            # white detection bb if score < threshold
            #det_c = c if dann['score'] >= SCORE_THRESHOLD else 'white'

            gcolor.append(c)
            dcolor.append(det_c)
            gtbb = gtbbox[1], gtbbox[
                0], gtbbox[1] + gtbbox[3], gtbbox[0] + gtbbox[2]
            gtbbsize = (gtbb[2] - gtbb[0]) * (gtbb[3] - gtbb[1])
            dtbb = dtbbox[1], dtbbox[
                0], dtbbox[1] + dtbbox[3], dtbbox[0] + dtbbox[2]
            giou = iou_utils.giou(gtbb, dtbb)
            iou = iou_utils.iou(gtbb, dtbb)
            avggious[loss].append(giou)
            avgious[loss].append(iou)
            #if gious.shape[0] > 1:
            #    import pdb; pdb.set_trace(); 1
            bbox_txt.append(
                "BB: {}, category_id: {}, color: {}, giou: {}, iou: {}".format(
                    i, category_id, c, giou, iou))
            #iou = iou_utils.iou(gtbb, dtbb)

            linewidth = 5
            category_name = [
                cat['name'] for cat in gt.dataset['categories']
                if cat['id'] == category_id
            ][0]
            score = dann['score']
            if loss not in biggestboxscores:
                biggestboxscores[loss] = None
            if biggestboxscores[loss] is None or biggestboxscores[loss][
                    'box'] < gtbbsize:
                biggestboxscores[loss] = {
                    'box': gtbbsize,
                    'score': score,
                    'category': category_name,
                    'metric': giou
                }
            print("TEXT COORDINATES: ({}, {}), class: {}, score: {}".format(
                gtbbox[0], dtbbox[1], category_name, score))
            #ax.text(dtbbox[0], dtbbox[1], category_name, horizontalalignment='left', verticalalignment='bottom', color=c, family='serif', size=10)
            #if dann['score'] <= SCORE_THRESHOLD:
            #    ax.text(dtbbox[2], dtbbox[1], dann['score'], horizontalalignment='left', verticalalignment='bottom', color='white', family='serif', size=10)

            gtpoly = Rectangle((gtbbox[0], gtbbox[1]), gtbbox[2], gtbbox[3])
            gt_polygons.append(gtpoly)
            p = PatchCollection(gt_polygons,
                                facecolor='none',
                                edgecolors='white',
                                linewidths=linewidth,
                                alpha=0.5,
                                zorder=i)
            p.set_linestyle('solid')
            ax.add_collection(p)

            dtpoly = Rectangle((dtbbox[0], dtbbox[1]), dtbbox[2], dtbbox[3])
            dt_polygons.append(dtpoly)
            p = PatchCollection(dt_polygons,
                                facecolor='none',
                                edgecolors=dcolor,
                                linewidths=linewidth,
                                alpha=score,
                                zorder=len(gtbboxes) + i)
            p.set_linestyle('dashed')
            ax.add_collection(p)
            #p = PatchCollection(dt_polygons, facecolor='none', edgecolors=dcolor, linewidths=linewidth, alpha=score)
            #p.set_linestyle('dashed')
            #ax.add_collection(p)

            #txt = ax.text(0.5, 0.1, "IoU: %.3f, GIoU: %.3f" % (iou, giou), horizontalalignment='center', verticalalignment='center', transform=ax.transAxes, color=COLORS['white'], family='serif', size=26)
            #txt.set_path_effects([PathEffects.withStroke(linewidth=4, foreground='black')])

            #p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
            #ax.add_collection(p)
            # gt

            # dt

            #1 category only
            #if cidx >= PLOT_MAX_CATEGORIES:
            #    break

        if avggious['giou'] != False:
            #import pdb; pdb.set_trace(); 1
            imgfname = gt.imgs[imgid]['file_name']
            _, split, _ = imgfname.split('_')
            src_img = "{}/coco/coco/images/{}/{}".format(
                DATASETS, split, imgfname)
            img = mpimg.imread(src_img)
            #ax.add_image(img)
            #ax.figure.figimage(img)
            ax.autoscale()
            ax.imshow(img)
            ax.axes.get_xaxis().set_visible(False)
            ax.axes.get_yaxis().set_visible(False)
            ax.set_frame_on(False)
            # range 0 <-> 2
            mmse = 1 + np.mean(avggious['mse'])
            mgiou = 1 + np.mean(avggious['giou'])
            miou = 1 + np.mean(avggious['iou'])
            scorestr = "%s%s%s" % (str(int(
                mmse * 100)).zfill(3), str(int(
                    miou * 100)).zfill(3), str(int(mgiou * 100)).zfill(3))
            basename = "{}-id_{}-mse_{}-iou_{}-giou_{}-category-{}-{}-{}".format(
                scorestr, imgid, mmse, miou, mgiou, common_categories[0],
                network, loss)
            imgpath = "{}/{}.jpg".format(img_output_path, basename)
            txtpath = "{}/{}.txt".format(txt_output_path, basename)
            bbox_txt.insert(
                0,
                "AVG: giou metric: (giou loss: {}, iou loss: {}, mse loss: {}), iou metric: (giou loss: {}, iou loss: {}, mse loss: {})"
                .format(np.mean(avggious['giou']), np.mean(avggious['iou']),
                        np.mean(avggious['mse']), np.mean(avgious['giou']),
                        np.mean(avgious['iou']), np.mean(avgious['mse'])))
            with open(txtpath, 'wb') as f:
                f.write('\n'.join(bbox_txt))
            print("imgpath: {}".format(imgpath))
            ax.figure.savefig(imgpath,
                              dpi=100,
                              bbox_inches='tight',
                              pad_inches=0)
            plt.clf()

    if 'giou' in biggestboxscores and 'iou' in biggestboxscores and 'mse' in biggestboxscores:
        with open(os.path.join(txt_output_path, "scores.csv"), 'ab') as f:
            f.write("{},{},{},{},{},{},{},{},{},{}\n".format(
                imgid, biggestboxscores['giou']['score'],
                biggestboxscores['iou']['score'],
                biggestboxscores['mse']['score'],
                biggestboxscores['giou']['category'],
                biggestboxscores['iou']['category'],
                biggestboxscores['mse']['category'],
                biggestboxscores['giou']['metric'],
                biggestboxscores['iou']['metric'],
                biggestboxscores['mse']['metric']))
コード例 #11
0
def plot_site(options):
    options['prefix'] = 'site'
    fig = MyFig(options,
                figsize=(10, 8),
                legend=True,
                grid=False,
                xlabel=r'Probability $p_s$',
                ylabel=r'Reachability~$\reachability$',
                aspect='auto')
    fig_vs = MyFig(options,
                   figsize=(10, 8),
                   legend=True,
                   grid=False,
                   xlabel=r'Fraction of Forwarded Packets~$\forwarded$',
                   ylabel=r'Reachability~$\reachability$',
                   aspect='auto')

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

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

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

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

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

    fig.ax.set_ylim(0, options['limit'])
    fig.legend_title = 'Graph'
    fig.save('graphs')
    fig_vs.legend_title = 'Graph'
    fig_vs.ax.set_xlim(0, 1)
    fig_vs.ax.set_ylim(0, 1)
    fig_vs.save('vs_pb')
コード例 #12
0
def plot_bond_site(options):
    options['prefix'] = 'bond_site'
    epsilon = numpy.finfo(numpy.float).eps

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            fig_fw_pb.ax.set_xlim(0, 1)
            fig_fw_pb.ax.set_ylim(0, 1)
            fig_fw_pb.legend_title = '$p_b$'
            fig_fw_pb.save('fw_pb')
コード例 #13
0
ファイル: _mesh.py プロジェクト: dlontine/pyfem2AxiProj
    def Plot2D(self, xy=None, elecon=None, u=None, color=None, ax=None, show=0,
               weight=None, colorby=None, linestyle='-', label=None, xlim=None,
               ylim=None, filename=None, **kwds):
        assert self.dimensions == 2
        from matplotlib.patches import Polygon
        import matplotlib.lines as mlines
        from matplotlib.collections import PatchCollection
        from matplotlib.cm import coolwarm, Spectral
        import matplotlib.pyplot as plt

        if xy is None:
            xy = array(self.coord)
        if elecon is None:
            elecon = []
            for blk in self.eleblx:
                elecon.extend(blk.elecon.tolist())
            elecon = asarray(elecon)
        if u is not None:
            xy += u.reshape(xy.shape)

        patches = []
        for points in xy[elecon[:]]:
            quad = Polygon(points, True)
            patches.append(quad)

        if ax is None:
            fig, ax = plt.subplots()

        #colors = 100 * random.rand(len(patches))
        p = PatchCollection(patches, linewidth=weight, **kwds)
        if colorby is not None:
            colorby = asarray(colorby).flatten()
            if len(colorby) == len(xy):
                # average value in element
                colorby = array([average(colorby[points]) for points in elecon])
            p.set_cmap(Spectral)  #coolwarm)
            p.set_array(colorby)
            p.set_clim(vmin=colorby.min(), vmax=colorby.max())
            fig.colorbar(p)
        else:
            p.set_edgecolor(color)
            p.set_facecolor('None')
            p.set_linewidth(weight)
            p.set_linestyle(linestyle)

        if label:
            ax.plot([], [], color=color, linestyle=linestyle, label=label)

        ax.add_collection(p)

        if not ylim:
            ymin, ymax = amin(xy[:,1]), amax(xy[:,1])
            dy = max(abs(ymin*.05), abs(ymax*.05))
            ax.set_ylim([ymin-dy, ymax+dy])
        else:
            ax.set_ylim(ylim)

        if not xlim:
            xmin, xmax = amin(xy[:,0]), amax(xy[:,0])
            dx = max(abs(xmin*.05), abs(xmax*.05))
            ax.set_xlim([xmin-dx, xmax+dx])
        else:
            ax.set_xlim(xlim)
        ax.set_aspect('equal')

        if show:
            plt.show()

        if filename is not None:
            plt.legend()
            plt.savefig(filename, transparent=True,
                        bbox_inches="tight", pad_inches=0)

        return ax