Пример #1
0
def vis_back_proj(ind=1, img_style="edge", pcd_style="intens"):
    imgfile = "img/" + str(ind).zfill(
        params["file_name_digits"]) + "." + params['image_format']
    if img_style == "edge":
        gray = cv2.imread(imgfile)
        edges = cv2.Canny(gray, 50, 150, apertureSize=3)
        img = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
    elif img_style == "orig":
        img = cv2.imread(imgfile)
    else:
        print "Please input the right image style"

    csvfile = "pcd/" + str(ind).zfill(params["file_name_digits"]) + ".csv"

    csv = np.genfromtxt(csvfile, delimiter=",", skip_header=1)
    pcd = csv[:, :3]
    dis_arr = np.linalg.norm(pcd, axis=1)
    intens = csv[:, 3]

    filels = os.listdir(".")
    for file in filels:
        if file.find("cali_result.txt") > -1:
            r_t = np.genfromtxt(file, delimiter=',')
            print "Load ", file, " as the extrinsic calibration parameters!"
            break
    else:
        raise Exception("No calibration file is found!")

    if pcd_style == "intens":
        pcd_color = np.fliplr(
            (cm.jet(intens.astype(np.float32) / intens.max()) * 255).astype(
                np.int32)[:, :3])
    elif pcd_style == "dis":
        pcd_color = np.fliplr(
            (cm.jet(dis_arr / 10) * 255).astype(np.int32)[:, :3])
    else:
        print "Please input the right pcd color style"

    backproj_img = back_project_pcd(img, pcd, pcd_color, r_t)
    resized_img_for_view = cv2.resize(backproj_img, (int(W / 4.), int(H / 4.)))

    window_name = "ind: " + str(
        ind) + " img_style: " + img_style + " pcd_style: " + pcd_style
    cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
    cv2.imshow(window_name, resized_img_for_view)
    k = cv2.waitKey(0)
    if k == 27:  # wait for ESC key to exit
        cv2.destroyAllWindows()
    elif k == ord('s'):  # wait for 's' key to save and exit
        save_file_name = str(ind).zfill(
            params["file_name_digits"]
        ) + "_" + img_style + "_" + pcd_style + "." + params['image_format']
        cv2.imwrite(save_file_name, img, [cv2.IMWRITE_JPEG_QUALITY, 70])
        print "The image is saved to ", save_file_name
        cv2.destroyAllWindows()
Пример #2
0
def compareVoteonBar():
    total = 0
    for elval1 in listt:
        total += elval1[1]
    for elval in listt:
        c = "%.3f" % ((elval[1] / total) * 100)
        chng.append([elval[0], float(c)])
    perclist = sorted(chng, key=itemgetter(1))
    for element in perclist:
        names.append(element[0])
        byvote.append(element[1])
    byvote.reverse()
    names.reverse()
    length = len(names)
    aaa = np.arange(length)
    rex = list(map("{} %".format, byvote))
    k = 0
    for con in names:
        plot.bar(k,
                 byvote[k],
                 align='center',
                 color=cm.jet(1. * k / length),
                 label=con)
        k += 1
        plot.xticks(aaa, rex)
    plot.xlabel("Nominees")
    plot.ylabel("Vote percentages")
    plot.legend()
    plot.autoscale()
    plot.tight_layout()
    plot.savefig("CompVotePercs.pdf")
    plot.close()
    def SetClassPoints(self, classCoords):
        self.sizer4.DeleteWindows()
        vals = np.arange(float(len(classCoords))) / len(classCoords)
        if len(vals) > 0:
            vals += (1.0 - vals[-1]) / 2
            colors = [np.array(cm.jet(val)) * 255 for val in vals]
            colors_dict = {}
            i=0
            for name in classCoords:
                colors_dict[name] = colors[i]
                i+=1
            self.sizer4.Add(wx.StaticText(self.Parent, -1, 'Classes:'))
            i=1
            classCoords_ordered = [name for name in classCoords if name[:8] != 'training']
            classCoords_ordered.extend([name for name in classCoords if name[:8] == 'training'])
            for name in classCoords_ordered:
                if i == len(classCoords)/2 + 1:
                    self.sizer4.Add(wx.StaticText(self.Parent, -1, 'Training:'))
                checkBox = wx.CheckBox(self.Parent, wx.NewId(), '%d) %s'%(i,name))
      
                #checkBox.SetForegroundColour(color)   # Doesn't work on Mac. Works on Windows.
                checkBox.SetBackgroundColour(colors_dict[name])
                checkBox.SetValue(True)
                self.sizer4.Add(checkBox, flag=wx.EXPAND)

                def OnTogglePhenotype(evt):
                    className = evt.EventObject.Label
                    for listener in self.listeners:
                        listener.ToggleClass(className[3:], evt.Checked())

                checkBox.Bind(wx.EVT_CHECKBOX, OnTogglePhenotype)
                i+=1
Пример #4
0
    def plot_mesh(self):
        """Plot the overall BEM mesh and domain geometry

        Each domain can have different color by modifing line:
        
        plt.plot(np.append([BE.xa for BE in BEMobj.BEs_edge], BEMobj.BEs_edge[0].xa), 
             np.append([BE.ya for BE in BEMobj.BEs_edge], BEMobj.BEs_edge[0].ya), 
             ,color=c,markersize=5)

        plt.scatter([BE.xc for BE in BEMobj.BEs_edge], 
                            [BE.yc for BE in BEMobj.BEs_edge], color=c, s=25)

        Author:Bin Wang([email protected])
        Date: July. 2017
        """
        plt.figure(figsize=(6, 6))
        plt.axes().set_aspect('equal')
        plt.axes().set_title('BEM Mesh', fontsize=15)
        plt.axes().set_xlabel('x(m)')
        plt.axes().set_ylabel('y(m)')

        #plt.xticks(np.arange(-3, 9, 1))
        #plt.yticks(np.arange(-2, 5,1))

        #plt.grid(b=True, which='major', color='k', linestyle=':')
        #plt.grid(b=True, which='minor', color='k', linestyle='--', alpha=0.2)
        #plt.minorticks_on()

        Total_Ele = 0

        color = cm.jet(np.linspace(0, 1, self.NumObj + 1))
        for i, c in zip(range(self.NumObj), color):  #For each subdomain
            BEMobj = self.BEMobjs[i]

            #Boundary elements
            plt.plot(np.append([BE.xa for BE in BEMobj.BEs_edge],
                               BEMobj.BEs_edge[0].xa),
                     np.append([BE.ya for BE in BEMobj.BEs_edge],
                               BEMobj.BEs_edge[0].ya),
                     'bo-',
                     markersize=5)

            if (BEMobj.BEs_edge[0].element_type == "Quad"):
                plt.scatter([BE.xc for BE in BEMobj.BEs_edge],
                            [BE.yc for BE in BEMobj.BEs_edge],
                            color='b',
                            s=25)

            Total_Ele += len(BEMobj.BEs_edge)

        #plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
        plt.tight_layout()
        #plt.savefig('Couplded_Fig.png', format='png', dpi=300)

        print('-----Mesh Info-----')
        print('Total Number of Elements:', Total_Ele)
        print("Total Number of Subdomains:", self.NumObj)
        plt.show()
Пример #5
0
def random_jet(bgcolor=(255, 255, 255)):
    """Generate random RGB lut for nice visually object distinguishing.

    Return random uint8 cmap based on jet colors.
    """
    lut = (cm.jet(np.arange(256))[...,:3] * 256).round().astype(np.uint8)
    np.random.shuffle(lut)
    lut[0] = bgcolor
    return lut
Пример #6
0
 def get_colors(self):
     if self.colors:
         colors = self.colors
     elif max(list(map(len, self.x_points)))==0:
         colors = []
     else:
         # Choose colors from jet colormap starting with light blue (0.28)
         vals = np.arange(0.28, 1.28, 1. / len(self.x_points)) % 1.
         colors = [colorConverter.to_rgba(cm.jet(val), alpha=0.75) 
                   for val in vals]
     return colors
Пример #7
0
    def plotReflectance(root, dirpath, filename):
        try:
            referenceGroup = root.getGroup("Reflectance")
            rrsData = referenceGroup.getDataset("Rrs")

            font = {
                'family': 'serif',
                'color': 'darkred',
                'weight': 'normal',
                'size': 16,
            }

            x = []
            for k in rrsData.data.dtype.names:
                if Utilities.isFloat(k):
                    x.append(k)

            total = rrsData.data.shape[0]
            color = iter(cm.jet(np.linspace(0, 1, total)))
            for i in range(total):
                y = []
                for k in x:
                    y.append(rrsData.data[k][i])

                c = next(color)
                plt.plot(x, y, 'k', c=c)
                #if (i % 25) == 0:
                #    plt.plot(x, y, 'k', color=(i/total, 0, 1-i/total, 1))

            #plt.title('Remote sensing reflectance', fontdict=font)
            #plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font)
            plt.xlabel('wavelength (nm)', fontdict=font)
            plt.ylabel('Rrs ($sr^{-1}$)', fontdict=font)

            # Tweak spacing to prevent clipping of ylabel
            plt.subplots_adjust(left=0.15)
            #plt.show()

            # Create output directory
            plotdir = os.path.join(dirpath, 'Plots')
            os.makedirs(plotdir, exist_ok=True)

            # Save the plot
            fp = os.path.join(plotdir, filename + '.png')
            plt.savefig(fp)
            plt.close(
            )  # This prevents displaying the polt on screen with certain IDEs
        except:
            e = sys.exc_info()[0]
            print("Error: %s" % e)
Пример #8
0
    def SetClassPoints(self, classes):
        if len(classes) == 0:
            logging.warn('There are no objects to classify in this image.')
            return
        from matplotlib.pyplot import cm
        self.classes = classes
        vals = np.arange(0, 1, 1. / len(classes))
        vals += (1.0 - vals[-1]) / 2
        self.colors = [np.array(cm.jet(val)) * 255 for val in vals]
        self.class_nums = [str(i + 1) for i, _ in enumerate(classes)]

        self.classVisible = {}
        for className in classes.keys():
            self.classVisible[className] = True
        self.Refresh()
    def SetClassPoints(self, classes):
        if len(classes) == 0:
            logging.warn('There are no objects to classify in this image.')
            return
        from matplotlib.pyplot import cm
        self.classes = classes
        vals = np.arange(0, 1, 1. / len(classes))
        vals += (1.0 - vals[-1]) / 2
        self.colors = [np.array(cm.jet(val)) * 255 for val in vals]
        self.class_nums = [str(i+1) for i,_ in enumerate(classes)]

        self.classVisible = {}
        for className in classes.keys():
            self.classVisible[className] = True 
        self.Refresh()
Пример #10
0
    def plotDataset(root, filename, name, label):
        try:
            referenceGroup = root.getGroup("Reflectance")
            rrsData = referenceGroup.getDataset(name)

            font = {
                'family': 'serif',
                'color': 'darkred',
                'weight': 'normal',
                'size': 16,
            }

            x = []
            for k in rrsData.data.dtype.names:
                x.append(k)

            total = rrsData.data.shape[0]
            color = iter(cm.jet(np.linspace(0, 1, total)))
            for i in range(total):
                y = []
                for k in x:
                    y.append(rrsData.data[k][i])

                c = next(color)
                plt.plot(x, y, 'k', c=c)
                #if (i % 25) == 0:
                #    plt.plot(x, y, 'k', color=(i/total, 0, 1-i/total, 1))

            #plt.title('Remote sensing reflectance', fontdict=font)
            #plt.text(2, 0.65, r'$\cos(2 \pi t) \exp(-t)$', fontdict=font)
            plt.xlabel('wavelength (nm)', fontdict=font)
            plt.ylabel(label, fontdict=font)

            # Tweak spacing to prevent clipping of ylabel
            plt.subplots_adjust(left=0.15)
            #plt.show()
            plt.savefig('Plots/' + filename + '.png')
            plt.close(
            )  # This prevents displaying the polt on screen with certain IDEs
        except:
            e = sys.exc_info()[0]
            print("Error: %s" % e)
 def SetClassPoints(self, classCoords):
     self.sizer4.DeleteWindows()
     vals = np.arange(float(len(classCoords))) / len(classCoords)
     if len(vals) > 0:
         vals += (1.0 - vals[-1]) / 2
         colors = [np.array(cm.jet(val)) * 255 for val in vals]
         
         self.sizer4.Add(wx.StaticText(self.Parent, -1, 'Classes:'))
         i=1
         for (name, keys), color in zip(classCoords.items(), colors):
             checkBox = wx.CheckBox(self.Parent, wx.NewId(), '%d) %s'%(i,name))
             checkBox.SetForegroundColour(color)   # Doesn't work on Mac. Works on Windows.
             checkBox.SetValue(True)
             self.sizer4.Add(checkBox, flag=wx.EXPAND)
             
             def OnTogglePhenotype(evt):
                 className = evt.EventObject.Label
                 for listener in self.listeners:
                     listener.ToggleClass(className[3:], evt.Checked())
             
             checkBox.Bind(wx.EVT_CHECKBOX, OnTogglePhenotype)
             i+=1
Пример #12
0
    def SetClassPoints(self, classCoords):
        self.sizer4.DeleteWindows()
        vals = np.arange(float(len(classCoords))) / len(classCoords)
        if len(vals) > 0:
            vals += (1.0 - vals[-1]) / 2
            colors = [np.array(cm.jet(val)) * 255 for val in vals]
            colors_dict = {}
            i = 0
            for name in classCoords:
                colors_dict[name] = colors[i]
                i += 1
            self.sizer4.Add(wx.StaticText(self.Parent, -1, 'Classes:'))
            i = 1
            classCoords_ordered = [
                name for name in classCoords if name[:8] != 'training'
            ]
            classCoords_ordered.extend(
                [name for name in classCoords if name[:8] == 'training'])
            for name in classCoords_ordered:
                if i == len(classCoords) / 2 + 1:
                    self.sizer4.Add(wx.StaticText(self.Parent, -1,
                                                  'Training:'))
                checkBox = wx.CheckBox(self.Parent, wx.NewId(),
                                       '%d) %s' % (i, name))

                #checkBox.SetForegroundColour(color)   # Doesn't work on Mac. Works on Windows.
                checkBox.SetBackgroundColour(colors_dict[name])
                checkBox.SetValue(True)
                self.sizer4.Add(checkBox, flag=wx.EXPAND)

                def OnTogglePhenotype(evt):
                    className = evt.EventObject.Label
                    for listener in self.listeners:
                        listener.ToggleClass(className[3:], evt.Checked())

                checkBox.Bind(wx.EVT_CHECKBOX, OnTogglePhenotype)
                i += 1
Пример #13
0
def plot_evol(z_nums, masses, bins, avg=False, normalized=False):
    fig, ax = plt.subplots()
    color = iter(cm.jet(np.linspace(0, 1, len(masses))))

    if avg == True:
        for m in np.arange(len(masses)):
            ax.plot(
                z_nums[m],
                masses[m],
                color=next(color),
                label=("bin " + str(m + 1) + ": (" + "{:.2e}".format(bins[m]) +
                       " to " + "{:.2e}".format(bins[m + 1]) + ")"))
        ax.legend()
        if normalized == True:
            ax.set_title("Normalized averaged mass evolution of halos in " +
                         str(int(len(bins) - 1)) + " bins")
        elif normalized == False:
            ax.set_title("Averaged mass evolution of halos in " +
                         str(int(len(bins) - 1)) + " bins")

    elif avg == False:
        for m in np.arange(len(masses)):
            ax.plot(z_nums[m], masses[m], color=next(color))
        if extremum == 'max':
            ax.set_title("Mass evolution of " + str(n) + " most massive halos")
        elif extremum == 'min':
            ax.set_title("Mass evolution of " + str(n) +
                         " least massive halos")
        elif extremum == '':
            ax.set_title("Mass evolution of halos in range " +
                         my_range_str[0] + " to " + my_range_str[1])

    ax.set_yscale('log', nonpositive='clip')
    ax.set_xlabel('Redshift')
    ax.set_ylabel('Mass [M_sun/h]')
    plt.savefig('full_mass_evol_bins_z_norm.png')
    plt.show()
    def SetClassPoints(self, classCoords):
        self.sizer4.DeleteWindows()
        vals = np.arange(float(len(classCoords))) / len(classCoords)
        if len(vals) > 0:
            vals += (1.0 - vals[-1]) / 2
            colors = [np.array(cm.jet(val)) * 255 for val in vals]

            self.sizer4.Add(wx.StaticText(self.Parent, -1, 'Classes:'))
            i = 1
            for (name, keys), color in zip(classCoords.items(), colors):
                checkBox = wx.CheckBox(self.Parent, wx.NewId(),
                                       '%d) %s' % (i, name))
                checkBox.SetForegroundColour(
                    color)  # Doesn't work on Mac. Works on Windows.
                checkBox.SetValue(True)
                self.sizer4.Add(checkBox, flag=wx.EXPAND)

                def OnTogglePhenotype(evt):
                    className = evt.EventObject.Label
                    for listener in self.listeners:
                        listener.ToggleClass(className[3:], evt.Checked())

                checkBox.Bind(wx.EVT_CHECKBOX, OnTogglePhenotype)
                i += 1
Пример #15
0
from matplotlib.markers import MarkerStyle as mk
markers = mk.filled_markers
from matplotlib.pyplot import cm
import matplotlib.pyplot as plt
import glob as g
import numpy as np
from astropy.coordinates import SkyCoord as SC
from astropy import units as u
from astropy.io import ascii
cats = sorted(g.glob('Catalogues/v*dat'))
visits = np.array(cats).reshape((len(cats) / 4, 4))
color = cm.jet(np.linspace(0, 1, len(visits)))
markers = markers[:len(visits)]
for v, c in zip(visits, color):
    alpha, delta = np.loadtxt(v[0], usecols=(0, 1), unpack=True)
    plt.scatter(alpha, delta, color=c, s=2, label=str(v[0]).split('/')[1][:3])
    alpha, delta = np.loadtxt(v[2], usecols=(0, 1), unpack=True)
    plt.scatter(alpha, delta, color=c, s=2)
plt.scatter(194.8987875,
            27.9593889,
            marker='^',
            color='black',
            s=50,
            label='NGC4874')
plt.scatter(195.0337375,
            27.9770250,
            marker='v',
            color='black',
            s=50,
            label='NGC4889')
data = ascii.read('Catalogues/vandokkum15.csv',
                   thr=0.9,
                   colors='yellow',
                   vmax=0.75,
                   display_numbers=False,
                   cmap='gray')
a4 = plot_contours(A_gt.tocsc()[:, idx_components_gt[fn_gt_online]],
                   Cn,
                   thr=0.9,
                   vmax=0.85,
                   colors='r',
                   display_numbers=False,
                   cmap='gray')
# %% FIGURE 4 c and d
from matplotlib.pyplot import cm as cmap
pl.figure("Figure 4c and 4d")
color = cmap.jet(np.linspace(0, 1, 10))
i = 0
legs = []
all_ys = []
SNRs = np.arange(0, 10)
pl.subplot(1, 3, 1)

for k, fl_results in all_results.items():
    print(k)
    nm = k[:]
    nm = nm.replace('neurofinder', 'NF')
    nm = nm.replace('final_map', '')
    nm = nm.replace('.', '')
    nm = nm.replace('Data', '')
    idx_components_gt = fl_results['idx_components_gt']
    tp_gt = fl_results['tp_gt']
Пример #17
0
 def plot_grouped_by_mica(self,
                          train,
                          params,
                          i,
                          ylim=[0, 1],
                          force_ylim=True,
                          fs=24,
                          fs_tick=18):
     # if mica_library is not loaded, load it
     self.load_mica_library(train)
     # compute mica features
     mica_attributes = train.m.F_att(self.mica_library)
     mica_latents = train.m.F_lat(self.mica_library)
     self.mica_features = torch.cat([mica_latents, mica_attributes],
                                    dim=1).cpu().data.numpy()
     # generate samples and compute their features
     samples = torch.cat(
         [train.m.get_fake(64, params['z_dim']) for i in range(10)], dim=0)
     attributes = train.m.F_att(samples)
     latents = train.m.F_lat(samples)
     features = torch.cat([latents, attributes], dim=1).cpu().data.numpy()
     # compute cosine similarity
     similarity = cosine_similarity(features, self.mica_features)
     # matches = argmax cosine similarity
     matches = np.argmax(similarity, axis=1)
     # group spectra by matches
     groups = {}
     for idx, match in enumerate(matches):
         if match not in groups:
             groups[match] = set([(idx, similarity[idx][match])])
         else:
             groups[match].add((idx, similarity[idx][match]))
     # for each class in generated spectra:
     # plot spectra and save plot with filename as mica match
     samples = samples.cpu().data.numpy()
     # sim_min = np.cos(np.pi/4.)
     sim_min = max(np.cos(np.pi / 4.), np.min(np.max(similarity, axis=1)))
     sim_max = np.max(similarity)
     for endmember, sample_idxs in groups.items():
         n = 0
         avg_sim = 0.
         for idx, sim in list(sample_idxs):
             if sim >= sim_min:
                 # alpha = np.clip(0.5 * (sim + 1.), 0., 1.)
                 sim_norm = (sim - sim_min) / (sim_max - sim_min)
                 alpha = np.clip(sim_norm, 0., 1.)
                 plt.plot(self.waves,
                          samples[idx],
                          '--',
                          color=cm.jet(alpha))
                 avg_sim += sim
                 n += 1
         if n >= 1:
             avg_sim /= float(n)
             plt.plot(self.waves,
                      self.mica_library[endmember].cpu().data.numpy(), 'k-')
             plt.title(
                 '{:s}: avg_sim={:1.4f} global_min/max={:1.4f}/{:1.4f}'.
                 format(self.mica_names[endmember], avg_sim, sim_min,
                        sim_max),
                 fontsize=fs_tick - 6)
             plt.xlabel('Channels', fontsize=fs)
             plt.ylabel('Intensities', fontsize=fs)
             plt.tick_params(axis='both', which='major', labelsize=fs_tick)
             plt.grid(True, axis='x')
             if force_ylim:
                 plt.gca().set_ylim(ylim)
             filename = ''.join([
                 c for c in self.mica_names[endmember]
                 if c.isalpha() or c.isdigit()
             ]).rstrip()
             plt.savefig(params['saveto'] +
                         'mica/{}_{}.png'.format(i, filename))
             plt.close()
Пример #18
0
def plot_3D(*opts, fxn_name, animate_gif=True, f_name='v1'):
    def init():
        for line in lines:
            line.set_data([], [])
            line.set_3d_properties([])
        return lines

    def animate(i):
        num1 = int(x2[i])
        for lnum, (line, dot) in enumerate(zip(lines, dots)):
            if num1 < dp[lnum]:
                line.set_data(
                    xlist[lnum][:num1],
                    ylist[lnum][:num1])  # set data for each line separately.
                line.set_3d_properties(zlist[lnum][:num1])
                line.set_label(nn[lnum])  # set the label and draw the legend
                plt.legend(loc="upper center", ncol=4)
        return lines

    # Get data
    xlist, ylist, zlist, nn, dp = get_dlists(opts)
    n = len(opts)

    if fxn_name == 'rosenbrock':
        x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False, num=200))
        c = cm.jet(np.linspace(0, 1, n))
        g = 0.4
        rot_val = 245
        nr = colors.PowerNorm(gamma=g)
    elif fxn_name == 'saddle':
        rot_val = -60
        nr = None
        x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False, num=100))
        c = cm.rainbow(np.linspace(0, 1, n))
    else:
        x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False, num=200))
        c = cm.rainbow(np.linspace(0, 1, n))
        g = 0.25
        rot_val = 245
        nr = colors.PowerNorm(gamma=g)

    # Plot 3D Surface
    fig = plt.figure(figsize=(9.6, 6.4))
    ax = plt.axes(projection='3d', azim=rot_val)
    plt.tight_layout()

    data, minima, x_lims, y_lims = plot_fxn(fxn_name, '3D')

    ax.plot_surface(*data,
                    rstride=1,
                    cstride=1,
                    norm=nr,
                    cmap='viridis',
                    edgecolor='none',
                    alpha=1.0)
    ax.plot(*minima, 'x', markersize=12, mew=2, color='k')
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    # ax.set_xlim(x_lims)
    # ax.set_ylim(y_lims)
    #     c = new_cmap(np.linspace(0,1,n))
    #     c = cm.jet(np.linspace(0,1,n))

    if animate_gif == False:
        for k in range(n):
            x_history = np.array(xlist[k])
            y_history = np.array(ylist[k])
            path = np.concatenate(
                (np.expand_dims(x_history, 1), np.expand_dims(y_history, 1)),
                axis=1).T
            ax.quiver(path[0, :-1],
                      path[1, :-1],
                      beale_fxn(path[::, :-1][0], path[::, :-1][1]),
                      path[0, 1:] - path[0, :-1],
                      path[1, 1:] - path[1, :-1],
                      beale_fxn(path[::, :-1][0], path[::, :-1][1]) -
                      beale_fxn(path[::, :-1][0], path[::, :-1][1]),
                      color=c[k],
                      label=nn[k],
                      length=1,
                      normalize=False,
                      lw=5)
        plt.legend(loc="upper left")
    else:
        line, = ax.plot([], [], [], lw=2)
        #         dot, = ax.plot([], [], 'o', lw=2)
        lines = []
        dots = []
        for index in range(n):
            l_obj = ax.plot([], [], [], lw=2, color=c[index])[0]
            lines.append(l_obj)
            d_obj = ax.scatter([], [], [], marker='o', color=c[index])
            dots.append(d_obj)

        # print(x2)
        # blit=True --> only re-draw the parts that have changed.


#         dot = ax.scatter([],[],[]) # Set the dot at some arbitrary position initially
        anim = animation.FuncAnimation(fig,
                                       animate,
                                       init_func=init,
                                       frames=len(x2),
                                       interval=1,
                                       blit=True)
        anim.save('images/{}_3D_{}.gif'.format(fxn_name, f_name),
                  dpi=60,
                  writer="imagemagick")
    # ax.invert_yaxis()
    plt.show()
    def get_network_from_bursts(self, bursts_count_threshold=1, user_interaction_weight_threshold=1):
        """
        get bursts in activity for units of information, get network of connected users that parcipate in these bursts
        :param bursts_count_threshold: threshold for the number of bursts in activity for an information to be considered
        :param user_interaction_weight_threshold: threshold for the number of burts two users must participate in together in order for them to be connected
        """ 
        def get_burst_user_connections_df(content_id, content_df, burst_interval, userid_col='from_id', timestamp_col='date'):
            '''connect users who participate in the same burst'''
            burst_df = content_df[(content_df[self.timestamp_col].between(burst_interval[0], burst_interval[1], inclusive=True)) & (~content_df[self.userid_col].isna())].copy()
            uids = list(sorted(burst_df[self.userid_col].unique())) 
            if len(uids) < 2:
                return []            
            content_user_connections = []
            for i, uid1 in enumerate(uids):
                for uid2 in uids[i+1:]:
                    content_user_connections.append({'content': content_id,
                                    'uid1': uid1,
                                    'uid2': uid2,
                                    'weight': 1})
            return content_user_connections

        user_connections = []
        n_ids = self.dataset_df[self.content_col].nunique()
        max_plots_to_show = 5
        num_plots = 0
        for content_id, content_df in self.dataset_df.groupby(self.content_col):
            if num_plots < max_plots_to_show:
                show = True
            else:
                show = False
            if self.selected_content is not None and content_id not in self.selected_content:
                continue
            burstDetection = BurstDetection(dataset_df=content_df, metadata=self.metadata, id_col=self.id_col,
                                            timestamp_col=self.timestamp_col, platform_col=self.platform_col, 
                                            time_granularity=self.time_granularity,
                                            min_date=self.min_date, max_date=self.max_date)
            burst_intervals = burstDetection.detect_bursts(self.gammas[content_id])
            if len(burst_intervals) < bursts_count_threshold:
                continue

            if self.plot_bursts:
                plot_df = self.dataset_df.copy()
                plot_df.set_index(self.timestamp_col, inplace=True)
                new_df = plot_df.groupby(pd.Grouper(freq=self.time_granularity))[[self.content_col]].count()
                new_df.reset_index(inplace=True)
                plt.figure()
                plt.plot(new_df[self.timestamp_col], new_df[self.content_col])

            for burst_interval in burst_intervals:
                user_connections.extend(get_burst_user_connections_df(content_id, content_df, burst_interval))
                if self.plot_bursts:
                    plt.axvspan(xmin=burst_interval[0], xmax=burst_interval[1], color="red", alpha=0.25)
            if show and self.plot_bursts:
                plt.show()
            if self.plot_bursts and self.save_plots:
                plt.savefig(self.plot_dir + str(content_id) + "_persistent_groups_with_bursts.png", bbox_inches='tight')
                plt.close()
            num_plots += 1


        user_network_df = pd.DataFrame(user_connections)
        if 'uid1' not in user_network_df.columns:
            warnings.warn("No bursts detected in any information IDs. Persistent group measurements cannot be run. They will fail with uid1 KeyError.")
        user_network_df = user_network_df.groupby(['uid1', 'uid2'])['weight'].sum().reset_index()
        
        self.user_network_df = user_network_df[user_network_df['weight']>=user_interaction_weight_threshold]        
        
        edgelist = self.user_network_df[['uid1', 'uid2', 'weight']].apply(tuple, axis=1).tolist()
        if len(edgelist) == 0:
            return
        user_interaction_graph = ig.Graph.TupleList(edgelist, directed=False)
        self.groups = self.community_detection_algorithm(user_interaction_graph)
        print('Number of groups: ', len(self.groups))

        if self.plot:
            figsize = (10, 10)
            fig = plt.figure(figsize=figsize)
            ax = fig.add_subplot(1, 1, 1)
            ax.axis('off')
            ax.set_frame_on(False)
            colors = iter(cm.jet(np.linspace(0, 1, len(self.groups))))
            node_color = {}
            node_labels = {}
            for g_id, g in enumerate(self.groups):
                c = next(colors)
                for i in g:
                    node_color[i] = c
                    node_labels[i] = g_id
            # Draw graph of users by group membership
            node_c = [node_color[node['name']] for node in user_interaction_graph.vs]

            ig.plot(user_interaction_graph, layout=user_interaction_graph.layout_fruchterman_reingold(), vertex_size=30, edge_color='black', vertex_color=node_c)

            plt.show()
            if self.save_plots:
                plt.savefig(self.plot_dir+ "network_of_users_by_groups.png",bbox_inches='tight')
Пример #20
0
dec_min=np.min(data_cat["DELTA_J2000_1"][~np.isnan(data_cat["DELTA_J2000_1"])])
ra_slices=20
dec_slices=20
for i,ii in enumerate(np.linspace(ra_min,ra_max,ra_slices)):
    for j,jj in enumerate(np.linspace(dec_min,dec_max,dec_slices)):
        coords.append([ii,jj])
        


'''filter_names="ugrizJHK"
filters=[]
for f in filter_names:
    filters.append((g.glob("synth/*"+f+"*Mega*")+g.glob("synth/"+f+"wircam*"))[0])
'''
filters=sorted(g.glob("../../Coding/synth/F*W.fil.txt"))
filtercolor=cm.jet(np.linspace(0,1,len(filters)))
#print filters
wl=np.empty(0)
filts=[]
wls=[]
ax1=plt.subplot2grid((3,1),(0,0))
ax2=plt.subplot2grid((3,1),(1,0),sharex=ax1)
ax3=plt.subplot2grid((3,1),(2,0))
ax1.set_xlim([2900,17100])
ax1.set_ylim([0,0.6])
spec=0.5
for i,f in enumerate(filters):
    wlr,eff=np.loadtxt(f,unpack=True)
    wls.append(wlr)
    wl=np.concatenate((wl,wlr))
    filts.append(eff)
        ax2 = fig1.add_subplot(312)
        ax3 = fig1.add_subplot(313)

        plt.tight_layout(pad=3.0, w_pad=3.0, h_pad=3.0)
        fig1.subplots_adjust(left=0.15)
        #		fig1.subplots_adjust(bottom=0.25)
        #		fig1.subplots_adjust(top=0.90)
        #		fig1.subplots_adjust(right=0.95)

        for axis in ['top', 'bottom', 'left', 'right']:
            ax1.spines[axis].set_linewidth(1.)
            ax2.spines[axis].set_linewidth(1.)
            ax3.spines[axis].set_linewidth(1.)

        plt_title = ax1.set_title(' ')
        color = cycle(cm.jet(np.linspace(0, 1, 100)))

        ax1_hdl, = ax1.plot([], [])
        ax1_c_hdl, = ax1.plot([], [])
        ax2_hdl, = ax2.plot([], [])
        ax2_c_hdl, = ax2.plot([], [])
        ax3_hdl, = ax3.plot([], [])

        set_line_hdl = ax3.axvline(1.5, color='red')
        act_line_hdl = ax3.axvline(1.5, color='black')

        #		ax1.set_ylabel('Amplitude of TM modes (norm.)',**axis_font)
        ax1.set_ylabel('Power of TM modes (norm.)', **axis_font)
        ax1.set_xlabel('Time (ms)', **axis_font)
        ax2.set_ylabel('Power of TE modes (norm.)', **axis_font)
        #		ax2.set_ylabel('Amplitude of Fabry Perot (norm.)',**axis_font)
Пример #22
0
galq[6] = 4341
galq[7] = 4862
galq[8] = 5008
galq[9] = 6564

lab = [
    'OVI: 1034 $\AA$', 'Ly-alpha: 1215 $\AA$', 'NV: 1240 $\AA$',
    'CIV: 1549 $\AA$', 'CIII: 1908 $\AA$', 'MgII: 2799 $\AA$',
    'H-gama: 4341 $\AA$', 'H-beta: 4863 $\AA$', 'OIII: 5008 $\AA$',
    'H-alpha: 6564 $\AA$'
]

# Redshift
z = N.arange(0., 10.01, 0.01)

colores = list(cm.jet(N.linspace(0, 1, 10)))
colores = colores[::-1]

plt.figure(1, figsize=(11, 9), dpi=80, facecolor='w', edgecolor='k')
plt.clf()
for ii in range(10):
    plt.plot(galq[ii] * (1 + z), z, '-', alpha=0.5, lw=3., color=colores[ii])

for ii in range(7):
    x, y = U.get_data(root_to_filts + filters[ii], (0, 1))
    plt.plot(x, 8. * (y / y.max()), '-', lw=1, color='grey', alpha=0.5)
    plt.fill_betweenx(8. * (y / y.max()), x, 0, alpha=0.1)
    plt.xlabel('Wavelength [$\AA$]', size=25, labelpad=5)
    plt.ylabel('$z$', size=35)

for ii in range(10):
Пример #23
0
def plot_contour(*opts,
                 fxn_name,
                 animate_gif=True,
                 fig_size=None,
                 save_f=True,
                 f_name='v1',
                 in_type=None):
    def init():
        for line in lines:
            line.set_data([], [])
        return lines

    def animate(i):
        num1 = int(x2[i])
        for lnum, (line, scat) in enumerate(zip(lines, scats)):
            if num1 < dp[lnum]:
                #                 print(i, dp[lnum])
                line.set_data(
                    xlist[lnum][:num1],
                    ylist[lnum][:num1])  # set data for each line separately.
                scat.set_offsets([xlist[lnum][num1], ylist[lnum][num1]])
                line.set_label(nn[lnum])  # set the label and draw the legend
                plt.legend(loc="upper left")
        return lines

    if fig_size == 'small':
        fig, ax = plt.subplots(figsize=(6, 4))
    else:
        fig, ax = plt.subplots(figsize=(8.5, 6.8))
    plt.tight_layout()

    data, minima, x_lims, y_lims = plot_fxn(fxn_name, 'contour')

    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_xlim(x_lims)
    ax.set_ylim(y_lims)

    ax.contour(*data,
               levels=np.logspace(-.5, 5, 35),
               norm=LogNorm(),
               cmap='viridis',
               alpha=0.7)  #cmap=plt.cm.jet)
    ax.plot(*minima[0:2], 'x', markersize=12, mew=2, color='k')

    xlist, ylist, zlist, nn, dp = get_dlists(opts, in_type)
    n = len(xlist)
    # print(len(xlist))

    if fxn_name == 'rosenbrock':
        if in_type == 'sdict':
            c = cm.rainbow_r(np.linspace(0, 1, n))
        else:
            c = cm.jet(np.linspace(0, 1, n))
    else:
        c = cm.rainbow(np.linspace(0, 1, n))

    if animate_gif == False:
        for k in range(n):
            x_history = np.array(xlist[k])
            y_history = np.array(ylist[k])
            path = np.concatenate(
                (np.expand_dims(x_history, 1), np.expand_dims(y_history, 1)),
                axis=1).T
            ax.quiver(path[0, :-1],
                      path[1, :-1],
                      path[0, 1:] - path[0, :-1],
                      path[1, 1:] - path[1, :-1],
                      scale_units='xy',
                      angles='xy',
                      width=0.003,
                      scale=1,
                      color=c[k],
                      label=nn[k])
        plt.legend(loc="upper left")
        if save_f == True:
            plt.savefig('images/{}_path.png'.format(fxn_name))
    else:
        line, = ax.plot([], [], lw=2)  #, markersize=12)
        lines = []
        scats = []
        for index in range(n):
            l_obj = ax.plot([], [], lw=2, color=c[index])[0]
            lines.append(l_obj)
            s_obj = ax.scatter([], [], lw=2, color=c[index])
            scats.append(s_obj)
        num_min = int(len(xlist[0]) / 50)
        #         print(num_min)
        x2 = np.rint(np.linspace(0, len(xlist[1]), endpoint=False,
                                 num=200))  # fix this
        #         print(x2)
        #         x2 = np.arange(len(xlist[0]))
        # blit=True --> only re-draw the parts that have changed.
        scat = ax.scatter(
            [], [])  # Set the dot at some arbitrary position initially
        anim = animation.FuncAnimation(fig,
                                       animate,
                                       init_func=init,
                                       frames=len(x2),
                                       interval=1,
                                       blit=True)
        anim.save('images/{}_contour_{}.gif'.format(fxn_name, f_name),
                  dpi=60,
                  writer="imagemagick")

    plt.show()
Пример #24
0
#plot slices responsible for reconstruction
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm 

fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(16, 8))

plt.gray()
plt.tight_layout()

maxLines = len(lines)
#maxLines = 12
ax[0].imshow(powerSpect)
ax[1].imshow(powerSpect)
#color=iter(cm.rainbow(np.linspace(0,1,len(lines))))
color=iter(cm.jet(np.linspace(0,1,maxLines+1)))
fareyImage = np.zeros_like(powerSpect)
for i, line in enumerate(lines):
    u, v = line
    c=next(color)
    ax[0].plot(u, v, '.', c=c)
    ax[1].plot(u, v, '.r',markersize=1)
    fareyImage[u,v] = 255
    if i == maxLines:
        break
#ax[0].set_title('Sampling (colour per line) for prime size:'+str(p))
#ax[1].set_title('Sampling (same colour per line) for prime size:'+str(p))
ax[0].set_title('Sampling (colour per line) for dyadic size:'+str(M))
ax[1].set_title('Sampling (same colour per line) for dyadic size:'+str(M))
#ax[0].set_xlim([0,M])
#ax[0].set_ylim([0,M])
Пример #25
0
def vis_back_proj(ind=1,
                  img_style="edge",
                  pcd_style="intens",
                  hide_occlussion_by_marker=False,
                  save_without_show=False):
    imgfile = os.path.join(
        params['base_dir'],
        "img/" + str(ind).zfill(params["file_name_digits"]) + "." +
        params['image_format'])
    if img_style == "edge":
        gray = cv2.imread(imgfile)
        edges = cv2.Canny(gray, 50, 150, apertureSize=3)
        img = cv2.cvtColor(edges, cv2.COLOR_GRAY2BGR)
    elif img_style == "orig":
        img = cv2.imread(imgfile)
    else:
        raise Exception("Please input the right image style")

    csvfile = os.path.join(
        params['base_dir'],
        "pcd/" + str(ind).zfill(params["file_name_digits"]) + ".csv")

    csv = np.genfromtxt(csvfile, delimiter=",", skip_header=1)
    pcd = csv[:, :3]
    dis_arr = np.linalg.norm(pcd, axis=1)
    intens = csv[:, params['intensity_col_ind']]

    filels = os.listdir(params['base_dir'])
    cali_file_ls = []
    for file in filels:
        if file.find("cali_result.txt") > -1:
            cali_file_ls.append(file)
    if len(cali_file_ls) > 1:
        warnings.warn(
            "More than one calibration file exit! Load the latest file.",
            UserWarning)
        latest_cali = find_latest(cali_file_ls)
        r_t = np.genfromtxt(os.path.join(params['base_dir'], latest_cali),
                            delimiter=',')
        print("Load ", latest_cali,
              " as the extrinsic calibration parameters!")
    elif len(cali_file_ls) == 1:
        r_t = np.genfromtxt(os.path.join(params['base_dir'], cali_file_ls[0]),
                            delimiter=',')
        print("Load ", cali_file_ls[0],
              " as the extrinsic calibration parameters!")
    else:
        raise Exception("No calibration file is found!")

    if pcd_style == "intens":
        pcd_color = np.fliplr(
            (cm.jet(intens.astype(np.float32) / intens.max()) * 255).astype(
                np.int32)[:, :3])
    elif pcd_style == "dis":
        pcd_color = np.fliplr(
            (cm.jet(dis_arr / 42) * 255).astype(np.int32)[:, :3])
    else:
        print("Please input the right pcd color style")

    backproj_img = back_project_pcd(img, pcd, pcd_color, r_t, ind,
                                    hide_occlussion_by_marker)

    if max(backproj_img.shape[0], backproj_img.shape[1]) > 1000:
        resize_factor = 1000. / max(backproj_img.shape[0],
                                    backproj_img.shape[1])
        resized_img_for_view = cv2.resize(backproj_img, (0, 0),
                                          fx=resize_factor,
                                          fy=resize_factor)
    else:
        resized_img_for_view = backproj_img

    if save_without_show:
        window_name = "ind: " + str(
            ind) + " img_style: " + img_style + " pcd_style: " + pcd_style + (
                " hide_occlusion " if hide_occlussion_by_marker else "")
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        cv2.imshow(window_name, resized_img_for_view)
        k = cv2.waitKey(0)
        if k == 27:  # wait for ESC key to exit
            cv2.destroyAllWindows()
        elif k == ord('s'):  # wait for 's' key to save and exit
            save_file_name = os.path.join(
                params['base_dir'],
                str(ind).zfill(params["file_name_digits"])
            ) + "_" + img_style + "_" + pcd_style + (
                "_hide_occlusion" if hide_occlussion_by_marker else
                "") + "." + params['image_format']
            cv2.imwrite(save_file_name, img, [cv2.IMWRITE_JPEG_QUALITY, 70])
            print("The image is saved to ", save_file_name)
            cv2.destroyAllWindows()
    else:
        save_file_name = os.path.join(
            params['base_dir'],
            str(ind).zfill(params["file_name_digits"])
        ) + "_" + img_style + "_" + pcd_style + (
            "_hide_occlusion" if hide_occlussion_by_marker else
            "") + "." + params['image_format']
        cv2.imwrite(save_file_name, img, [cv2.IMWRITE_JPEG_QUALITY, 70])
        print("The image is saved to ", save_file_name)
        cv2.destroyAllWindows()
Пример #26
0
        tmp['log_C1_true'] = -5
        tmp['log_C2_true'] = -5
        tmp['r1_true'] = 100. * (.3)
        tmp['r2_true'] = 100. * (.3)
        tmp['log_alpha1_true'] = np.array(log_alpha)
        tmp['log_alpha2_true'] = np.array(log_alpha)
        tmp['log_gamma1_true'] = 0.
        tmp['log_gamma2_true'] = 0.
        T = T.append(tmp, ignore_index=True)
    except:
        print d

#Figure B, compare pso fitting
plt.figure(figsize=(3, 5))
ax = []
cols = cm.jet(np.linspace(0, 1, len(T['expt'].unique())))

fils = glob.glob('*/*/*.h5')
df = pd.DataFrame([])
x = {}
for tmp in T['expt'].unique():
    ky = tmp.split('_')[-1].split('x')[0]
    x[ky] = np.array([])
    x[ky + '_iter'] = np.array([])

for fil in fils:
    try:
        f = h5py.File(fil, 'r')
        if 'pso' in f.keys():
            ky = fil.split('_')[1].split('x')[0]
            x[ky] = np.concatenate(
def load_labelsLinesMarkers(experiments, varied_values, colormap=None):
    ''' Load labels, lines, color and markers for the (simulation, groups) combinations.     

    Returns
    -------
    line_style, line_color, marker_color, marker_style : dictionaries with keys [simlutation] and [groups]
    '''

    # Initiate the dictionaries
    line_label = initiate_nesteddict()
    marker_label = initiate_nesteddict()
    line_style = initiate_nesteddict()
    line_color = initiate_nesteddict()
    marker_color = initiate_nesteddict()
    marker_style = initiate_nesteddict()

    # Initiate colors, lines, markers to chose from
    if colormap == "rainbow":
        l_colors = cm.rainbow(np.linspace(0, 1, len(experiments) + 1))
    if colormap == "jet":
        l_colors = cm.jet(np.linspace(0, 1, len(experiments) + 1))
    if colormap == None:
        l_colors = [
            'navy', 'crimson', 'black', 'darkgreen', 'purple', 'magenta'
        ] * 5
    m_colors = cm.jet(np.linspace(0, 1, len(varied_values)))
    l_styles = [
        '-', '--', ':', '-.', 'densely dotted', 'densely dasged', 'densely'
    ] * 5
    m_styles = ['o', 'X', 'D', 'P', 's', 'x', 'd', 'p'] * 10

    # Find the common prefix of the experiments
    common_prefix = ''.join(c[0] for c in takewhile(
        lambda x: all(x[0] == y for y in x), zip(*experiments)))

    # If no specific case was chosen, given random colors
    for experiment in experiments:
        if common_prefix == experiments[0] or common_prefix == "":
            line_label[experiment] = str(experiment).replace(
                "nl_", "").replace("th_", "").replace("_",
                                                      " ")  #.split("_")[0]
        if "=" in common_prefix:
            line_label[experiment] = str(experiment)
        else:
            try:
                line_label[experiment] = str(experiment).replace("_", " ")
                # line_label[experiment] = str(experiment).split(common_prefix)[-1].replace("_", " ")#.split("_")[0]
            except:
                line_label[experiment] = str(experiment).replace("_", " ")
        marker_label[experiment] = str(experiment).replace("__", ": ").replace(
            "_", " ")
        line_color[experiment] = l_colors[experiments.index(experiment)]
        line_style[experiment] = l_styles[experiments.index(experiment)]
        marker_color[experiment] = l_colors[experiments.index(experiment)]
        marker_style[experiment] = m_styles[experiments.index(experiment)]

    for variation in varied_values:
        line_label[variation] = str(variation)
        marker_label[variation] = str(variation)
        line_color[variation] = m_colors[varied_values.index(variation)]
        line_style[variation] = '-'
        marker_color[variation] = m_colors[varied_values.index(variation)]
        marker_style[variation] = m_styles[varied_values.index(variation)]

    if experiments == varied_values and len(experiments) == 1:
        return line_label[varied_values[0]], marker_label[
            varied_values[0]], line_style[varied_values[0]], line_color[
                varied_values[0]], marker_style[
                    varied_values[0]], marker_color[varied_values[0]]
    return line_label, marker_label, line_style, line_color, marker_style, marker_color
Пример #28
0
for i in range(0, 3, 1):
    m, b = get_ls_line(plot_data[i][:, 0], plot_data[i][:, 2])
    ls_fit[i] = [b + m * x for x in plot_data[i][:, 0]]
    fits[i] = [m, b]

#%% Plotting Average

# Build Plot
plot.style.use('ggplot')
plot.title("Hall Effect at Different Magnetic Field Strengths (Cr)", color='k')
plot.xlabel("Charge Density($J_x$) [$A/m^2$]")
plot.ylabel("Electric Field Strength($E_y$) [J]")

# Plot data
for i in range(0, 3, 1):
    colors = cm.jet((0.85, 0.25, 0.45))
    plot.errorbar(plot_data[i][:, 0],
                  plot_data[i][:, 2],
                  yerr=plot_data[i][:, 3],
                  xerr=plot_data[i][:, 1],
                  fmt='o',
                  color=colors[i])
    plot.plot(plot_data[i][:, 0], ls_fit[i], color=colors[i])

plot.legend(['Field Strength: {}G'.format(x) for x in trial_field_strengths])

# Display
fig = plot.gcf()
plot.figure()

#%% Save Figure
Пример #29
0
support_types = np.unique(support)

'''
Based on support
'''
category = support.copy()
types = support_types.copy()

legend_labels = [r'$\rm CeO_{2}(100)$', r'$\rm CeO_{2}(111)$', 'Graphene', 'MgO(100)', '2H-'+r'$\rm MoS_{2}(0001)$', r'$\rm SrTiO_{3}(100)$',
         'Steps of ' + r'$\rm CeO_{2}$', r'$\rm TiO_{2}(110)$', 'ZnO(100)']
term_index = np.where(np.array(x_features_poly_combined) ==  'Ec_-1Ebind_2')[0][0]
x_plot =  X_before_scaling[:,term_index]
y_plot = y.copy()
sns.set_style("ticks")
fig, ax = plt.subplots(figsize=(6, 6))
color_set = cm.jet(np.linspace(0,1,len(types)))
for type_i, ci, label_i in zip(types, color_set, legend_labels):
    indices = np.where(np.array(category) == type_i)[0]
    ax.scatter(x_plot[indices],
                y_plot[indices],
                label=label_i,
                facecolor = ci, 
                alpha = 0.8,
                s  = 100)
ax.plot([x_plot.min(), x_plot.max()], [DSL.predict(X_DSL).min(), DSL.predict(X_DSL).max()], 'k--',  lw=2)
ax.set_xlabel(r'$\rm E_{bind}^2/E_c$ ' + '(eV)')
ax.set_ylabel(r'$\rm E_a$' +'(eV)')

plt.text(1.6,0, r'$\rm E_a$ = ' + str(np.around(u1, decimals = 3)) + r'$\rm E_{bind}^2/E_c$ ' + str(np.around(u0, decimals = 3)))
plt.text(4,0.4, r'$\rm R^2$ = ' + str(np.around(DSL_r2, decimals = 3)) )
Пример #30
0
           ['PC%i' % (w + 1) for w in range(nDescriptors)],
           rotation=60)
plt.legend(loc='right')
plt.tight_layout()

#%% Plot the normalized desciptor loading
'''
Need to be completed
'''
ind = 0
yvals = []
ylabels = []
bar_vals = []
space = 0.2

cm_cur = cm.jet(np.linspace(0, 1, nDescriptors))
fig = plt.figure(figsize=(6, 6))

ax = fig.add_subplot(111)
n = len(descriptors)
width = (1 - space) / (len(descriptors))
indeces = np.arange(0, pc_reg) + 0.5

PC_loadings = []
# Create a set of bars at each position
for i, pci in enumerate(eig_vecs[:pc_reg]):

    vals = pci / np.sum(np.absolute(pci))
    PC_loadings.append(vals)
    pos = width * np.arange(n) + i
    ax.bar(pos, vals, width=width, label=str(i + 1), color=cm_cur, alpha=1)
plotDir3 = '../plots/gws/Ka2017_TrPi2018_FixZPT0/F606W_F160W_K/0_10/GRB160821B/1.00/'
pcklFile = os.path.join(plotDir3,"data.pkl")
f = open(pcklFile, 'r')
(data_out, data3, tmag3, lbol3, mag3, t0_best3, zp_best3, n_params3, labels3, best3, truths3) = pickle.load(f)
f.close()

tmag1 = tmag1 + t0_best1
tmag2 = tmag2 + t0_best2
tmag3 = tmag3 + t0_best3

title_fontsize = 30
label_fontsize = 30

#filts = ["u","g","r","i","z","y","J","H","K"]
filts = ["F606W","F160W","K"]
colors=cm.jet(np.linspace(0,1,len(filts)))
tini, tmax, dt = 0.0, 21.0, 0.1    
tt = np.arange(tini,tmax,dt)

color1 = 'coral'
color2 = 'cornflowerblue'
color3 = 'palegreen'

plotName = "%s/models_panels.pdf"%(plotDir)
#plt.figure(figsize=(20,18))
plt.figure(figsize=(20,24))

tini, tmax, dt = 0.0, 10.0, 0.1
tt = np.arange(tini,tmax,dt)

cnt = 0
Пример #32
0
import imageio
from diffusion_model import grid
import matplotlib.pyplot as plt
from matplotlib.pyplot import cm
import numpy as np
gr = grid(200, 200)
gr.initiate_atoms_in_line(quantitiy=5000)

images = []
for i in range(800):
    gr.simulate_move()
    images.append(np.uint8(cm.jet(gr.grid) * 255))
imageio.mimsave('diffusion.gif', images, duration=0.1)
Пример #33
0
def createFractal4(reduction, N, proportion):
    #parameters
    M = 2*N
    twoQuads = True
    angles, lengths = mojette.angleSet_Symmetric(N,N,1,True,50)
    perpAngle = farey.farey(1,0)
    angles.append(perpAngle)
    powerSpect = np.zeros((M,M))

    #compute lines
    centered = True
    mLines = []
    sLines = []
    mValues = []
    sValues = []
    pValues = []
    qValues = []
    for angle in angles:
        m, s, p, q, inv = farey.toFinite(angle, M)
        pValues.append(p)
        qValues.append(q)
        if m not in mValues and m < M:
            u, v = radon.getSliceCoordinates2(m, powerSpect, centered, M)
            mLines.append((u,v))
            mValues.append(m)
        
        #second quadrant
        if twoQuads:
            if m != 0 and m != M: #dont repeat these
                m = M-m
                if m not in mValues and m < M:
                    u, v = radon.getSliceCoordinates2(m, powerSpect, centered, M)
                    mLines.append((u,v))
                    mValues.append(m)
                    i = (len(mValues)+len(sValues))/float(M)
                    if i >= 1:
                        break

    ss = []
    ss.append(M)
    ss.extend(range(0, N/2))

    maxLines = len(ss)
    for i,s in enumerate(ss):
        u, v = radon.getSliceCoordinates2(s, powerSpect, centered, M)
        sLines.append((u,v))
        sValues.append(s)
        i = (len(mValues)+len(sValues))/float(M)
        if i >= 1.5:
            break

    length = 0

    fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(16, 8))

    plt.gray()
    plt.tight_layout()

    maxLines = len(sLines+mLines)
    i = 0
    ax[0].imshow(powerSpect)
    ax[1].imshow(powerSpect)
    color=iter(cm.jet(np.linspace(0,1,maxLines+1)))
    fareyImage = np.zeros_like(powerSpect)
    fareyImage1 = np.zeros_like(powerSpect)
    for i, sLine in enumerate(sLines):
        u, v = sLine
        ax[1].plot(u, v, '.w',markersize=1)
        fareyImage[u,v] = 1
        length = length + 1
        i = np.count_nonzero(fareyImage)/float((M*M))
        if i >= reduction*proportion:
            break

    maxLines = len(mLines)
    for i, mLine in enumerate(mLines):
        u, v = mLine
        ax[0].plot(u, v, '.r', markersize=1)
        ax[1].plot(u, v, '.r',markersize=1)
        fareyImage[u,v] = 1
        fareyImage1[u,v] = 1
        length = length + 1
        i = np.count_nonzero(fareyImage)/float((M*M))
        if i >= reduction:
            break

    print("Proportion of M:", (length/float(M)))

    print("Non-zero elements with holes: ", np.count_nonzero(fareyImage1)/float((M*M)) * 100)
    print("Non-zero elements without holes: ", np.count_nonzero(fareyImage)/float((M*M)) * 100)

    print("Absolute difference percentage extra filled in is ", (np.count_nonzero(fareyImage)- np.count_nonzero(fareyImage1))/float((M*M)) *100)

    withHoles = np.count_nonzero(fareyImage1)/float((M*M)) * 100
    withoutHoles = np.count_nonzero(fareyImage)/float((M*M)) * 100

    percentage = (withoutHoles - withHoles)/float(withHoles) * 100

    print("Percentage difference percentage extra filled in is ", percentage)
            
    ax[0].set_title('Sampling (colour per line) for dyadic size:'+str(M))
    ax[1].set_title('Sampling (same colour per line) for dyadic size:'+str(M))
    imageio.imsave("farey_image_"+str(M)+"_"+".png", fareyImage)
    plt.show()

    lines = mLines + sLines

    return fareyImage, lines
Пример #34
0
plt.legend(lab, loc='upper right', fontsize=21, frameon=False)
# plt.xlim(3000,14500)
plt.xlim(3000, 10500)
plt.ylim(0.001, 0.999)
plt.xticks(fontsize=22)
plt.yticks(fontsize=22)

#### Separated in two windows
ruta = '/Users/albertomolino/codigos/bpz-1.99.2/FILTER/SPLUS_July2017/'
filtros = U.get_str(ruta + 'SPLUS.list', 0)

bbs = [0, 5, 7, 9, 11]
nbs = [1, 2, 3, 4, 6, 8, 10]

splus_colors = list(cm.jet(N.linspace(0, 1, 12)))

colores_BB = N.zeros((3, 5), float)
colores_NB = N.zeros((3, 7), float)
colores_BB[:, 0] = (0.00, 0.00, 1.00)
colores_BB[:, 1] = (0.00, 0.50, 0.00)
colores_BB[:, 2] = (0.85, 0.65, 0.00)
colores_BB[:, 3] = (1.00, 0.00, 0.00)
colores_BB[:, 4] = (0.35, 0.00, 0.00)

colores_NB[:, 0] = (0.00, 0.25, 1.00)
colores_NB[:, 1] = (0.00, 0.65, 1.00)
colores_NB[:, 2] = (0.00, 0.50, 0.00)
colores_NB[:, 3] = (0.85, 0.65, 0.00)
colores_NB[:, 4] = (0.80, 0.25, 0.00)
colores_NB[:, 5] = (0.85, 0.00, 0.00)