PLots C/O surface number fraction
15386
def set_plot_CO_mass(self,fig=3123,xaxis='mass',linestyle=['-'],marker=['o'],color=['r'],age_years=True,sparsity=500,markersparsity=200,withoutZlabel=False,t0_model=[]):
		
		'''
			
		'''

		if len(t0_model)==0:
			t0_model = len(self.runs_H5_surf)*[0]

		plt.figure(fig)
                for i in range(len(self.runs_H5_surf)):
                        sefiles=se(self.runs_H5_surf[i])
			cycles=range(int(sefiles.se.cycles[0]),int(sefiles.se.cycles[-1]),sparsity)
			mini=sefiles.get("mini")
			zini=sefiles.get("zini")
			label=str(mini)+'$M_{\odot}$, Z='+str(zini)
			if xaxis=='cycles':
				x=cycles
			if xaxis=='age':
				x=sefiles.get(cycles,'age')
                        	if age_years==True:
                                	x=np.array(x)*sefiles.get('age_unit')/(365*24*3600)
				x = x - x[t0_model[i]]
			if xaxis=='mass':
				x=sefiles.get(cycles,'mass')
			x=x[t0_model[i]:]
			c12=sefiles.get(cycles,'C-12')[t0_model[i]:]
			o16=sefiles.get(cycles,'O-16')[t0_model[i]:]
			if withoutZlabel==True:
				plt.plot(x,4./3.*np.array(c12)/np.array(o16),label=label.split(',')[0],marker=marker[i],linestyle=linestyle[i],markevery=markersparsity,color=color[i])

			else:
				plt.plot(x,4./3.*np.array(c12)/np.array(o16),label=label,marker=marker[i],linestyle=linestyle[i],markevery=markersparsity,color=color[i])
			if xaxis=='mass':
				plt.xlim(7,0.5)
				#plt.gca().invert_xaxis()	
	                        plt.xlabel('$M/M_{\odot}$',fontsize=18)
	
                        plt.ylabel('C/O Ratio', fontsize=18)
			plt.legend(loc=1)
720065
def plot(self, axis, ith_plot, total_plots, limits):
        
        print(self.plot_type_str.upper() + " plot")
        print("%5s %9s  %s" % ("id", " #points", "group"))

        for idx, group in enumerate(self.groups):
            print("%5s %9s  %s" % (idx + 1, len(self.groups[group]), group))

        print('')

        datasets = []
        colors = []
        minx = np.inf
        maxx = -np.inf

        for idx, group in enumerate(self.groups):
            x = date2num([logevent.datetime
                          for logevent in self.groups[group]])
            minx = min(minx, min(x))
            maxx = max(maxx, max(x))
            datasets.append(x)
            color, marker = self.color_map(group)
            colors.append(color)

        if total_plots > 1:
            # if more than one plot, move histogram to twin axis on the right
            twin_axis = axis.twinx()
            twin_axis.set_ylabel(self.ylabel)
            axis.set_zorder(twin_axis.get_zorder() + 1)  # put ax ahead of ax2
            axis.patch.set_visible(False)  # hide the 'canvas'
            axis = twin_axis

        n_bins = max(1, int((maxx - minx) * 24. * 60. * 60. / self.bucketsize))
        if n_bins > 1000:
            # warning for too many buckets
            print("warning: %i buckets, will take a while to render. "
                  "consider increasing --bucketsize." % n_bins)

        n, bins, artists = axis.hist(datasets, bins=n_bins, align='mid',
                                     log=self.logscale,
                                     histtype="barstacked"
                                     if self.barstacked else "bar",
                                     color=colors, edgecolor="none",
                                     linewidth=0, alpha=0.8, picker=True,
                                     label=map(str, self.groups.keys()))

        # scale current y-axis to match min and max values
        axis.set_ylim(np.min(n), np.max(n))

        # add meta-data for picking
        if len(self.groups) > 1:
            for g, group in enumerate(self.groups.keys()):
                for i in range(len(artists[g])):
                    artists[g][i]._mt_plot_type = self
                    artists[g][i]._mt_group = group
                    artists[g][i]._mt_n = n[g][i]
                    if self.barstacked:
                        artists[g][i]._mt_n -= (n[g - 1][i] if g > 0 else 0)

                    artists[g][i]._mt_bin = bins[i]
        else:
            for i in range(len(artists)):
                artists[i]._mt_plot_type = self
                artists[i]._mt_group = group
                artists[i]._mt_n = n[i]
                artists[i]._mt_bin = bins[i]

        return artists
435868
def plot_init(fignum, w, h):
    
    global fig_x_pos, fig_y_pos, plt_num
    dpi = 80
    if isServer:
        dpi = 240
    # plt.ion()
    plt_num += 1
    fig = plt.figure(num=fignum, figsize=(w, h), dpi=dpi)
    if (not isServer) and (not set_env.IS_NOTEBOOK):
        plt.get_current_fig_manager().show()
        # plt.get_current_fig_manager().window.wm_geometry('+%d+%d' %
        # (fig_x_pos,fig_y_pos)) # this only works with matplotlib.use('TKAgg')
        fig_x_pos = fig_x_pos + dpi * (w) + 25
        if plt_num == 3:
            plt_num = 0
            fig_x_pos = 25
            fig_y_pos = fig_y_pos + dpi * (h) + 25
        plt.figtext(.02, .01, version_num)
# plt.connect('button_press_event',click)
#
    # plt.ioff()
    return fig
1104019
def plot(x, y, z, color=default_color, **kwargs):
    
    fig = gcf()
    _grow_limits(x, y, z)
    defaults = dict(
        visible_lines=True, color_selected=None, size_selected=1, size=1, connected=True, visible_markers=False
    )
    kwargs = dict(defaults, **kwargs)
    s = ipv.Scatter(x=x, y=y, z=z, color=color, **kwargs)
    s.material.visible = False
    fig.scatters = fig.scatters + [s]
    return s
197492
def plot(self, numPoints=100):
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')

    # generate sphere
    phi, theta = np.meshgrid(
      np.linspace(0, pi, numPoints),
      np.linspace(0, 2 * pi, numPoints)
    )
    x = self.radius * np.sin(phi) * np.cos(theta)
    y = self.radius * np.sin(phi) * np.sin(theta)
    z = self.radius * np.cos(phi)

    # plot
    ax.plot_surface(x, y, z, alpha=0.2, rstride=20, cstride=10)
    ax.set_xlabel("X")
    ax.set_ylabel("Y")
    ax.set_zlabel("Z")

    plt.title("{}".format(self))
    return fig, ax
1198562
def plot_di_sym(fignum, DIblock, sym):
    global globals
    
    X_down, X_up, Y_down, Y_up = [], [], [], []  # initialize some variables
    plt.figure(num=fignum)
#
#   plot the data - separate upper and lower hemispheres
#
    for rec in DIblock:
        Up, Down = 0, 0
        XY = pmag.dimap(rec[0], rec[1])
        if rec[1] >= 0:
            X_down.append(XY[0])
            Y_down.append(XY[1])
        else:
            X_up.append(XY[0])
            Y_up.append(XY[1])
#
    if 'size' not in list(sym.keys()):
        size = 50
    else:
        size = sym['size']
    if 'edgecolor' not in list(sym.keys()):
        sym['edgecolor'] = 'k'
    if len(X_down) > 0:
        plt.scatter(X_down, Y_down, marker=sym['lower'][0],
                    c=sym['lower'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_down
            globals.DIlisty = Y_down
    if len(X_up) > 0:
        plt.scatter(X_up, Y_up, marker=sym['upper'][0],
                    c=sym['upper'][1], s=size, edgecolor=sym['edgecolor'])
        if globals != 0:
            globals.DIlist = X_up
            globals.DIlisty = Y_up
1232892
def twoSurfplots(self):
    
    # Could more elegantly just call surfplot twice
    # And also could include xyzinterp as an option inside surfplot.
    # Noted here in case anyone wants to take that on in the future...

    plt.subplot(211)
    plt.title('Load thickness, mantle equivalent [m]',fontsize=16)
    if self.latlon:
      plt.imshow(self.qs/(self.rho_m*self.g), extent=(0, self.dx*self.qs.shape[0], self.dy*self.qs.shape[1], 0))
      plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold')
      plt.ylabel('latitude [deg N]', fontsize=12, fontweight='bold')
    else:
      plt.imshow(self.qs/(self.rho_m*self.g), extent=(0, self.dx/1000.*self.qs.shape[0], self.dy/1000.*self.qs.shape[1], 0))
      plt.xlabel('x [km]', fontsize=12, fontweight='bold')
      plt.ylabel('y [km]', fontsize=12, fontweight='bold')
    plt.colorbar()

    plt.subplot(212)
    plt.title('Deflection [m]')
    if self.latlon:
      plt.imshow(self.w, extent=(0, self.dx*self.w.shape[0], self.dy*self.w.shape[1], 0))
      plt.xlabel('longitude [deg E]', fontsize=12, fontweight='bold')
      plt.ylabel('latitude [deg N]', fontsize=12, fontweight='bold')
    else:
      plt.imshow(self.w, extent=(0, self.dx/1000.*self.w.shape[0], self.dy/1000.*self.w.shape[1], 0))
      plt.xlabel('x [km]', fontsize=12, fontweight='bold')
      plt.ylabel('y [km]', fontsize=12, fontweight='bold')
    plt.colorbar()
1161930
def surface(func, umin=0, umax=2 * np.pi, ucount=64, urepeat=1.0,
            vmin=0, vmax=2 * np.pi, vcount=64, vrepeat=1.0):
    

    vtype = [('position', np.float32, 3),
             ('texcoord', np.float32, 2),
             ('normal',   np.float32, 3)]
    itype = np.uint32

    # umin, umax, ucount = 0, 2*np.pi, 64
    # vmin, vmax, vcount = 0, 2*np.pi, 64

    vcount += 1
    ucount += 1
    n = vcount * ucount

    Un = np.repeat(np.linspace(0, 1, ucount, endpoint=True), vcount)
    Vn = np.tile(np.linspace(0, 1, vcount, endpoint=True), ucount)
    U = umin + Un * (umax - umin)
    V = vmin + Vn * (vmax - vmin)

    vertices = np.zeros(n, dtype=vtype)
    for i, (u, v) in enumerate(zip(U, V)):
        vertices["position"][i] = func(u, v)

    vertices["texcoord"][:, 0] = Un * urepeat
    vertices["texcoord"][:, 1] = Vn * vrepeat

    indices = []
    for i in range(ucount - 1):
        for j in range(vcount - 1):
            indices.append(i * (vcount) + j)
            indices.append(i * (vcount) + j + 1)
            indices.append(i * (vcount) + j + vcount + 1)
            indices.append(i * (vcount) + j + vcount)
            indices.append(i * (vcount) + j + vcount + 1)
            indices.append(i * (vcount) + j)
    indices = np.array(indices, dtype=itype)
    vertices["normal"] = normals(vertices["position"],
                                 indices.reshape(len(indices) / 3, 3))

    return vertices, indices
1196579
def plot_neff(self, ax, xt_labelsize, titlesize, markersize):
        """"""
        for plotter in self.plotters.values():
            for y, ess, color in plotter.ess():
                if ess is not None:
                    ax.plot(
                        ess,
                        y,
                        "o",
                        color=color,
                        clip_on=False,
                        markersize=markersize,
                        markeredgecolor="k",
                    )
        ax.set_xlim(left=0)
        ax.set_title("ess", fontsize=titlesize, wrap=True)
        ax.tick_params(labelsize=xt_labelsize)
        return ax
743166
def plot_result(x_p, y_p, y_p_e, smoothed_data, smoothed_data_diff, filename=None):
    ''' 
    '''
    logging.info('Plot results')
    plt.close()

    p1 = plt.errorbar(x_p * analysis_configuration['vcal_calibration'], y_p, yerr=y_p_e, fmt='o')  # plot data with error bars
    p2, = plt.plot(x_p * analysis_configuration['vcal_calibration'], smoothed_data, '-r')  # plot smoothed data
    factor = np.amax(y_p) / np.amin(smoothed_data_diff) * 1.1
    p3, = plt.plot(x_p * analysis_configuration['vcal_calibration'], factor * smoothed_data_diff, '-', lw=2)  # plot differentiated data
    mpv_index = np.argmax(-analysis_utils.smooth_differentiation(x_p, y_p, weigths=1 / y_p_e, order=3, smoothness=analysis_configuration['smoothness'], derivation=1))
    p4, = plt.plot([x_p[mpv_index] * analysis_configuration['vcal_calibration'], x_p[mpv_index] * analysis_configuration['vcal_calibration']], [0, factor * smoothed_data_diff[mpv_index]], 'k-', lw=2)
    text = 'MPV ' + str(int(x_p[mpv_index] * analysis_configuration['vcal_calibration'])) + ' e'
    plt.text(1.01 * x_p[mpv_index] * analysis_configuration['vcal_calibration'], -10. * smoothed_data_diff[mpv_index], text, ha='left')
    plt.legend([p1, p2, p3, p4], ['data', 'smoothed spline', 'spline differentiation', text], prop={'size': 12}, loc=0)
    plt.title('\'Single hit cluster\'-occupancy for different pixel thresholds')
    plt.xlabel('Pixel threshold [e]')
    plt.ylabel('Single hit cluster occupancy [a.u.]')
    plt.ylim(0, np.amax(y_p) * 1.15)
    if filename is None:
        plt.show()
    else:
        filename.savefig(plt.gcf())
    return smoothed_data_diff
556934
def plot_temp_diagrams(config, results, temp_dir):
    """"""
    display_name = {
        'time': 'Compilation time (s)',
        'memory': 'Compiler memory usage (MB)',
    }

    files = config['files']
    img_files = []

    if any('slt' in result for result in results) and 'bmp' in files.values()[0]:
        config['modes']['slt'] = 'Using BOOST_METAPARSE_STRING with string literal templates'
        for f in files.values():
            f['slt'] = f['bmp'].replace('bmp', 'slt')

    for measured in ['time', 'memory']:
        mpts = sorted(int(k) for k in files.keys())
        img_files.append(os.path.join(temp_dir, '_{0}.png'.format(measured)))
        plot(
            {
                m: [(x, results[files[str(x)][m]][measured]) for x in mpts]
                for m in config['modes'].keys()
            },
            config['modes'],
            display_name[measured],
            (config['x_axis_label'], display_name[measured]),
            img_files[-1]
        )
    return img_files
1373785
def _plot(self):
        """"""
        r_max = min(
            self.view.x(1) - self.view.x(0),
            (self.view.y(0) or 0) - self.view.y(1)
        ) / (2 * 1.05)
        for serie in self.series:
            self.dot(serie, r_max)
895655
def plotSegmentationResults(flags_ind, flags_ind_gt, class_names, mt_step, ONLY_EVALUATE=False):
    '''
    
    '''    
    flags = [class_names[int(f)] for f in flags_ind]
    (segs, classes) = flags2segs(flags, mt_step)    
    min_len = min(flags_ind.shape[0], flags_ind_gt.shape[0])    
    if min_len > 0:
        accuracy = numpy.sum(flags_ind[0:min_len] == 
                             flags_ind_gt[0:min_len]) / float(min_len)
    else:
        accuracy = -1

    if not ONLY_EVALUATE:
        duration = segs[-1, 1]
        s_percentages = numpy.zeros((len(class_names), 1))
        percentages = numpy.zeros((len(class_names), 1))
        av_durations = numpy.zeros((len(class_names), 1))

        for iSeg in range(segs.shape[0]):
            s_percentages[class_names.index(classes[iSeg])] += \
                (segs[iSeg, 1]-segs[iSeg, 0])

        for i in range(s_percentages.shape[0]):
            percentages[i] = 100.0 * s_percentages[i] / duration
            S = sum(1 for c in classes if c == class_names[i])
            if S > 0:
                av_durations[i] = s_percentages[i] / S
            else:
                av_durations[i] = 0.0

        for i in range(percentages.shape[0]):
            print(class_names[i], percentages[i], av_durations[i])

        font = {'size': 10}
        plt.rc('font', **font)

        fig = plt.figure()
        ax1 = fig.add_subplot(211)
        ax1.set_yticks(numpy.array(range(len(class_names))))
        ax1.axis((0, duration, -1, len(class_names)))
        ax1.set_yticklabels(class_names)
        ax1.plot(numpy.array(range(len(flags_ind))) * mt_step +
                 mt_step / 2.0, flags_ind)
        if flags_ind_gt.shape[0] > 0:
            ax1.plot(numpy.array(range(len(flags_ind_gt))) * mt_step +
                     mt_step / 2.0, flags_ind_gt + 0.05, '--r')
        plt.xlabel("time (seconds)")
        if accuracy >= 0:
            plt.title('Accuracy = {0:.1f}%'.format(100.0 * accuracy))

        ax2 = fig.add_subplot(223)
        plt.title("Classes percentage durations")
        ax2.axis((0, len(class_names) + 1, 0, 100))
        ax2.set_xticks(numpy.array(range(len(class_names) + 1)))
        ax2.set_xticklabels([" "] + class_names)
        ax2.bar(numpy.array(range(len(class_names))) + 0.5, percentages)

        ax3 = fig.add_subplot(224)
        plt.title("Segment average duration per class")
        ax3.axis((0, len(class_names)+1, 0, av_durations.max()))
        ax3.set_xticks(numpy.array(range(len(class_names) + 1)))
        ax3.set_xticklabels([" "] + class_names)
        ax3.bar(numpy.array(range(len(class_names))) + 0.5, av_durations)
        fig.tight_layout()
        plt.show()
    return accuracy
241014
def c2s(self,p=[0,0]):
        """"""

        return((p[0]-self.canvasx(self.cx1),p[1]-self.canvasy(self.cy1)))
1018311
def get_plot(self, xlim=None, ylim=None):
        

        ncolors = max(3, len(self._doses))
        ncolors = min(9, ncolors)

        import palettable

        colors = palettable.colorbrewer.qualitative.Set1_9.mpl_colors

        y = None
        alldensities = []
        allenergies = []
        plt = pretty_plot(12, 8)

        # Note that this complicated processing of energies is to allow for
        # stacked plots in matplotlib.
        for key, dos in self._doses.items():
            energies = dos['energies']
            densities = dos['densities']
            if not y:
                y = {Spin.up: np.zeros(energies.shape),
                     Spin.down: np.zeros(energies.shape)}
            newdens = {}
            for spin in [Spin.up, Spin.down]:
                if spin in densities:
                    if self.stack:
                        y[spin] += densities[spin]
                        newdens[spin] = y[spin].copy()
                    else:
                        newdens[spin] = densities[spin]
            allenergies.append(energies)
            alldensities.append(newdens)

        keys = list(self._doses.keys())
        keys.reverse()
        alldensities.reverse()
        allenergies.reverse()
        allpts = []
        for i, key in enumerate(keys):
            x = []
            y = []
            for spin in [Spin.up, Spin.down]:
                if spin in alldensities[i]:
                    densities = list(int(spin) * alldensities[i][spin])
                    energies = list(allenergies[i])
                    if spin == Spin.down:
                        energies.reverse()
                        densities.reverse()
                    x.extend(energies)
                    y.extend(densities)
            allpts.extend(list(zip(x, y)))
            if self.stack:
                plt.fill(x, y, color=colors[i % ncolors],
                         label=str(key))
            else:
                plt.plot(x, y, color=colors[i % ncolors],
                         label=str(key), linewidth=3)
            if not self.zero_at_efermi:
                ylim = plt.ylim()
                plt.plot([self._doses[key]['efermi'],
                          self._doses[key]['efermi']], ylim,
                         color=colors[i % ncolors],
                         linestyle='--', linewidth=2)

        if xlim:
            plt.xlim(xlim)
        if ylim:
            plt.ylim(ylim)
        else:
            xlim = plt.xlim()
            relevanty = [p[1] for p in allpts
                         if xlim[0] < p[0] < xlim[1]]
            plt.ylim((min(relevanty), max(relevanty)))

        if self.zero_at_efermi:
            ylim = plt.ylim()
            plt.plot([0, 0], ylim, 'k--', linewidth=2)

        plt.xlabel('Energies (eV)')
        plt.ylabel('Density of states')

        plt.legend()
        leg = plt.gca().get_legend()
        ltext = leg.get_texts()  # all the text.Text instance in the legend
        plt.setp(ltext, fontsize=30)
        plt.tight_layout()
        return plt
423586
def _compute_surface_areas(self, cell_ids):
        
        # Each of the three edges may contribute to the surface areas of all
        # three vertices. Here, only the two adjacent nodes receive a
        # contribution, but other approaches (e.g., the flat cell corrector),
        # may contribute to all three nodes.
        cn = self.cells["nodes"][cell_ids]
        ids = numpy.stack([cn, cn, cn], axis=1)

        half_el = 0.5 * self.edge_lengths[..., cell_ids]
        zero = numpy.zeros([half_el.shape[1]])
        vals = numpy.stack(
            [
                numpy.column_stack([zero, half_el[0], half_el[0]]),
                numpy.column_stack([half_el[1], zero, half_el[1]]),
                numpy.column_stack([half_el[2], half_el[2], zero]),
            ],
            axis=1,
        )

        return ids, vals
141946
def _plot(self):
        """"""
        squares = self._squares()
        sq_dimensions = self.add_squares(squares)

        for index, serie in enumerate(self.series):
            current_square = self._current_square(squares, index)
            self.gaugify(serie, squares, sq_dimensions, current_square)