returns matplotlib figure with anisotropy data plotted against depth
    available depth scales: 'sample_composite_depth', 'sample_core_depth', or 'age' (you must provide an age file to use this option)
194536
def ani_depthplot2(ani_file='rmag_anisotropy.txt', meas_file='magic_measurements.txt', samp_file='er_samples.txt', age_file=None, sum_file=None, fmt='svg', dmin=-1, dmax=-1, depth_scale='sample_core_depth', dir_path='.'):
    
    pcol = 4
    tint = 9
    plots = 0

    # format files to use full path
    # os.path.join(dir_path, ani_file)
    ani_file = pmag.resolve_file_name(ani_file, dir_path)
    if not os.path.isfile(ani_file):
        print("Could not find rmag_anisotropy type file: {}.\nPlease provide a valid file path and try again".format(ani_file))
        return False, "Could not find rmag_anisotropy type file: {}.\nPlease provide a valid file path and try again".format(ani_file)

    # os.path.join(dir_path, meas_file)
    meas_file = pmag.resolve_file_name(meas_file, dir_path)

    if age_file:
        if not os.path.isfile(age_file):
            print(
                'Warning: you have provided an invalid age file.  Attempting to use sample file instead')
            age_file = None
            depth_scale = 'sample_core_depth'
            # os.path.join(dir_path, samp_file)
            samp_file = pmag.resolve_file_name(samp_file, dir_path)
        else:
            # os.path.join(dir_path, age_file)
            samp_file = pmag.resolve_file_name(samp_file, dir_path)
            depth_scale = 'age'
            print(
                'Warning: you have provided an er_ages format file, which will take precedence over er_samples')
    else:
        samp_file = pmag.resolve_file_name(samp_file, dir_path)

    label = 1

    if sum_file:
        sum_file = os.path.join(dir_path, sum_file)

    dmin, dmax = float(dmin), float(dmax)

    # get data read in
    isbulk = 0  # tests if there are bulk susceptibility measurements
    AniData, file_type = pmag.magic_read(ani_file)  # read in tensor elements
    if not age_file:
        # read in sample depth info from er_sample.txt format file
        Samps, file_type = pmag.magic_read(samp_file)
    else:
        # read in sample age info from er_ages.txt format file
        Samps, file_type = pmag.magic_read(samp_file)
        age_unit = Samps[0]['age_unit']
    for s in Samps:
        # change to upper case for every sample name
        s['er_sample_name'] = s['er_sample_name'].upper()
    Meas, file_type = pmag.magic_read(meas_file)
    # print 'meas_file', meas_file
    # print 'file_type', file_type
    if file_type == 'magic_measurements':
        isbulk = 1
    Data = []
    Bulks = []
    BulkDepths = []
    for rec in AniData:
        # look for depth record for this sample
        samprecs = pmag.get_dictitem(Samps, 'er_sample_name',
                                     rec['er_sample_name'].upper(), 'T')
        # see if there are non-blank depth data
        sampdepths = pmag.get_dictitem(samprecs, depth_scale, '', 'F')
        if dmax != -1:
            # fishes out records within depth bounds
            sampdepths = pmag.get_dictitem(
                sampdepths, depth_scale, dmax, 'max')
            sampdepths = pmag.get_dictitem(
                sampdepths, depth_scale, dmin, 'min')
        if len(sampdepths) > 0:  # if there are any....
            # set the core depth of this record
            rec['core_depth'] = sampdepths[0][depth_scale]
            Data.append(rec)  # fish out data with core_depth
            if isbulk:  # if there are bulk data
                chis = pmag.get_dictitem(
                    Meas, 'er_specimen_name', rec['er_specimen_name'], 'T')
                # get the non-zero values for this specimen
                chis = pmag.get_dictitem(
                    chis, 'measurement_chi_volume', '', 'F')
                if len(chis) > 0:  # if there are any....
                    # put in microSI
                    Bulks.append(
                        1e6 * float(chis[0]['measurement_chi_volume']))
                    BulkDepths.append(float(sampdepths[0][depth_scale]))
    if len(Bulks) > 0:  # set min and max bulk values
        bmin = min(Bulks)
        bmax = max(Bulks)
    xlab = "Depth (m)"
    if len(Data) > 0:
        location = Data[0]['er_location_name']
    else:
        return False, 'no data to plot'
    # collect the data for plotting tau  V3_inc and V1_dec
    Depths, Tau1, Tau2, Tau3, V3Incs, P, V1Decs = [], [], [], [], [], [], []
    F23s = []
    Axs = []  # collect the plot ids
# START HERE
    if len(Bulks) > 0:
        pcol += 1
    # get all the s1 values from Data as floats
    s1 = pmag.get_dictkey(Data, 'anisotropy_s1', 'f')
    s2 = pmag.get_dictkey(Data, 'anisotropy_s2', 'f')
    s3 = pmag.get_dictkey(Data, 'anisotropy_s3', 'f')
    s4 = pmag.get_dictkey(Data, 'anisotropy_s4', 'f')
    s5 = pmag.get_dictkey(Data, 'anisotropy_s5', 'f')
    s6 = pmag.get_dictkey(Data, 'anisotropy_s6', 'f')
    nmeas = pmag.get_dictkey(Data, 'anisotropy_n', 'int')
    sigma = pmag.get_dictkey(Data, 'anisotropy_sigma', 'f')
    Depths = pmag.get_dictkey(Data, 'core_depth', 'f')
    # Ss=np.array([s1,s4,s5,s4,s2,s6,s5,s6,s3]).transpose() # make an array
    Ss = np.array([s1, s2, s3, s4, s5, s6]).transpose()  # make an array
    # Ts=np.reshape(Ss,(len(Ss),3,-1)) # and re-shape to be n-length array of
    # 3x3 sub-arrays
    for k in range(len(Depths)):
        # tau,Evecs= pmag.tauV(Ts[k]) # get the sorted eigenvalues and eigenvectors
        # v3=pmag.cart2dir(Evecs[2])[1] # convert to inclination of the minimum
        # eigenvector
        fpars = pmag.dohext(nmeas[k] - 6, sigma[k], Ss[k])
        V3Incs.append(fpars['v3_inc'])
        V1Decs.append(fpars['v1_dec'])
        Tau1.append(fpars['t1'])
        Tau2.append(fpars['t2'])
        Tau3.append(fpars['t3'])
        P.append(old_div(Tau1[-1], Tau3[-1]))
        F23s.append(fpars['F23'])
    if len(Depths) > 0:
        if dmax == -1:
            dmax = max(Depths)
            dmin = min(Depths)
        tau_min = 1
        for t in Tau3:
            if t > 0 and t < tau_min:
                tau_min = t
        tau_max = max(Tau1)
        # tau_min=min(Tau3)
        P_max = max(P)
        P_min = min(P)
        # dmax=dmax+.05*dmax
        # dmin=dmin-.05*dmax

        main_plot = plt.figure(1, figsize=(10, 8))  # make the figure

        version_num = pmag.get_version()
        plt.figtext(.02, .01, version_num)  # attach the pmagpy version number
        ax = plt.subplot(1, pcol, 1)  # make the first column
        Axs.append(ax)
        ax.plot(Tau1, Depths, 'rs')
        ax.plot(Tau2, Depths, 'b^')
        ax.plot(Tau3, Depths, 'ko')
        if sum_file:
            core_depth_key, core_label_key, Cores = read_core_csv_file(
                sum_file)
            for core in Cores:
                depth = float(core[core_depth_key])
                if depth > dmin and depth < dmax:
                    plt.plot([0, 90], [depth, depth], 'b--')
        ax.axis([tau_min, tau_max, dmax, dmin])
        ax.set_xlabel('Eigenvalues')
        if depth_scale == 'sample_core_depth':
            ax.set_ylabel('Depth (mbsf)')
        elif depth_scale == 'age':
            ax.set_ylabel('Age (' + age_unit + ')')
        else:
            ax.set_ylabel('Depth (mcd)')
        ax2 = plt.subplot(1, pcol, 2)  # make the second column
        ax2.plot(P, Depths, 'rs')
        ax2.axis([P_min, P_max, dmax, dmin])
        ax2.set_xlabel('P')
        ax2.set_title(location)
        if sum_file:
            for core in Cores:
                depth = float(core[core_depth_key])
                if depth > dmin and depth < dmax:
                    plt.plot([0, 90], [depth, depth], 'b--')
        Axs.append(ax2)
        ax3 = plt.subplot(1, pcol, 3)
        Axs.append(ax3)
        ax3.plot(V3Incs, Depths, 'ko')
        ax3.axis([0, 90, dmax, dmin])
        ax3.set_xlabel('V3 Inclination')
        if sum_file:
            for core in Cores:
                depth = float(core[core_depth_key])
                if depth > dmin and depth < dmax:
                    plt.plot([0, 90], [depth, depth], 'b--')
        ax4 = plt.subplot(1, np.abs(pcol), 4)
        Axs.append(ax4)
        ax4.plot(V1Decs, Depths, 'rs')
        ax4.axis([0, 360, dmax, dmin])
        ax4.set_xlabel('V1 Declination')
        if sum_file:
            for core in Cores:
                depth = float(core[core_depth_key])
                if depth >= dmin and depth <= dmax:
                    plt.plot([0, 360], [depth, depth], 'b--')
                    if pcol == 4 and label == 1:
                        plt.text(360, depth + tint, core[core_label_key])
        # ax5=plt.subplot(1,np.abs(pcol),5)
        # Axs.append(ax5)
        # ax5.plot(F23s,Depths,'rs')
        # bounds=ax5.axis()
        # ax5.axis([bounds[0],bounds[1],dmax,dmin])
        # ax5.set_xlabel('F_23')
        # ax5.semilogx()
        # if sum_file:
        #    for core in Cores:
        #         depth=float(core[core_depth_key])
        #         if depth>=dmin and depth<=dmax:
        #            plt.plot([bounds[0],bounds[1]],[depth,depth],'b--')
        #            if pcol==5 and label==1:plt.text(bounds[1],depth+tint,core[core_label_key])
        # if pcol==6:
        if pcol == 5:
            # ax6=plt.subplot(1,pcol,6)
            ax6 = plt.subplot(1, pcol, 5)
            Axs.append(ax6)
            ax6.plot(Bulks, BulkDepths, 'bo')
            ax6.axis([bmin - 1, 1.1 * bmax, dmax, dmin])
            ax6.set_xlabel('Bulk Susc. (uSI)')
            if sum_file:
                for core in Cores:
                    depth = float(core[core_depth_key])
                    if depth >= dmin and depth <= dmax:
                        plt.plot([0, bmax], [depth, depth], 'b--')
                        if label == 1:
                            plt.text(1.1 * bmax, depth + tint,
                                     core[core_label_key])
        for x in Axs:
            # this makes the x-tick labels more reasonable - they were
            # overcrowded using the defaults
            pmagplotlib.delticks(x)
        fig_name = location + '_ani_depthplot.' + fmt
        return main_plot, fig_name
    else:
        return False, "No data to plot"
125922
def ax(self):
        """"""
        if self._ax is None:
            import matplotlib.pyplot as plt
            plt.figure()
            self._ax = plt.axes(projection=self._get_sample_projection())
        return self._ax
167338
def _get_subplot_extents(self, overlay, ranges, range_type):
        
        if range_type == 'combined':
            extents = {'extents': [], 'soft': [], 'hard': [], 'data': []}
        else:
            extents = {range_type: []}
        items = overlay.items()
        if self.batched and self.subplots:
            subplot = list(self.subplots.values())[0]
            subplots = [(k, subplot) for k in overlay.data.keys()]
        else:
            subplots = self.subplots.items()

        for key, subplot in subplots:
            found = False
            if subplot is None:
                continue
            layer = overlay.data.get(key, None)
            if isinstance(self.hmap, DynamicMap) and layer is None:
                for _, layer in items:
                    if isinstance(layer, subplot.hmap.type):
                        found = True
                        break
                if not found:
                    layer = None
            if layer is None or not subplot.apply_ranges:
                continue

            if isinstance(layer, CompositeOverlay):
                sp_ranges = ranges
            else:
                sp_ranges = util.match_spec(layer, ranges) if ranges else {}
            for rt in extents:
                extent = subplot.get_extents(layer, sp_ranges, range_type=rt)
                extents[rt].append(extent)
        return extents
46240
def scaledBy(self, scale):
        
        scaled = deepcopy(self)
    
        if type(scaled.value) in (int, float):
            scaled.value *= scale
        elif isinstance(scaled.value, numbers):
            scaled.value.values = tuple(v * scale for v in scaled.value.values)

        return scaled
6418
def plot_slnp(fignum, SiteRec, datablock, key):
    
# make the stereonet
    plt.figure(num=fignum)
    plot_net(fignum)
    s = SiteRec['er_site_name']
#
#   plot on the data
#
    coord = SiteRec['site_tilt_correction']
    title = ''
    if coord == '-1':
        title = s + ": specimen coordinates"
    if coord == '0':
        title = s + ": geographic coordinates"
    if coord == '100':
        title = s + ": tilt corrected coordinates"
    DIblock, GCblock = [], []
    for plotrec in datablock:
        if plotrec[key + '_direction_type'] == 'p':  # direction is pole to plane
            GCblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
        else:  # assume direction is a directed line
            DIblock.append(
                (float(plotrec[key + "_dec"]), float(plotrec[key + "_inc"])))
    if len(DIblock) > 0:
        plot_di(fignum, DIblock)  # plot directed lines
    if len(GCblock) > 0:
        for pole in GCblock:
            plot_circ(fignum, pole, 90., 'g')  # plot directed lines
#
# put on the mean direction
#
    x, y = [], []
    XY = pmag.dimap(float(SiteRec["site_dec"]), float(SiteRec["site_inc"]))
    x.append(XY[0])
    y.append(XY[1])
    plt.scatter(x, y, marker='d', s=80, c='g')
    plt.title(title)
#
# get the alpha95
#
    Xcirc, Ycirc = [], []
    Da95, Ia95 = pmag.circ(float(SiteRec["site_dec"]), float(
        SiteRec["site_inc"]), float(SiteRec["site_alpha95"]))
    for k in range(len(Da95)):
        XY = pmag.dimap(Da95[k], Ia95[k])
        Xcirc.append(XY[0])
        Ycirc.append(XY[1])
    plt.plot(Xcirc, Ycirc, 'g')
239974
def _calcDepths(self):
        '''
        
        '''
        depths = self.layerBoundaries.mean(axis=1)[1:]

        depth_y = []
        for y in self.y:
            if y in ['p23', 'b23', 'nb23']:
                depth_y = np.r_[depth_y, depths[0]]
            elif y in ['p4', 'ss4(L23)', 'ss4(L4)', 'b4', 'nb4']:
                depth_y = np.r_[depth_y, depths[1]]
            elif y in ['p5(L23)', 'p5(L56)', 'b5', 'nb5']:
                depth_y = np.r_[depth_y, depths[2]]
            elif y in ['p6(L4)', 'p6(L56)', 'b6', 'nb6']:
                depth_y = np.r_[depth_y, depths[3]]
            else:
                raise Exception, 'this aint right'
                
        return depth_y
997813
def create_anisophaplot(plotman, x, y, z, alpha, options):
    '''
    '''
    sizex, sizez = getfigsize(plotman)
    # create figure
    f, ax = plt.subplots(2, 3, figsize=(3 * sizex, 2 * sizez))
    if options.title is not None:
        plt.suptitle(options.title, fontsize=18)
        plt.subplots_adjust(wspace=1, top=0.8)
    # plot phase
    cidx = plotman.parman.add_data(x)
    cidy = plotman.parman.add_data(y)
    cidz = plotman.parman.add_data(z)
    cidxy = plotman.parman.add_data(np.subtract(x, y))
    cidyz = plotman.parman.add_data(np.subtract(y, z))
    cidzx = plotman.parman.add_data(np.subtract(z, x))
    plot_pha(cidx, ax[0, 0], plotman, 'x', alpha,
             options.pha_vmin, options.pha_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.pha_cbtiks, options.no_elecs,
             )
    plot_pha(cidy, ax[0, 1], plotman, 'y', alpha,
             options.pha_vmin, options.pha_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.pha_cbtiks, options.no_elecs,
             )
    plot_pha(cidz, ax[0, 2], plotman, 'z', alpha,
             options.pha_vmin, options.pha_vmax,
             options.xmin, options.xmax, options.zmin, options.zmax,
             options.unit, options.pha_cbtiks, options.no_elecs,
             )
    plot_ratio(cidxy, ax[1, 0], plotman, 'x-y', alpha,
               options.rat_vmin, options.rat_vmax,
               options.xmin, options.xmax, options.zmin, options.zmax,
               options.unit, options.mag_cbtiks, options.no_elecs,
               )
    plot_ratio(cidyz, ax[1, 1], plotman, 'y-z', alpha,
               options.rat_vmin, options.rat_vmax,
               options.xmin, options.xmax, options.zmin, options.zmax,
               options.unit, options.mag_cbtiks, options.no_elecs,
               )
    plot_ratio(cidzx, ax[1, 2], plotman, 'z-x', alpha,
               options.rat_vmin, options.rat_vmax,
               options.xmin, options.xmax, options.zmin, options.zmax,
               options.unit, options.mag_cbtiks, options.no_elecs,
               )
    f.tight_layout()
    f.savefig('pha_aniso.png', dpi=300)
    return f, ax
1249741
def helper_for_plot_data(self, X, plot_limits, visible_dims, fixed_inputs, resolution):
    
    #work out what the inputs are for plotting (1D or 2D)
    if fixed_inputs is None:
        fixed_inputs = []
    fixed_dims = get_fixed_dims(fixed_inputs)
    free_dims = get_free_dims(self, visible_dims, fixed_dims)

    if len(free_dims) == 1:
        #define the frame on which to plot
        resolution = resolution or 200
        Xnew, xmin, xmax = x_frame1D(X[:,free_dims], plot_limits=plot_limits, resolution=resolution)
        Xgrid = np.zeros((Xnew.shape[0],self.input_dim))
        Xgrid[:,free_dims] = Xnew
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
        x = Xgrid
        y = None
    elif len(free_dims) == 2:
        #define the frame for plotting on
        resolution = resolution or 35
        Xnew, x, y, xmin, xmax = x_frame2D(X[:,free_dims], plot_limits, resolution)
        Xgrid = np.zeros((Xnew.shape[0], self.input_dim))
        Xgrid[:,free_dims] = Xnew
        #xmin = Xgrid.min(0)[free_dims]
        #xmax = Xgrid.max(0)[free_dims]
        for i,v in fixed_inputs:
            Xgrid[:,i] = v
    else:
        raise TypeError("calculated free_dims {} from visible_dims {} and fixed_dims {} is neither 1D nor 2D".format(free_dims, visible_dims, fixed_dims))
    return fixed_dims, free_dims, Xgrid, x, y, xmin, xmax, resolution
1290427
def _read_color_and_depth_image(self):
        
        frames = self._pipe.wait_for_frames()
        if self._depth_align:
            frames = self._align.process(frames)

        depth_frame = frames.get_depth_frame()
        color_frame = frames.get_color_frame()

        if not depth_frame or not color_frame:
            logging.warning('Could not retrieve frames.')
            return None, None

        if self._filter_depth:
            depth_frame = self._filter_depth_frame(depth_frame)

        # convert to numpy arrays
        depth_image = self._to_numpy(depth_frame, np.float32)
        color_image = self._to_numpy(color_frame, np.uint8)

        # convert depth to meters
        depth_image *= self._depth_scale

        # bgr to rgb
        color_image = color_image[..., ::-1]

        depth = DepthImage(depth_image, frame=self._frame)
        color = ColorImage(color_image, frame=self._frame)
        return color, depth
31735
def plot_acquisition(bounds,input_dim,model,Xdata,Ydata,acquisition_function,suggested_sample, filename = None):
    '''
    
    '''

    # Plots in dimension 1
    if input_dim ==1:
        # X = np.arange(bounds[0][0], bounds[0][1], 0.001)
        # X = X.reshape(len(X),1)
        # acqu = acquisition_function(X)
        # acqu_normalized = (-acqu - min(-acqu))/(max(-acqu - min(-acqu))) # normalize acquisition
        # m, v = model.predict(X.reshape(len(X),1))
        # plt.ioff()
        # plt.figure(figsize=(10,5))
        # plt.subplot(2, 1, 1)
        # plt.plot(X, m, 'b-', label=u'Posterior mean',lw=2)
        # plt.fill(np.concatenate([X, X[::-1]]), \
        #         np.concatenate([m - 1.9600 * np.sqrt(v),
        #                     (m + 1.9600 * np.sqrt(v))[::-1]]), \
        #         alpha=.5, fc='b', ec='None', label='95% C. I.')
        # plt.plot(X, m-1.96*np.sqrt(v), 'b-', alpha = 0.5)
        # plt.plot(X, m+1.96*np.sqrt(v), 'b-', alpha=0.5)
        # plt.plot(Xdata, Ydata, 'r.', markersize=10, label=u'Observations')
        # plt.axvline(x=suggested_sample[len(suggested_sample)-1],color='r')
        # plt.title('Model and observations')
        # plt.ylabel('Y')
        # plt.xlabel('X')
        # plt.legend(loc='upper left')
        # plt.xlim(*bounds)
        # grid(True)
        # plt.subplot(2, 1, 2)
        # plt.axvline(x=suggested_sample[len(suggested_sample)-1],color='r')
        # plt.plot(X,acqu_normalized, 'r-',lw=2)
        # plt.xlabel('X')
        # plt.ylabel('Acquisition value')
        # plt.title('Acquisition function')
        # grid(True)
        # plt.xlim(*bounds)

        x_grid = np.arange(bounds[0][0], bounds[0][1], 0.001)
        x_grid = x_grid.reshape(len(x_grid),1)
        acqu = acquisition_function(x_grid)
        acqu_normalized = (-acqu - min(-acqu))/(max(-acqu - min(-acqu)))
        m, v = model.predict(x_grid)


        model.plot_density(bounds[0], alpha=.5)

        plt.plot(x_grid, m, 'k-',lw=1,alpha = 0.6)
        plt.plot(x_grid, m-1.96*np.sqrt(v), 'k-', alpha = 0.2)
        plt.plot(x_grid, m+1.96*np.sqrt(v), 'k-', alpha=0.2)

        plt.plot(Xdata, Ydata, 'r.', markersize=10)
        plt.axvline(x=suggested_sample[len(suggested_sample)-1],color='r')
        factor = max(m+1.96*np.sqrt(v))-min(m-1.96*np.sqrt(v))

        plt.plot(x_grid,0.2*factor*acqu_normalized-abs(min(m-1.96*np.sqrt(v)))-0.25*factor, 'r-',lw=2,label ='Acquisition (arbitrary units)')
        plt.xlabel('x')
        plt.ylabel('f(x)')
        plt.ylim(min(m-1.96*np.sqrt(v))-0.25*factor,  max(m+1.96*np.sqrt(v))+0.05*factor)
        plt.axvline(x=suggested_sample[len(suggested_sample)-1],color='r')
        plt.legend(loc='upper left')


        if filename!=None:
            savefig(filename)
        else:
            plt.show()

    if input_dim ==2:
        X1 = np.linspace(bounds[0][0], bounds[0][1], 200)
        X2 = np.linspace(bounds[1][0], bounds[1][1], 200)
        x1, x2 = np.meshgrid(X1, X2)
        X = np.hstack((x1.reshape(200*200,1),x2.reshape(200*200,1)))
        acqu = acquisition_function(X)
        acqu_normalized = (-acqu - min(-acqu))/(max(-acqu - min(-acqu)))
        acqu_normalized = acqu_normalized.reshape((200,200))
        m, v = model.predict(X)
        plt.figure(figsize=(15,5))
        plt.subplot(1, 3, 1)
        plt.contourf(X1, X2, m.reshape(200,200),100)
        plt.plot(Xdata[:,0], Xdata[:,1], 'r.', markersize=10, label=u'Observations')
        plt.colorbar()
        plt.xlabel('X1')
        plt.ylabel('X2')
        plt.title('Posterior mean')
        plt.axis((bounds[0][0],bounds[0][1],bounds[1][0],bounds[1][1]))
        ##
        plt.subplot(1, 3, 2)
        plt.plot(Xdata[:,0], Xdata[:,1], 'r.', markersize=10, label=u'Observations')
        plt.contourf(X1, X2, np.sqrt(v.reshape(200,200)),100)
        plt.colorbar()
        plt.xlabel('X1')
        plt.ylabel('X2')
        plt.title('Posterior sd.')
        plt.axis((bounds[0][0],bounds[0][1],bounds[1][0],bounds[1][1]))
        ##
        plt.subplot(1, 3, 3)
        plt.contourf(X1, X2, acqu_normalized,100)
        plt.colorbar()
        plt.plot(suggested_sample[:,0],suggested_sample[:,1],'k.', markersize=10)
        plt.xlabel('X1')
        plt.ylabel('X2')
        plt.title('Acquisition function')
        plt.axis((bounds[0][0],bounds[0][1],bounds[1][0],bounds[1][1]))
        if filename!=None:
            savefig(filename)
        else:
            plt.show()
762457
def _figure_data(self, plot, fmt='html', doc=None, as_script=False, **kwargs):
        
        model = plot.state
        if doc is None:
            doc = plot.document
        else:
            plot.document = doc

        for m in model.references():
            m._document = None

        doc.theme = self.theme
        doc.add_root(model)

        # Bokeh raises warnings about duplicate tools and empty subplots
        # but at the holoviews level these are not issues
        logger = logging.getLogger(bokeh.core.validation.check.__file__)
        logger.disabled = True

        if fmt == 'png':
            from bokeh.io.export import get_screenshot_as_png
            img = get_screenshot_as_png(plot.state, None)
            imgByteArr = BytesIO()
            img.save(imgByteArr, format='PNG')
            data = imgByteArr.getvalue()
            if as_script:
                b64 = base64.b64encode(data).decode("utf-8")
                (mime_type, tag) = MIME_TYPES[fmt], HTML_TAGS[fmt]
                src = HTML_TAGS['base64'].format(mime_type=mime_type, b64=b64)
                div = tag.format(src=src, mime_type=mime_type, css='')
                js = ''
        else:
            try:
                with silence_warnings(EMPTY_LAYOUT, MISSING_RENDERERS):
                    js, div, _ = notebook_content(model)
                html = NOTEBOOK_DIV.format(plot_script=js, plot_div=div)
                data = encode_utf8(html)
                doc.hold()
            except:
                logger.disabled = False
                raise
            logger.disabled = False

        plot.document = doc
        if as_script:
            return div, js
        return data
317137
def plot_fit(self, intervals=True, **kwargs):
        
        import matplotlib.pyplot as plt
        import seaborn as sns

        figsize = kwargs.get('figsize',(10,7))
        series_type = kwargs.get('series_type','Smoothed')

        if self.latent_variables.estimated is False:
            raise Exception("No latent variables estimated!")
        else:
            date_index = copy.deepcopy(self.index)
            date_index = date_index[self.integ:self.data_original.shape[0]+1]

            if series_type == 'Smoothed':
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())
            elif series_type == 'Filtered':
                mu, V, _, _, _ = self._model(self.data,self.latent_variables.get_z_values())
            else:
                mu, V = self.smoothed_state(self.data,self.latent_variables.get_z_values())

            mu = mu[0][:-1]
            V = V.ravel()

            plt.figure(figsize=figsize) 
            
            plt.subplot(3, 1, 1)
            plt.title(self.data_name + " Raw and " + series_type)   

            if intervals == True:
                alpha =[0.15*i/float(100) for i in range(50,12,-2)]
                plt.fill_between(date_index[2:], mu[2:] + 1.98*np.sqrt(V[:-1][2:]), mu[2:] - 1.98*np.sqrt(V[:-1][2:]), alpha=0.15,label='95% C.I.') 

            plt.plot(date_index,self.data,label='Data')
            plt.plot(date_index,mu,label=series_type,c='black')
            plt.legend(loc=2)
            
            plt.subplot(3, 1, 2)
            plt.title(self.data_name + " Local Level")  

            if intervals == True:
                alpha =[0.15*i/float(100) for i in range(50,12,-2)]
                plt.fill_between(date_index[2:], mu[2:] + 1.98*np.sqrt(V[:-1][2:]), mu[2:] - 1.98*np.sqrt(V[:-1][2:]), alpha=0.15,label='95% C.I.') 

            plt.plot(date_index,mu,label='Local Level')
            plt.legend(loc=2)
            plt.subplot(3, 1, 3)
            plt.title("Measurement Noise")  
            plt.plot(date_index,self.data-mu)
            plt.show()
1072037
def depth(args):
    
    import seaborn as sns

    p = OptionParser(depth.__doc__)
    opts, args, iopts = p.set_image_options(args, figsize="14x14")

    if len(args) != 1:
        sys.exit(not p.print_help())

    tsvfile, = args
    fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(ncols=2, nrows=2,
                                    figsize=(iopts.w, iopts.h))
    plt.tight_layout(pad=6)

    data = pd.read_csv(tsvfile, sep="\t", low_memory=False)

    ids, treds = read_treds()
    for (dp, ax, title) in zip(("FDP", "PDP", "RDP", "PEDP"),
                        (ax1, ax2, ax3, ax4),
                        ("Spanning reads", "Partial reads",
                         "Repeat-only reads", "Paired-end reads")):
        logging.debug("Build {}".format(title))
        # Construct related data structure
        xd = []     # (tred, dp)
        mdp = []    # (tred, median_dp)
        for tred, motif in zip(treds["abbreviation"], treds["motif"]):
            if tred in ignore:
                logging.debug("Ignore {}".format(tred))
                continue
            if len(motif) > 4:
                if "/" in motif:  # CTG/CAG
                    motif = motif.split("/")[0]
                else:
                    motif = motif[:4] + ".."
            xtred = "{} {}".format(tred, motif)
            md = [x for x in data[tred + '.' + dp] if x >= 0]
            subsample = 10000 if dp == "RDP" else 1000
            md = sample(md, subsample)
            pmd = [x for x in md if x > 0]
            median = np.median(pmd) if pmd else 0
            mdp.append((xtred, median))
            for d in md:
                xd.append((xtred, d))

        # Determine order
        mdp.sort(key=lambda x: x[1])
        order, mdp = zip(*mdp)

        # OK, now plot
        xt, xd = zip(*xd)
        sns.boxplot(xt, xd, ax=ax, order=order, fliersize=2)
        xticklabels = ax.get_xticklabels()
        ax.set_xticklabels(xticklabels, rotation=45, ha="right")
        ax.set_title("Number of {} per locus".format(title), size=18)
        ylim = 30 if dp == "RDP" else 100
        ax.set_ylim(0, ylim)

        yticklabels = [int(x) for x in ax.get_yticks()]
        ax.set_yticklabels(yticklabels, family='Helvetica', size=14)

    root = fig.add_axes([0, 0, 1, 1])
    pad = .04
    panel_labels(root, ((pad,  1 - pad, "A"), (1 / 2. + pad / 2,  1 - pad, "B"),
                        (pad, .5 - pad / 2, "C"), (1 / 2. + pad / 2, .5 - pad / 2, "D")))
    normalize_axes(root)

    image_name = "depth." + iopts.format
    savefig(image_name, dpi=iopts.dpi, iopts=iopts)
597703
def pilscale(self, r):
        
        return r * float(self.upsamplefactor) / float(self.binfactor)
1211929
def compute_near_isotropic_downsampling_scales(size,
                                               voxel_size,
                                               dimensions_to_downsample,
                                               max_scales=DEFAULT_MAX_DOWNSAMPLING_SCALES,
                                               max_downsampling=DEFAULT_MAX_DOWNSAMPLING,
                                               max_downsampled_size=DEFAULT_MAX_DOWNSAMPLED_SIZE):
    """"""

    num_dims = len(voxel_size)
    cur_scale = np.ones((num_dims, ), dtype=int)
    scales = [tuple(cur_scale)]
    while (len(scales) < max_scales and (np.prod(cur_scale) < max_downsampling) and
           (size / cur_scale).max() > max_downsampled_size):
        # Find dimension with smallest voxelsize.
        cur_voxel_size = cur_scale * voxel_size
        smallest_cur_voxel_size_dim = dimensions_to_downsample[np.argmin(cur_voxel_size[
            dimensions_to_downsample])]
        cur_scale[smallest_cur_voxel_size_dim] *= 2
        target_voxel_size = cur_voxel_size[smallest_cur_voxel_size_dim] * 2
        for d in dimensions_to_downsample:
            if d == smallest_cur_voxel_size_dim:
                continue
            d_voxel_size = cur_voxel_size[d]
            if abs(d_voxel_size - target_voxel_size) > abs(d_voxel_size * 2 - target_voxel_size):
                cur_scale[d] *= 2
        scales.append(tuple(cur_scale))
    return scales
799874
def build_D3treepie(old, MAX_DEPTH, level=1, toplayer=None):
    
    d = {}
    if not old:
        old = toplayer
    for x in old:
        label = x.bestLabel(quotes=False).replace("_", " ")
        if x.children() and level < MAX_DEPTH:
            size = len(x.children())
            d[x.qname] = [
                label, [size, size],
                build_D3treepie(x.children(), MAX_DEPTH, level + 1)
            ]
        else:
            size = 1
            d[x.qname] = [label, [size, size], {}]

    return d
1206989
def save_figure_raw_data(figure="gcf", **kwargs):
    

    # choose a path to save to
    path = _s.dialogs.Save(**kwargs)
    if path=="": return "aborted."

    # if no argument was given, get the current axes
    if figure=="gcf": figure = _pylab.gcf()

    for n in range(len(figure.axes)):
        a = figure.axes[n]

        for m in range(len(a.lines)):
            l = a.lines[m]

            x = l.get_xdata()
            y = l.get_ydata()

            p = _os.path.split(path)
            p = _os.path.join(p[0], "axes" + str(n) + " line" + str(m) + " " + p[1])
            print(p)

            # loop over the data
            f = open(p, 'w')
            for j in range(0, len(x)):
                f.write(str(x[j]) + "\t" + str(y[j]) + "\n")
            f.close()