Пример #1
0
def main():
    
    dataFolder = '/Users/deepak/Dropbox/GravityMachine/GravityMachineManuscript/EnsembleTrackStatistics'
    
    subFolder = 'Starfish_Blinks'
    
    saveFolder = dataFolder
    
    Files = os.listdir(os.path.join(dataFolder, subFolder))
    
#    Files = {0:'Dendraster1_Blink_Statistics.pkl',1:'Dendraster2_Blink_Statistics.pkl',2:'Dendraster3_Blink_Statistics.pkl'}

    
#    Files = {0:'Dendraster1_Blink_Statistics.pkl',1:'Dendraster2_Blink_Statistics.pkl',2:'Dendraster3_Blink_Statistics.pkl'}
    
#    Time = []
#    peak_indicator = []
#    peak_indicator_neg = []
#    TimeBetweenBlinks_array = []
#    BlinkDurations_array = []
    
    TimeBetweenBlinks_array = np.array([])
    BlinkDurations_array = np.array([])
    
    color1 = cm.inferno(64)
    color2 = cm.inferno(128)
    
    for fileNames in Files:
        
        print('Analyzing ... {}'.format(fileNames))
        with open(os.path.join(dataFolder,subFolder,fileNames),'rb') as f:
            
            Time, peak_indicator, peak_indicator_neg, TimeBetweenBlinks, BlinkDurations = pickle.load(f)
Пример #2
0
def plotModified(reference, histo, color=1):

    # plot original histogram (reference) with ones resampled from it (histo),
    # histo is either an array of histograms or a single histogram.
    # reference is a dataframe element.
    if color == 1:
        colors = [cm.viridis(i) for i in np.linspace(0, 1, len(histo))]
    elif color == 2:
        colors = [cm.plasma(i) for i in np.linspace(0, 1, len(histo))]
    else:
        colors = [cm.inferno(i) for i in np.linspace(0, 1, len(histo))]
    name = reference['hname']
    vmin = reference['Xmin']
    vmax = reference['Xmax']

    # create an array with x values, from x_min to x_max and length as input histogram
    x = vmin + (np.arange(len(histo[0]))) * float(
        (vmax - vmin) / float(len(histo[0])))
    x = x[1:-1]

    for i in range(len(histo)):
        plt.xlim(vmin, vmax)

        histo_todraw = histo[i][1:-1]

        #srun=df_plot.index.get_level_values('fromrun')[num]
        #slumi=df_plot.index.get_level_values('fromlumi')[num]

        plt.step(x,
                 histo_todraw,
                 where='mid',
                 label=(name + " LS " + str(reference['fromlumi']) + " Run " +
                        str(reference['fromrun'])),
                 color=colors[i])
Пример #3
0
def plot_cube(ax, cube, angle=50):
    cube = plot_normalize(cube)

    facecolors = cm.inferno(cube)
    facecolors[:, :, :, -1] = cube  # alpha channel = voxel value
    facecolors = explode(facecolors)

    filled = abs(facecolors[:, :, :, -1]) >= 0.5
    #filled = facecolors[:,:,:,-1] != 0
    z, y, x = expand_coordinates(np.indices(np.array(filled.shape) + 1))

    ax.view_init(50, angle)
    ax.set_xlim(right=IMG_DIM * 2)
    ax.set_ylim(top=IMG_DIM * 2)
    ax.set_zlim(top=IMG_DIM * 2)

    ax.set_xlabel('$X$')  #, fontsize=20)
    ax.set_ylabel('$Y$')
    #ax.yaxis._axinfo['label']['space_factor'] = 3.0
    # set z ticks and labels
    #ax.set_zticks([-2, 0, 2])
    # change fontsize
    #for t in ax.zaxis.get_major_ticks(): t.label.set_fontsize(10)
    # disable auto rotation
    ax.zaxis.set_rotate_label(False)
    ax.set_zlabel('$\lambda$', rotation=0)  #, fontsize=30)

    im = ax.voxels(x, y, z, filled, facecolors=facecolors)
Пример #4
0
def main_synth():
    n = 1536
    n = 2000
    pts = np.stack(
        np.meshgrid(np.linspace(-1, 1, n), np.linspace(-1, 1, n), [-1]),
        -1).reshape(-1, 3)

    pts = pts.astype(np.float32)
    pts[..., 2] = np.random.randn(n * n) * .0001 - .9

    pts[(pts[:, 1] + pts[:, 0] > -.5) & (pts[:, 1] + pts[:, 0] < .5) &
        (pts[:, 1] - 2 * pts[:, 0] > -.5) & (2 * pts[:, 1] - pts[:, 0] < .5),
        2] = -.6
    pts[(pts[:, 1] + pts[:, 0] > -.3) & (pts[:, 1] + pts[:, 0] < .3) &
        (pts[:, 1] - pts[:, 0] > -.3) & (pts[:, 1] - pts[:, 0] < .3), 2] = -.4
    print('PTS\n', pts)

    lo = pts[:, 2].min()
    hi = pts[:, 2].max()
    print(lo, hi)
    colors = inferno(1e-1 + (pts[:, 2] - lo) / (1e-6 + hi - lo))[..., :3]

    app = PointRenderer(1024, 1024)
    app.init(True)
    app.setPts(pts, colors, None)
    while not app.q_pressed:
        app.startFrame()
        app.render()
        app.endFrame()
        #if app.endFrame(): break
    app.q_pressed = False
Пример #5
0
def get_depth(model, img):
    model.switch_to_eval()

    input_height = 384
    input_height = 512
    input_width = 512
    img = cv2.resize(img, (input_width, input_height))
    input_img = torch.from_numpy(np.transpose(
        img, (2, 0, 1))).contiguous().float() / 255.
    input_img = input_img.unsqueeze(0)

    input_images = Variable(input_img.cuda())
    pred_log_depth = model.netG.forward(input_images)
    pred_log_depth = torch.squeeze(pred_log_depth)

    pred_depth = torch.exp(pred_log_depth)

    # visualize prediction using inverse depth, so that we don't need sky segmentation (if you want to use RGB map for visualization, \
    # you have to run semantic segmentation to mask the sky first since the depth of sky is random from CNN)
    pred_inv_depth = 1 / pred_depth
    pred_inv_depth = pred_inv_depth.data.cpu().numpy()
    # you might also use percentile for better visualization
    pred_inv_depth = pred_inv_depth / np.amax(pred_inv_depth)

    from matplotlib.cm import inferno
    colored = (inferno(pred_inv_depth) * 255)[..., 0:3].astype(np.uint8)

    #io.imsave('demo.png', colored)
    # print(pred_inv_depth.shape)
    cv2.imshow('depth', cv2.cvtColor(colored, cv2.COLOR_BGR2RGB))
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return img, pred_depth.detach().cpu().numpy()
Пример #6
0
	def plot_ei_regime(ax,data,JEI,JII,filename,fig,zoom_in,zoom_lims,scales):
		JII_b = np.array(data["points_fr_gpe"])*0.725*40*10
		JEI_b = np.array(data["points_fr_stn"])*1.2*23*5
		

		ax1 = ax.twinx().twiny()
		start_markers=[]
		end_markers=[]
		lines=[]
		line_colors=[]
		for k,(x_row,y_row) in enumerate(zip(JEI_b,JII_b)):
			arr_col = cm.inferno(float(k)/len(JEI_b))
			line_colors.append(arr_col)
			for l,(x_col,y_col) in enumerate(zip(x_row,y_row)):
				if l < len(x_row)-1: 
					lines.append(ax1.arrow(x_col,y_col,x_row[l+1]-x_col,y_row[l+1]-y_col,head_width=50,length_includes_head=True,fc = arr_col, ec = arr_col,linestyle='-',linewidth=1.0,alpha=0.8))
			if k%2 == 0:
				end_markers.append(ax1.plot(x_col,y_col,marker='o',markersize=12,color=arr_col,label='gpe ratio:'+str(gpe_rat[k]),alpha=0.8))
			else:
				end_markers.append(ax1.plot(x_col,y_col,marker='o',markersize=12,color=arr_col,alpha=0.8))
			start_markers.append(ax1.plot(x_row[0],y_row[0],marker='*',markersize=12,color=arr_col,alpha = 0.8))
		handles, labels = ax1.get_legend_handles_labels()
		fig.legend(handles,labels,loc='upper center', bbox_to_anchor=(0.8, 1.005), ncol=2, fancybox=True,prop={'size':18,'weight':'bold'})
		ax1.set_xlim(ax.get_xlim())
		ax1.set_ylim(ax.get_ylim())
		ax1.set_xticklabels([])
		ax1.set_yticklabels([])
Пример #7
0
def normalize_and_show(arr):
    dimg = (inferno((arr - arr.min()) / (arr.max() - arr.min())) *
            255)[..., 0:3].astype(np.uint8)
    dimg = cv2.cvtColor(dimg, cv2.COLOR_RGB2BGR)
    cv2.imshow('dimg', dimg)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
Пример #8
0
def visualise_voxels(vox_cubes: np.ndarray,
                     inv=True,
                     figsize=(5, 5),
                     det_coords=None):
    """
    Plot a 3D visualization of the voxels. Intensities are from Inferno colormap. Transparency is equal to value in the voxel.
    Inverted image is (1-original). If detector coordinates are provided, they are added as a scatter plot.

    :param vox_cubes: 3d array of voxels
    :param inv: bool whether to invert filled-empty
    :param figsize: matplotlib figure size
    :param det_coords: 2d array (n_det, 3) of detector coordinates
    :return: (interactive) 3d graph
    """
    facecolors = cm.inferno(inv + ((-1)**inv) * vox_cubes)
    facecolors[..., -1] = inv + ((-1)**inv) * vox_cubes
    filled = np.ones(vox_cubes.shape)
    filled_2 = explode(filled)
    fcolors_2 = explode(facecolors)
    fig = plt.figure(figsize=figsize)
    ax = fig.gca(projection='3d')
    ax.voxels(*shrink(filled_2), filled_2, facecolors=fcolors_2)
    if det_coords is not None:
        ax.scatter(det_coords[:, 0],
                   det_coords[:, 1],
                   zs=np.min(det_coords[:, 2]),
                   zdir='z',
                   linewidth=3)
    plt.show(block=False)
    def save_images(self):
        """
        Save the extracted images
        :return:
        """
        rgb_np = self.get_rgb_np()
        thermal_np = self.extract_thermal_image()

        img_visual = Image.fromarray(rgb_np)
        thermal_normalized = (thermal_np - np.amin(thermal_np)) / (
            np.amax(thermal_np) - np.amin(thermal_np))
        img_thermal = Image.fromarray(
            np.uint8(cm.inferno(thermal_normalized) * 255))

        fn_prefix, _ = os.path.splitext(self.flir_img_filename)
        thermal_filename = fn_prefix + self.thermal_suffix
        image_filename = fn_prefix + self.image_suffix
        if self.use_thumbnail:
            image_filename = fn_prefix + self.thumbnail_suffix

        if self.is_debug:
            print("DEBUG Saving RGB image to:{}".format(image_filename))
            print("DEBUG Saving Thermal image to:{}".format(thermal_filename))

        img_visual.save(image_filename)
        img_thermal.save(thermal_filename)
Пример #10
0
    def save_images(self, options):
        """
        Save the extracted images
        :return:
        """
        options = options.split('|')

        rgb_np = self.rgb_image_np
        thermal_np = self.thermal_image_np

        img_visual = Image.fromarray(rgb_np)
        thermal_normalized = (thermal_np - np.amin(thermal_np)) / (np.amax(thermal_np) - np.amin(thermal_np))
        img_thermal = Image.fromarray(np.uint8(cm.inferno(thermal_normalized) * 255))
        img_gray = Image.fromarray(np.uint8(cm.binary(thermal_normalized) * 255))

        fn_prefix, _ = os.path.splitext(self.flir_img_filename)
        thermal_filename = fn_prefix + self.thermal_suffix
        image_filename = fn_prefix + self.image_suffix
        grayscale_filename = fn_prefix + self.grayscale_suffix

        if self.use_thumbnail:
            image_filename = fn_prefix + self.thumbnail_suffix

        if self.is_debug:
            print("DEBUG Saving RGB image to:{}".format(image_filename))
            print("DEBUG Saving Thermal image to:{}".format(thermal_filename))
            print("DEBUG Saving Gray image to:{}".format(grayscale_filename))
        if 'rgb' in options:
            img_visual.save(image_filename)
        if 'thermal' in options:
            img_thermal.save(thermal_filename)
        if 'gray' in options:
            img_gray.save(grayscale_filename)
def lineplot_files(fnames, xlabels,  yaxis):

    color = cm.inferno(np.linspace(0.1, 0.4, len(fnames)))

    nfiles = len(fnames)

    data_means = []
    data_stds  = []
    data_pos   = np.arange(nfiles)

    for i in range(0,nfiles):
        temp_data = np.loadtxt("data/context-switches/" + fnames[i])
        temp_mean = st.hmean(temp_data)
        temp_std  = np.std(temp_data) 

        data_means.append(temp_mean)
        data_stds.append(temp_std)

    ax, fig = plt.subplots(1, figsize=(3.5,6))
    ax = plt.bar(data_pos, data_means, yerr=data_stds, align='center',capsize=10, width=0.2, color=color)

    plt.xticks(data_pos, xlabels, rotation=30)
    plt.ylabel(yaxis)

    # Save figure
    plt.tight_layout()
    plt.savefig("context_switches.pdf")
Пример #12
0
def audio_to_spectrum(audio_batch):

  def convert_(audio):
    spectrogram = librosa.feature.melspectrogram(
        audio[:16384], sr=16000, n_mels=64, n_fft=512, hop_length=256)
    log_amp = librosa.core.amplitude_to_db(spectrogram)[::-1, :]
    return log_amp

  audio_batch = audio_batch[:100]

  specturm_batch = [convert_(audio) for audio in audio_batch]
  specturm_batch = np.array(specturm_batch)
  specturm_batch = np.clip(specturm_batch, -100.0, 0.0) / 100.0 + 1.0
  for index_b in range(specturm_batch.shape[0]):
    min_v_ = specturm_batch[index_b].min()
    max_v_ = specturm_batch[index_b].max()
    specturm_batch[
        index_b] = (specturm_batch[index_b] - min_v_) / (max_v_ - min_v_)
  # [0., 1.0], means -100 to 0 e.g. 100db to 0db

  # http://thomas-cokelaer.info/blog/2014/09/about-matplotlib-colormap-and-how-to-get-rgb-values-of-the-map/

  img = np.zeros(list(specturm_batch.shape) + [3])
  for index_b in range(specturm_batch.shape[0]):
    for index_x in range(specturm_batch.shape[1]):
      for index_y in range(specturm_batch.shape[2]):
        v = int(specturm_batch[index_b][index_x][index_y] * 255)
        r, g, b, _ = cm.inferno(v)
        img[index_b][index_x][index_y] = [r, g, b]

  # specturm_batch = np.clip(specturm_batch, -100.0, 0.0) / 100.0 + 1.0
  # [0., 1.0], means -100 to 0 e.g. 100db to 0db
  # img = np.stack((specturm_batch,) * 3, -1)  # grey -> rgb
  return img
    def make_color_lookup(self):
        self.color_lookup = np.zeros(shape=(256, 4))

        for aa in range(256):
            r, g, b, _ = cm.inferno(aa)
            alpha = (aa / 256)

            self.color_lookup[aa, :] = [r, g, b, alpha]
Пример #14
0
def topOverall(topk=30):
    df = pd.read_csv(FIFA_DIR, encoding="utf-8")[['Name', 'Overall']]
    df.sort_values(by='Overall')
    df = df.head(topk)
    colors = [cm.inferno(x) for x in np.linspace(0, 1, topk)]
    plt.bar(df['Name'], df['Overall'] - 80, bottom=80, color=colors)
    plt.xticks(rotation=90)
    plt.title('Top {} Overall'.format(topk))
    plt.show()
Пример #15
0
def plot_set(data_wide,
             idx_calibration,
             idx_change_1,
             idx_change_0,
             datapath,
             y_var="$\Delta T$",
             title=""):
    fig, (ax) = plt.subplots(1, 1, gridspec_kw={'height_ratios': [3]})
    plt.subplots_adjust(left=.15,
                        bottom=.333,
                        right=.85,
                        top=.95,
                        wspace=0,
                        hspace=0)

    capture_start = .75
    capture_range = .2
    idx_look = np.argwhere(idx_calibration == 1).ravel()
    colors = cm.inferno(np.linspace(0, 1, idx_look.size + 2))
    data_a = data_wide[0:0]  # empty array to hold the data
    for ii, i in enumerate(idx_look):
        data_s = data_wide.iloc[idx_change_0[i]:idx_change_1[i]]

        idx_range = idx_change_1[i] - idx_change_0[i]
        idx_a, idx_b = int(capture_start *
                           idx_range), int(capture_start * idx_range +
                                           capture_range * idx_range)
        # local_dataframe= data_s.iloc[idx_a:idx_b].agg(['mean'])
        local_dataframe = data_s.iloc[idx_a:idx_b].mean(numeric_only=None)
        data_a = data_a.append(local_dataframe, ignore_index=True)
        label = "%1.0i:  Temp: %3.1f, Mass Flow: %3.2f" % (
            i, local_dataframe["T Preheat Setpoint"],
            local_dataframe["Mass Flow Rate (kg/hr)"])
        ax.plot(data_s["Time (hr)"] - data_s["Time (hr)"].iloc[0],
                data_s[y_var],
                label=label,
                c=colors[ii])

        ax.axhline(y=local_dataframe[y_var],
                   linestyle="-.",
                   lw=1,
                   c=colors[ii],
                   label='_nolegend_')
    ax.set_ylabel(y_var)  # we already handled the x-label with ax1
    ax.set_xlabel('Time (hr)')  # we already handled the x-label with ax1
    ax.set_title(title)  # we already handled the x-label with ax1
    # ax.xaxis.tick_top()
    # ax.xaxis.set_label_position("top")
    # ax.set_xlim([0,np.max(data_s["Time (hr)"])])

    fig.legend(loc='lower center',
               borderaxespad=0.2,
               fontsize=8,
               frameon=False)
    fig.savefig(pjoin(datapath, '0_' + title.replace(' ', '') + '.png'))

    return fig, data_a
Пример #16
0
 def make_intensity_lookup(self):
     rospy.loginfo("make_intensity_lookup")
     self.intensity_lookup = [0 for _ in range(256)]
     for aa in range(256):
         r, g, b, _ = cm.inferno(aa)
         rr = int(255 * r)
         gg = int(255 * g)
         bb = int(255 * b)
         rgba = struct.unpack('I', struct.pack('BBBB', bb, gg, rr, aa))[0]
         self.intensity_lookup[aa] = rgba
Пример #17
0
def cat_spatiale_trajets(prob_dist, prob_duree, data, li_spat):
    df = data.copy()
    df['V2_DUREE'] = pd.to_timedelta(
        df['V2_DUREE'], unit='Min').dt.round('1Min').dt.total_seconds() // 60
    df = df[(df['V2_DUREE'] < 200) & (np.floor(df['V2_MMOTIFDES']) == 9) &
            (df['V2_MORICOM_MDESCOM_indicUU'] == 1)].copy()
    colors = cm.winter(np.linspace(0, 1, len(li_spat)))
    colors_outli = cm.inferno(np.linspace(0, 1, len(li_spat)))
    li_co = {}
    for i in range(len(li_spat)):
        #        sprint(li_spat[i])
        if df[df['SPATIAL'] == i]['V2_DUREE'].count() != 0:
            df_filt = df[df['SPATIAL'] == i].copy()
            te = sm.OLS(df_filt['V2_MDISTTOT'].values,
                        df_filt['V2_DUREE'].values.reshape(-1, 1))
            res = te.fit()
            influ = res.get_influence()
            (cook, p) = influ.cooks_distance
            df_filt['COOK'] = cook
            cook_outlier = [(df_filt['V2_DUREE'].values[o],
                             df_filt['V2_MDISTTOT'].values[o])
                            for o, t in enumerate(cook) if t > 4 / len(cook)]
            print(cook_outlier)
            plt.scatter(
                df_filt[df_filt['COOK'] <= 8 / len(cook)]['V2_DUREE'],
                df_filt[df_filt['COOK'] <= 8 / len(cook)]['V2_MDISTTOT'],
                color=colors[i])
            plt.plot(df_filt['V2_DUREE'],
                     res.predict(df_filt['V2_DUREE'].values))
            plt.scatter(
                df_filt[df_filt['COOK'] > 8 / len(cook)]['V2_DUREE'],
                df_filt[df_filt['COOK'] > 8 / len(cook)]['V2_MDISTTOT'],
                color=colors_outli[i])
            modele_sans_outlier = sm.OLS(
                df_filt[df_filt['COOK'] <= 4 /
                        len(cook)]['V2_MDISTTOT'].values,
                df_filt[df_filt['COOK'] <= 4 /
                        len(cook)]['V2_DUREE'].values.reshape(-1, 1))
            res_ss_outli = modele_sans_outlier.fit()
            plt.plot(df_filt['V2_DUREE'],
                     res_ss_outli.predict(df_filt['V2_DUREE'].values))
            plt.show()
            li_co[li_spat[i]] = [
                np.round(res.params[0] * 60, decimals=1),
                np.round(res.rsquared * 100, decimals=2),
                df[df['SPATIAL'] == i]['V2_MDISTTOT'].count()
            ]
            print(np.round(res.rsquared * 100, decimals=2),
                  np.round(res_ss_outli.rsquared * 100, decimals=2))
        else:
            li_co[li_spat[i]] = [0]
    print(li_co)
    #    plt.scatter(df[df['V2_MORICOM_MDESCOM_indicUU']==1]['V2_MDISTTOT'],df[df['V2_MORICOM_MDESCOM_indicUU']==1]['V2_DUREE'],color = 'm')
    return li_co
Пример #18
0
def NewAlphaZeroColormap(orig_cm, name, extent=25):
    """
    Only works for ListedColormaps
    """
    newcolors = orig_cm(crange)
    init = cm.inferno(0, alpha=0)
    final = newcolors[extent]
    t = crange[:extent][:, None] / crange[extent]
    newcolors[:extent] = t * t * t * np.subtract(final, init) + init
    new_cm = ListedColormap(newcolors, name=name)
    cm.register_cmap(name=name, cmap=new_cm)
 def plot_hist(ax, data, label):
     from matplotlib import cm
     colors = [cm.inferno(x) for x in np.linspace(0, 1, len(data))]
     for c,component in enumerate(data):
         if np.nanmax(component)>1e5:
             bins = np.logspace(np.log10(np.nanmin(component)),np.log10(np.nanmax(component)), 20)
             ax.set_xscale('log')
         else:
             bins = 20
         ax.hist(component, bins=bins, histtype='step',       color=colors[c],            label=str(c+1))
         ax.hist(component, bins=bins, histtype='stepfilled', color=colors[c], alpha=0.5, label=None)
         ax.set_xlabel(label, fontsize=12)
Пример #20
0
    def plot_ei_regime(ax, data, JEI, JII, filename, fig, zoom_in, zoom_lims,
                       scales):
        JII_b = np.array(data["points_fr_gpe"]) * 0.725 * 40 * 10
        JEI_b = np.array(data["points_fr_stn"]) * 1.2 * 23 * 5

        ax1 = ax.twinx().twiny()

        #if zoom_in == True:
        #	ax1.margins(x=zoom_lims[0],y=zoom_lims[1])
        for k, (x_row, y_row) in enumerate(zip(JEI_b, JII_b)):
            arr_col = cm.inferno(float(k) / len(JEI_b))
            for l, (x_col, y_col) in enumerate(zip(x_row, y_row)):
                if l < len(x_row) - 1:
                    ax1.arrow(x_col,
                              y_col,
                              x_row[l + 1] - x_col,
                              y_row[l + 1] - y_col,
                              head_width=50,
                              length_includes_head=True,
                              fc=arr_col,
                              ec=arr_col,
                              linestyle='-',
                              linewidth=1.0)
            if k % 2 == 0:
                ax1.plot(x_col,
                         y_col,
                         marker='o',
                         markersize=12,
                         color=arr_col,
                         label='gpe ratio:' + str(gpe_rat[k]),
                         alpha=0.8)
            else:
                ax1.plot(x_col,
                         y_col,
                         marker='o',
                         markersize=12,
                         color=arr_col,
                         alpha=0.8)
            ax1.plot(x_row[0],
                     y_row[0],
                     marker='*',
                     markersize=12,
                     color=arr_col,
                     alpha=0.8)

        handles, labels = ax1.get_legend_handles_labels()
        ax1.set_xlim(ax.get_xlim())
        ax1.set_ylim(ax.get_ylim())
        ax1.set_xticklabels([])
        ax1.set_yticklabels([])
Пример #21
0
    def save_images(self):
        """
        Save the extracted images
        :return:
        """
        rgb_np = self.get_rgb_np()
        thermal_np = self.extract_thermal_image()

        # Generate Images out of numpy arrays
        img_visual = Image.fromarray(rgb_np)
        thermal_normalized = (thermal_np - np.amin(thermal_np)) / (
            np.amax(thermal_np) - np.amin(thermal_np))
        img_thermal = Image.fromarray(
            np.uint8(cm.inferno(thermal_normalized) * 255))
        cropped_img_visual = Image.fromarray(self.cropped_visual_np)
        downscaled_img_visual = Image.fromarray(self.downscaled_rgb_image_np)

        fn_prefix, _ = os.path.splitext(self.flir_img_filename)

        # Generate the paths for the images
        thermal_filename = os.path.join(fn_prefix + '/' +
                                        fn_prefix.split('/')[1] +
                                        self.thermal_suffix)
        image_filename = os.path.join(fn_prefix + '/' +
                                      fn_prefix.split('/')[1] +
                                      self.image_suffix)
        cropped_image_filename = os.path.join(fn_prefix + '/' +
                                              fn_prefix.split('/')[1] +
                                              self.cropped_image_suffix)
        downscaled_image_filename = os.path.join(fn_prefix + '/' +
                                                 fn_prefix.split('/')[1] +
                                                 self.downscaled_image_suffix)

        if self.use_thumbnail:
            image_filename = os.path.join(fn_prefix + '/' +
                                          fn_prefix.split('\\')[6] +
                                          self.thumbnail_suffix)

        if self.is_debug:
            print("DEBUG Saving RGB image to:{}".format(image_filename))
            print("DEBUG Saving Thermal image to:{}".format(thermal_filename))
            print("DEBUG Saving RGB cropped image image to:{}".format(
                cropped_image_filename))
            print("DEBUG Saving RGB downscaled image to:{}".format(
                downscaled_image_filename))

        img_visual.save(image_filename)
        img_thermal.save(thermal_filename)
        downscaled_img_visual.save(downscaled_image_filename)
        cropped_img_visual.save(cropped_image_filename)
Пример #22
0
def plot(ind, square_sizes):
    maxX = max([x[0] + square_sizes[i] for i, x in enumerate(ind)])
    maxY = max([x[1] + square_sizes[i] for i, x in enumerate(ind)])

    grid = np.zeros((maxX, maxY))

    for square_index in range(len(square_sizes)):
        for x in range(ind[square_index][0],
                       ind[square_index][0] + square_sizes[square_index]):
            for y in range(ind[square_index][1],
                           ind[square_index][1] + square_sizes[square_index]):
                grid[x, y] = square_index

    my_cmap = cm.inferno(np.arange(cm.inferno.N))
    my_cmap[:, -1] = np.linspace(0, 1, cm.inferno.N)
    my_cmap = ListedColormap(my_cmap)

    plt.imshow(grid, cmap=my_cmap, alpha=0.3)
    plt.xticks([]), plt.yticks([])
    plt.show()
Пример #23
0
    def setup_ui(self):
        # {
        # Configure the main window defaults.  It enables mouse tracking to
        # be used by the zoom, and sets a black background.
        policy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                       QtWidgets.QSizePolicy.Expanding)
        policy.setHorizontalStretch(0)
        policy.setVerticalStretch(0)
        policy.setHeightForWidth(False)
        self.setSizePolicy(policy)
        self.setMouseTracking(True)

        pal = self.palette()
        pal.setColor(QtGui.QPalette.Background, QtCore.Qt.black)
        self.setAutoFillBackground(True)
        self.setPalette(pal)
        # }

        # {
        # Pre-compute RGBA values for the two different modes from the `inferno`
        # colormap.
        #
        # self.rgbas_alpha is used when the heatmap is overlayed atop the image.
        # self.rgbas_noalpha is used when no image is displayed.
        indices = np.linspace(0, 1, 256)
        rgbas = cm.inferno(indices)

        self.rgbas_noalpha = [
                QtGui.QColor(
                    int(r * 255),
                    int(g * 255),
                    int(b * 255),
                    int(a * 255)).rgba() for r, g, b, a in rgbas]

        rgbas[:,3] *= indices
        self.rgbas_alpha = [
                QtGui.QColor(
                    int(r * 255),
                    int(g * 255),
                    int(b * 255),
                    int(a * 255)).rgba() for r, g, b, a in rgbas]
Пример #24
0
def plotMedianDacNoise(nos, detFreq=150, getGoodDetsFromStats=True, show=True):
    ''' gets a list of noise observations, splits the data in detector types
    and makes a plot of the median psd
    '''
    no = nos[0]
    colors = cm.inferno(np.linspace(0, 1, len(nos)))
    if not getGoodDetsFromStats:
        detFreqs = no.detFreqs
        row, col = np.where(detFreqs == detFreq)
        print "warning, blindly plotting dets of the same freq"
    alpha = 0.4
    for j in range(len(nos)):
        color = colors[j]
        no = nos[j]
        if getGoodRowsColsFromNoiseStats:
            if no.pctRn != 0:
                row, col = getGoodRowsColsFromNoiseStats(
                    no.array, no.pctRn, detFreq)
        md = np.mean(no.pxx[row, col, :], axis=-2)
        if no.pctRn == 0:
            color = 'blue'
            alpha = 0.6
        plt.loglog(no.f,
                   md,
                   label='pctRn: %i, N_det: %i' % (no.pctRn, len(row)),
                   alpha=alpha,
                   color=color)
    plt.ylim([3e-4, 40.0])
    plt.legend()
    title = 'Array: %s. %i GHz mean psd.' % (no.array, detFreq)
    title = title.replace('AR', 'PA')
    plt.title(title)
    plt.xlabel('f [Hz]')
    plt.ylabel('psd [$\\frac{dac^2}{Hz}$]')
    plt.tight_layout()
    if show:
        plt.show()
    else:
        plt.savefig('results/average_HighFreqSpectrum_%s_detFreq_%i.pdf' %
                    (no.array, detFreq))
        plt.close()
Пример #25
0
def main():
    flags = parse_args()

    images = sorted(os.listdir(os.path.join(flags.data, 'depth')))
    frames = []
    for i, image in enumerate(images):
        print(f"Reading image {image}", end='\r')
        path = os.path.join(flags.data, 'depth', image)
        depth = np.load(path)
        max_depth = 7.5
        depth_m = depth / 1000.0
        depth_map = np.clip(1.0 - depth_m / max_depth, 0.0, 1.0)
        depth_map = cm.inferno(depth_map)

        frames.append((depth_map * 255).astype(np.uint8))

    writer = io.FFmpegWriter(os.path.join(flags.data, 'depth_video.mp4'))
    try:
        for i, frame in enumerate(frames):
            print(f"Writing frame {i:06}" + " " * 10, end='\r')
            writer.writeFrame(frame)
    finally:
        writer.close()
Пример #26
0
    def __init__(self, fname_path, skip_thermal=False):
        assert os.path.exists(fname_path), f'file {fname_path} does not exists'
        self.fname_path = fname_path
        self.datetime = self.extract_datetime()
        self.fie = flir_image_extractor.FlirImageExtractor(
            image_suffix="v.jpg", thermal_suffix="t.png")
        cached_thermal = ImageFiles.get_cached_thermal(
            fname_path) if Cfg.cache_thermal_allowed else None
        self.fie.process_image(fname_path, cached_thermal, skip_thermal)
        self.flir_img = self.get_flir_image(fname_path)
        self.visual_img = self.fie.get_rgb_np()
        self.thermal_np = self.fie.get_thermal_np()
        thermal_normalized = (self.thermal_np - np.amin(self.thermal_np)) \
                             / (np.amax(self.thermal_np) - np.amin(self.thermal_np))
        self.thermal_img = np.array(
            np.uint8(cm.inferno(thermal_normalized) * 255))  # inferno,gray
        self.thermal_img = cv.cvtColor(self.thermal_img, cv.COLOR_RGBA2BGR)

        self.vis_therm_ratio = (self.visual_img.shape[0] /
                                self.thermal_np.shape[0],
                                self.visual_img.shape[1] /
                                self.thermal_np.shape[1])
        if self.flir_img.shape[0] > self.flir_img.shape[1]:  # vertical
            # transpose
            # self.flir_img = cv.transpose(self.flir_img)
            # self.visual_img = cv.transpose(self.visual_img)
            # self.thermal_np = cv.transpose(self.thermal_np)
            # self.thermal_img = cv.transpose(self.thermal_img)
            # rotate
            self.flir_img = np.rot90(self.flir_img)
            self.visual_img = np.rot90(self.visual_img)
            self.thermal_np = np.rot90(self.thermal_np)
            self.thermal_img = np.rot90(self.thermal_img)

        self.image_id = ImageFiles.save(self.datetime, self.flir_img,
                                        self.visual_img, self.thermal_np)
        self.skip_thermal = skip_thermal
Пример #27
0
 def plot_deu_by_level(self, maxlevel, d0list, dumb=True):
     """
     Plots the defender's expected utility.
     """
     res = self.lkresults
     fig, ax = plt.subplots()
     ix = 0
     for d0 in d0list:
         if len(d0list) ==1:
             b = 1
         else:
             b = (255 - 255*ix/float(len(d0list)))/float(255)
         toplot = self.deu_over_levels(maxlevel, d0, dumb).values.T
         ax.plot(np.arange(0, maxlevel,2), toplot, color = cm.inferno(int(255*(1-b))), linewidth=1)
         ix +=1
     if len(d0list) > 1:
         ax2 = fig.add_axes([0.95, 0.12, 0.05, 0.78])
         cb = mpl.colorbar.ColorbarBase(ax2, cmap=plt.cm.inferno, 
                                boundaries=d0list, 
                                label="Initial Threshold")
     fig.suptitle("Defender of level-$k$ expected utility against an attacker of level $k+1$.", fontsize=12)
     ax.set_xlabel("$k$")
     ax.set_ylabel("Defender's Expected Utility")
     return fig, ax
Пример #28
0
    def draw_brush(self, x, y):

        width = self.line_width
        color = self.color

        if self.shrink != 0:

            interpolation_factor = ((self.shrink - 1) / 9.0)
            value = 50.0 * interpolation_factor + 500.0 * (
                1.0 - interpolation_factor)
            width *= (value - self.distance) / value
            width = max(0, int(width))
            color_index = 255 * (value - self.distance) / value
            color_index = 255 - max(0, int(color_index))
            color = cm.inferno(color_index)
            color = (int(color[0] * 255), int(color[1] * 255),
                     int(color[2] * 255))

        if width == 0:
            return

        color_image = Image.new("RGBA",
                                size=(2 * width, 2 * width),
                                color=color)
        image = self.brush_image.resize((2 * width, 2 * width),
                                        Image.ANTIALIAS)
        image = ImageChops.multiply(image, color_image)

        overall_image = Image.new("RGBA", size=self.size, color="black")
        points = self.get_mandala_points(x, y)
        for (x, y) in points:
            x = int(x)
            y = int(y)
            self.pilImage.paste(image, (x - width, y - width), image)

        self.refresh()
def draw_stixels(stixels,
                 max_disparity,
                 disparity_image=None,
                 semantic_image=None,
                 semantic_labelImg=None,
                 cost_image=None,
                 max_cost=1e4,
                 instancegt_mask=None,
                 disparity_result_image=None,
                 instance_image=None):
    """
    This method visualizes the stixels as images. Output images are for example
    a semantic segmentation image which visualizes each class by a color.
    A stixel will then be drawn as a rectangle. Optionally, a border can be
    drawn around the stixel. The final result can then be overlayed with the
    original RGB image.
    
    Note: Over the course of implementing and especially extending the
    proof of conecpt, it has become quite a mess, but it works. 
    """
    instance_gt_image = None
    shape = None
    for img in (semantic_image, disparity_image, semantic_labelImg):
        if img is not None:
            shape = img.shape[:2]
    if shape is None:
        raise ValueError("At least one output image has to be provided!")
    stixel_width = shape[1] // len(stixels)
    print("Stixel width = {}".format(stixel_width))
    print("image shape = {}".format(shape))

    stixel_count = 0
    for col, column_stixels in enumerate(stixels):
        for stixel in column_stixels:
            stixel_count += 1
            # Decide color based upon stixel type.
            color = (255, 255, 255)  # type 0 (ground)
            instance_color = np.array((0, 0, 0, 255), dtype=np.float)
            #cost = stixel[5] / max
            min_cost = -1e4
            max_cost = 1e4
            factor = max((stixel[5] - min_cost), 0) / (max_cost - min_cost)
            cost = (1. - factor) * 255

            # Compute image coordinates
            # *.stixels file    OpenCV
            # row in [0,h-1]    y in [0,h-1]
            #  ^                0/0---x---->
            #  |                 |
            #  |                 |
            # row                y
            #  |                 |
            #  |                 |
            # 0/0--column-->     v
            # y = (h-1) - row
            topleft_x = col * stixel_width
            topleft_y = shape[0] - stixel[2] - 1  # vT, mirror y-axis
            bottomright_x = topleft_x + stixel_width - 1  # e.g. width 5: 0-4,5-9,
            bottomright_y = shape[0] - stixel[1] - 1  # vB, mirror y-axis

            # type distinction
            # type 2 (sky)
            if stixel[0] == 2 or (stixel[0] == 1 and stixel[3] < 1.0):
                color = (255, 191, 0)
            elif stixel[0] == 1:  # type 1 (object)
                # Cropping of at disparities of max_disparity * 2e-2 = 2.56 and
                # below.
                distance = min(float(stixel[3] + 20) / max_disparity, 1.)
                color = np.array([[cm.inferno(distance)[:3]]]) * 255
                color = color.astype(np.uint8)
                color = cv2.cvtColor(color, cv2.COLOR_RGB2BGR)
                color = color[0, 0].tolist()

                # compute instance affiliation from ground truth
                if instancegt_mask is not None:
                    # Only consider classes with instances.
                    if stixel[4] < 11:  # 10 is sky
                        instance_color = np.array((0., 0., 0., 255.))
                    else:
                        max_instanceid = 0
                        # Must be at least 10% of stixel.
                        max_instanceid_pixels = 0
                        # Only use instance mask of predicted class.
                        # Before:for mask in instancegt_mask:
                        mask = instancegt_mask[stixel[4] - 11]
                        # extract pixels that belong to stixel from mask
                        stixel_pixels = mask[topleft_y:bottomright_y+1,
                                             topleft_x:bottomright_x+1]\
                                            .astype(np.int)
                        pixels_per_id = np.bincount(np.ravel(stixel_pixels))

                        # ignore zero-rows-stixels
                        if len(pixels_per_id) > 0:
                            max_instanceid_pixels = pixels_per_id.max()
                            max_instanceid = pixels_per_id.argmax()

                        instance_color =\
                                COLOR_LUT_RANDOM[max_instanceid\
                                                 % len(COLOR_LUT_RANDOM),
                                                 :]
                        # Alpha based on number of instance pixels.
                        #alpha = np.clip(max_instanceid_pixels, 150.0, 255.0)
                        alpha = 255.0
                        instance_color = np.concatenate(
                            [instance_color, [alpha]])
                        instance_color = instance_color.astype(np.float)
                        if max_instanceid == 0:
                            instance_color[:3] = 255.0
                            instance_color[3] = 255.0
                        elif (max_instanceid_pixels < 0.1 * stixel_width *
                              (bottomright_y - topleft_y)):
                            instance_color[:3] = 255.0

            if instancegt_mask is not None:
                if instance_gt_image is None:
                    instance_gt_image = np.zeros(
                        (*disparity_image.shape[:2], 4))
                cv2.rectangle(instance_gt_image, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              instance_color,
                              thickness=-1)  # fill rectangle
                # let's skip borders for now
                if False:
                    if np.abs(topleft_y - bottomright_y) > 1:
                        cv2.rectangle(instance_gt_image,
                                      (topleft_x, topleft_y),
                                      (bottomright_x + 1, bottomright_y + 1),
                                      0,
                                      thickness=1)  # border only on left side
            if instance_image is not None:
                if len(stixel) > 8:
                    instance_id = int(stixel[8])
                    if instance_id == -1:
                        instance_color = np.array((255., 255., 255.))
                    else:
                        instance_color = COLOR_LUT_RANDOM[
                            instance_id % len(COLOR_LUT_RANDOM), :]
                    instance_color = instance_color.astype(np.float)
                    cv2.rectangle(instance_image, (topleft_x, topleft_y),
                                  (bottomright_x, bottomright_y),
                                  instance_color,
                                  thickness=-1)  # fill rectangle
                if True:
                    if np.abs(topleft_y - bottomright_y) > 1:
                        cv2.rectangle(instance_image, (topleft_x, topleft_y),
                                      (bottomright_x, topleft_y - 2),
                                      (255, 255, 255),
                                      thickness=-1)  # border only on left side
            if disparity_image is not None and len(stixel) > 4:
                cv2.rectangle(disparity_image, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              color,
                              thickness=-1)  # fill rectangle
                # Border always overlaps with right and bottom neighboring
                # stixel.
                #if np.abs(topleft_y - bottomright_y) > 2:
                #    cv2.rectangle(disparity_image,
                #                  (topleft_x, topleft_y),
                #                  (bottomright_x+1, bottomright_y+1),
                #                  (0,0,0),
                #                  thickness=1) # border only on left side
            if semantic_image is not None and len(stixel) > 4:
                cv2.rectangle(semantic_image, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              stixel[4] + 1,
                              thickness=-1)  # fill rectangle
                if False:  # one pixel width border (around)
                    if np.abs(topleft_y - bottomright_y) > 1:
                        cv2.rectangle(semantic_image, (topleft_x, topleft_y),
                                      (bottomright_x + 1, bottomright_y + 1),
                                      0,
                                      thickness=1)  # border only on left side
                if True:  # upper end border of "width" pixels
                    width = 1
                    if np.abs(topleft_y - bottomright_y) > 1:
                        cv2.rectangle(semantic_image, (topleft_x, topleft_y),
                                      (bottomright_x, topleft_y - width),
                                      0,
                                      thickness=-1)  # border only on left side
            if cost_image is not None and len(stixel) > 4:
                cv2.rectangle(cost_image, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              int(cost),
                              thickness=-1)  # fill rectangle
            # --- result images
            if semantic_labelImg is not None and len(stixel) > 4:
                cv2.rectangle(semantic_labelImg, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              cityscapes_labels.trainId2label[stixel[4]].id,
                              thickness=-1)  # fill rectangle
            if disparity_result_image is not None:
                # TODO: Handle ground stixels appropriately.
                cv2.rectangle(disparity_result_image, (topleft_x, topleft_y),
                              (bottomright_x, bottomright_y),
                              stixel[3],
                              thickness=-1)  # fill rectangle
    print("Processed {} stixels.".format(stixel_count))
    return (disparity_image, semantic_image, semantic_labelImg, cost_image,
            stixel_count, instance_gt_image, disparity_result_image,
            instance_image)
Пример #30
0
def plot_obse_samplers(
    lcset_name,
    lcset_info,
    obse_sampler_bdict,
    original_space: bool = 1,
    pdf_scale: float = 0.01,
    figsize=FIGSIZE_2X1,
    dpi=DPI,
    add_samples=0,
    save_filedir=None,
):
    survey = lcset_info['survey']
    band_names = lcset_info['band_names']

    fig, axs = plt.subplots(1, 2, figsize=figsize, dpi=dpi)
    for kb, b in enumerate(band_names):
        ax = axs[kb]
        obse_sampler = obse_sampler_bdict[b]
        if original_space:
            label = '$p(x_{ij},\sigma_{xij})$' + f' {lcset_name} samples'
            ax.plot(obse_sampler.raw_obse,
                    obse_sampler.raw_obs,
                    'k.',
                    markersize=2,
                    alpha=0.2)
            ax.plot(np.nan, np.nan, 'k.', label=label)

            ### add samples
            if add_samples:
                n = int(2e3)
                to_sample = obse_sampler.raw_obs
                std = 1e-4
                new_obs = [
                    np.random.normal(
                        to_sample[np.random.randint(0, len(to_sample))], std)
                    for _ in range(n)
                ]  # kde
                #x = 0.05; new_obs = np.linspace(x, x+0.001, 1000) # sanity check
                new_obse, new_obs = obse_sampler.conditional_sample(new_obs)
                ax.plot(new_obse, new_obs, 'r.', markersize=2, alpha=1)
                ax.plot(np.nan,
                        np.nan,
                        'r.',
                        label='$\hat{p}(x_{ij},\sigma_{xij})$ samples (KDE)')

            ### rot axis
            x = np.linspace(obse_sampler.raw_obse.min(),
                            obse_sampler.raw_obse.max(), 100)
            ax.plot(x,
                    x * obse_sampler.m + obse_sampler.n,
                    'b',
                    alpha=0.75,
                    label='rotation axis',
                    lw=1)
            #ax.plot(obse_sampler.lr_x, obse_sampler.lr_y, 'b.', alpha=1, markersize=4); ax.plot(np.nan, np.nan, 'b.', label='rotation axis support samples')

            ax.set_xlabel('observation-error')
            ax.set_ylabel('observation-flux' if kb == 0 else None)
            ax.set_xlim([0.0, 0.05])
            ax.set_ylim([0.0, 0.3])

        else:
            label = '$p(x_{ij}' + "'" + ',\sigma_{xij}' + "'" + ')$' + f' empirical samples'
            ax.plot(obse_sampler.obse,
                    obse_sampler.obs,
                    'k.',
                    markersize=2,
                    alpha=0.2)
            ax.plot(np.nan, np.nan, 'k.', label=label)
            min_obse = obse_sampler.obse.min()
            max_obse = obse_sampler.obse.max()
            pdfx = np.linspace(min_obse, max_obse, 200)
            colors = cm.inferno(np.linspace(0, .5, len(obse_sampler.distrs)))
            min_pdfy = np.infty
            for p_idx in range(len(obse_sampler.distrs)):
                d = obse_sampler.distrs[p_idx]
                if p_idx % 10 == 0:
                    rank_ranges = obse_sampler.rank_ranges[p_idx]
                    pdf_offset = rank_ranges[1]  # upper of rank range
                    pdfy = d['distr'].pdf(pdfx, *d['params'])
                    pdfy = pdfy / pdfy.max() * pdf_scale + pdf_offset
                    c = colors[p_idx]
                    label = '$q(\sigma_{xij}' + "'" + '|x_{ij}' + "'" + ')$ Normal distribution fit'
                    ax.plot(pdfx,
                            pdfy,
                            c=c,
                            alpha=1,
                            lw=1,
                            label=label if p_idx == 0 else None)
                    min_pdfy = pdfy.min(
                    ) if pdfy.min() < min_pdfy else min_pdfy

            ax.set_xlabel('rotated-flipped observation-error')
            ax.set_ylabel('rotated observation-flux' if kb == 0 else None)
            #ax.set_xlim([0.0, 0.02])
            ax.set_ylim([min_pdfy, 1])

        title = ''
        title += f'{latex_bf_alphabet_count(kb)} Joint distribution from {lcset_name}; band={b}' + '\n'
        ax.set_title(title[:-1])
        ax.legend(loc='upper left')

        ### multiband colors
        [
            ax.spines[border].set_color(COLOR_DICT[b])
            for border in ['bottom', 'top', 'right', 'left']
        ]
        [
            ax.spines[border].set_linewidth(2)
            for border in ['bottom', 'top', 'right', 'left']
        ]

    fig.tight_layout()
    save_fig(save_filedir, fig)
Пример #31
0
def make_coolingfile(colfiles):
    '''
    prepost.make_coolingfile
    
    PURPOSE:
        Reads in a bunch of outfiles and writes a single parameter file with nh, T and the volume emissivity
    
    INPUTS:
        colfiles:[list/array] All the .col files for the completed runs
    
    OUTPUTS:
        File with nh, T and volume emissivity, Lambda
    
    NOTES: 
        Likely only works if the grid is a rectangle. May want to change this in the future?
        Also will want to remove interpolation section once grid is complete.
    
    '''
    
    outdata = []
    
    for i, f in enumerate(colfiles):
        try:
            data = np.genfromtxt(f, skip_header = 1, usecols=[1,3])
        except StopIteration:
            print('File empty: ' +f)
            continue
        except ValueError:
            pdb.set_trace()
        
        density = float(f.split('__n')[1].split('.col')[0])
        Temperature = float(f.split('__T')[1].split('__')[0])
        
        outdata.append([data[1], density, Temperature])
    
    outdata = np.array(outdata)
    maxcool = np.max(np.log10(outdata[:,0]))
    mincool = np.min(np.log10(outdata[:,0]))
    
    for i, point in enumerate(outdata):
        plt.scatter(point[2], point[1], color = cm.inferno((np.log10(point[0])-mincool)/(maxcool - mincool), 1), s = 50, marker = 's')
    
    sm = plt.cm.ScalarMappable(cmap=cm.inferno, norm=plt.Normalize(vmin=mincool, vmax=maxcool))
    sm.set_array(outdata[:,2])
    plt.colorbar(sm)
    
    plt.show()
    
    #Sort the data into a grid
    unT = np.unique(outdata[:,2])
    unN = np.unique(outdata[:,1])
    
    grid = np.zeros([len(unT), len(unN)])
    
    for i, x in enumerate(unT):
        for j, y in enumerate(unN):
            ind = (outdata[:,2] == x) * (outdata[:,1] == y)
            if np.sum(ind) == 0:
                grid[i,j] = np.nan
            else:
                grid[i,j] = outdata[np.where(ind)[0][0],0]
                
    
    #Write out the grid + temp/density
    gridfile = open('coolinggrid.txt', 'w')
    gridfile.write('Grid containing volume emissivities from Cloudy coronal models. First row is log10(nh), first column is T\n')
    gridfile.write('#-------------------------------------------------------------------------------------------------------#\n')
    
    gridfile.write('0, ')
    line = ''
    for val in unN:
        line = line + str(val) +', '
    line = line[:-2] +'\n'
    gridfile.write(line)

    for i, line in enumerate(grid):
        line = str(unT[i]) +', '
        for val in grid[i]:
            line = line +str(val) +', '
        line = line[:-2] + '\n'
        
        gridfile.write(line)
    gridfile.close()
Пример #32
0
def transform_and_clean_hex_image(pmt_signal, cam_geom, photo_electrons):

    start_time = time.time()

    colors = cm.inferno(pmt_signal/max(pmt_signal))

    new_geom, new_signal = convert_geometry_1d_to_2d(
        cam_geom, pmt_signal, cam_geom.cam_id)

    print("rot_signal", np.count_nonzero(np.isnan(new_signal)))

    square_mask = new_geom.mask
    cleaned_img = wavelet_transform(new_signal,
                                    raw_option_string=args.raw)

    unrot_img = cleaned_img[square_mask]
    unrot_colors = cm.inferno(unrot_img/max(unrot_img))

    cleaned_img_ik = kill_isolpix(cleaned_img, threshold=.5)
    unrot_img_ik = cleaned_img_ik[square_mask]
    unrot_colors_ik = cm.inferno(unrot_img_ik/max(unrot_img_ik))

    square_image_add_noise = np.copy(new_signal)
    square_image_add_noise[~square_mask] = \
        np.random.normal(0.13, 5.77, np.count_nonzero(~square_mask))

    square_image_add_noise_cleaned = wavelet_transform(square_image_add_noise,
                                                       raw_option_string=args.raw)

    square_image_add_noise_cleaned_ik = kill_isolpix(square_image_add_noise_cleaned,
                                                     threshold=1.5)

    unrot_geom, unrot_noised_signal = convert_geometry_back(
        new_geom, square_image_add_noise_cleaned_ik, cam_geom.cam_id)

    end_time = time.time()
    print(end_time - start_time)

    global fig
    global cb1, ax1
    global cb2, ax2
    global cb3, ax3
    global cb4, ax4
    global cb5, ax5
    global cb6, ax6
    global cb7, ax7
    global cb8, ax8
    global cb9, ax9
    if fig is None:
        fig = plt.figure(figsize=(10, 10))
    else:
        fig.delaxes(ax1)
        fig.delaxes(ax2)
        fig.delaxes(ax3)
        fig.delaxes(ax4)
        fig.delaxes(ax5)
        fig.delaxes(ax6)
        fig.delaxes(ax7)
        fig.delaxes(ax8)
        fig.delaxes(ax9)
        cb1.remove()
        cb2.remove()
        cb3.remove()
        cb4.remove()
        cb5.remove()
        cb6.remove()
        cb7.remove()
        cb8.remove()
        cb9.remove()

    ax1 = fig.add_subplot(333)
    disp1 = CameraDisplay(cam_geom, image=photo_electrons, ax=ax1)
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("photo-electron image")
    disp1.cmap = plt.cm.inferno
    disp1.add_colorbar()
    cb1 = disp1.colorbar

    ax2 = fig.add_subplot(336)
    disp2 = CameraDisplay(cam_geom, image=pmt_signal, ax=ax2)
    plt.gca().set_aspect('equal', adjustable='box')
    disp2.cmap = plt.cm.inferno
    disp2.add_colorbar()
    cb2 = disp2.colorbar
    plt.title("noisy image")

    ax3 = fig.add_subplot(331)
    plt.imshow(new_signal, interpolation='none', cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("noisy, slanted image")
    cb3 = plt.colorbar()

    ax4 = fig.add_subplot(334)
    plt.imshow(cleaned_img, interpolation='none', cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("cleaned, slanted image, islands not killed")
    cb4 = plt.colorbar()
    ax4.set_axis_off()

    ax5 = fig.add_subplot(337)
    plt.imshow(np.sqrt(cleaned_img_ik), interpolation='none', cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("cleaned, slanted image, islands killed")
    cb5 = plt.colorbar()
    ax5.set_axis_off()

    #
    ax6 = fig.add_subplot(332)
    plt.imshow(square_image_add_noise, interpolation='none', cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("slanted image, noise added")
    cb6 = plt.colorbar()
    ax6.set_axis_off()

    #
    ax7 = fig.add_subplot(335)
    plt.imshow(np.sqrt(square_image_add_noise_cleaned), interpolation='none',
               cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("slanted image, noise added, cleaned")
    cb7 = plt.colorbar()
    ax7.set_axis_off()

    ax8 = fig.add_subplot(338)
    plt.imshow(square_image_add_noise_cleaned_ik, interpolation='none',
               cmap=cm.inferno,
               origin='lower')
    plt.gca().set_aspect('equal', adjustable='box')
    plt.title("slanted image, noise added, cleaned, islands killed")
    cb8 = plt.colorbar()
    ax8.set_axis_off()

    try:
        ax9 = fig.add_subplot(339)
        disp9 = CameraDisplay(unrot_geom, image=unrot_noised_signal,
                              ax=ax9)
        plt.gca().set_aspect('equal', adjustable='box')
        plt.title("cleaned, original geometry, islands killed")
        disp9.cmap = plt.cm.inferno
        disp9.add_colorbar()
        cb9 = disp9.colorbar
    except:
        pass

    plt.suptitle(cam_geom.cam_id)
    plt.subplots_adjust(top=0.94, bottom=.08, left=0, right=.96, hspace=.41, wspace=.08)

    plt.pause(.1)
    response = input("press return to continue")
    if response != "":
        exit()
Пример #33
0
        if i>0:
            param_range = np.linspace(param_values[i][0], param_values[i][1], 3)
        else:
            param_range = np.array(param_values[i])
    
        current_params = model.get_baseline_params()
        for n, param_value in enumerate(param_range):
            current_params[i] = param_value
            x_grid, y_grid, dl = dlg.get_model_dl(current_params)
            scale_z = True if n==1 else False
            dlp.plot_surface(x_grid, y_grid, dl, color=colors[n], alpha=0.7, scale_z=scale_z)
        
        title_format = r'$\%s$' if param_name=='tau' else r'$%s$'
        dlp.ax.set_title(title_format % (param_name), loc='left', fontsize=42)        
        dlp.ax.legend(labels, param_range, fontsize=32)
        plt.savefig('figures/param_variations_%s.pdf' % param_name)
            
model = dl_model_3.DLModel3()
dlg = dl_generator.DLGenerator(model)    

dr = data_reader.DataReader()
data = dr.get_processed_data(path='csv/processed_data_high_low.csv')

param_names = ['tau', 'c_{11}', 'c_{21}', 'c_{12}']
k = 0.2
param_values = [[0.04, 0.05, 0.07], [-k*1.0, k*1.0], [-k*1.0, k*1.0], [-k*1.0, k*1.0]]
colors = [cm.inferno(0.2), cm.Greys(0.7), cm.inferno(0.8)]
labels = [plt.Rectangle((0, 0), 1, 1, fc=color) for color in colors]

plot_dl_variations(dlg, param_names, param_values, colors)
Пример #34
0
    def update(self):
        """
        """
        # Gets an element from the buffer and free the buffer
        buffer_element = self.buffer.get()
        self.buffer.task_done()
        # When the Producer Thread finishes publishing the data it sends a None
        # through the buffer to sinalize it has finished.
        if buffer_element is not None:
            score_map = buffer_element.score_map
            gt_img = buffer_element.img
            ref_img = buffer_element.ref_img
            visible = buffer_element.visible
            name = buffer_element.name
            bbox = buffer_element.bbox

            if self.peak_pos is not None and self.disp_prior is not None:
                h, w = score_map.shape
                disp_prior = make_gaussian_map((h,w), self.peak_pos, self.disp_prior)
                np.expand_dims(disp_prior, axis=2)
                score_map = score_map*disp_prior
                self.prior_radius.setData(pos=[(self.peak_pos[1], self.peak_pos[0])], size=self.disp_prior)

            # Find peak of the score map. You must incorporate all priors before
            # taking the max.
            peak = np.unravel_index(score_map.argmax(), score_map.shape)
            self.peak_pos = peak
            # Apply the inferno color map to the score map.
            # The output of cm.inferno has 4 channels, 3 color channels and a
            # transparency channel
            score_img = cm.inferno(score_map)[:, :, 0:3]
            # Overlay the score_img with a grayscale version of the original
            # frame
            img_gray = rgb2gray(gt_img)
            score_img = score_img[0:img_gray.shape[0], 0:img_gray.shape[1], :]
            score_img = score_img*self.alpha + (1-self.alpha)*img_gray/255

            vis_color = 'g' if visible else 'r'
            self.score_img.setImage(score_img, autoDownsample=False)
            # Set the marker in the peak. The pyqtgraph GraphItem takes the
            # position in terms of the x and y coordinates.
            self.peak.setData(pos=[(peak[1], peak[0])])
            self.gt_img.setImage(gt_img, autoDownsample=False)
            if bbox is not None:
                self.bounding_box.setRect(*bbox)
                center_error = np.linalg.norm([bbox[0]+bbox[2]/2-peak[1], bbox[1]+bbox[3]/2-peak[0]])
                self.center_errors.append(center_error)
                self.curve.setData(self.center_errors)
            else:
                self.bounding_box.setRect(0, 0, 0, 0)
            self.ref_img.setImage(ref_img, autoDownsample=False)
            # Calculate the fps rate.
            now = ptime.time()
            dt = now - self.lastTime
            self.lastTime = now
            if self.fps is None:
                self.fps = 1.0/dt
            else:
                s = np.clip(dt*3., 0, 1)
                self.fps = self.fps * (1-s) + (1.0/dt) * s
            self.fpsLabel.setText('{:.2f} fps'.format(self.fps), color='w')
            self.visibleLabel.setText('Visible: {}'.format(visible), color=vis_color)
            self.bufferLabel.setText('{} in Buffer'.format(self.buffer.qsize()))
            self.nameLabel.setText(name, size='10pt', color='w')

            self.index += 1
        else:
            # Set alive attribute to False to indicate the end of the program
            self.alive = False
            if self.exit_on_end:
                self.exit()
Пример #35
0
"Fp2" : (239,61), "O1" : (157,301), 
"O2" : (238,301), "Pz" : (197,245),
"P3" : (146,245), "P4" : (250,245), "T5" : (95,255),
"T6" : (300,255)} 

el_centers = np.array([el_centers_dict[item] for item in sens])
fig, ax = plt.subplots(nrows=2, ncols=2)
for band in range(4):
    plt.subplot(2,2,band+1)
    plt.title(bands[band])
    for i in range(eeg_no_ch):     
        for j in range(i):  
            coh = coherence_master[0,7,1,i,j,band]
            if coh > 0.5:
                coh = (coh - 0.5)*2
                col = cm.inferno(coh)
                plt.plot([el_centers[i,0], el_centers[j,0]], 
                         [el_centers[i,1], el_centers[j,1]], 
                         color=col, alpha=coh*.99, linewidth=coh*8)
    plt.imshow(eeg_1020)
    ax = plt.gca()            
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_xticks([])
    ax.set_yticks([])
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.03, 0.7])
cmap = mpl.cm.plasma
norm = mpl.colors.Normalize(vmin=0.5, vmax=1)
mpl.colorbar.ColorbarBase(cbar_ax, cmap=cmap,
                          norm=norm, orientation='vertical', 
Пример #36
0
                                V[2:  , 1:-1])
        uvv = u*v*v
        u += (Du*Lu - uvv + F*(1-u))
        v += (Dv*Lv + uvv - (F+k)*v)

t = 0.3

for i in tqdm(range(n)):
    res[:,n-i-1][v>t] = 256*u[v>t]
    update()

mask = res == 0
res += np.arange(n,dtype='B')[:, np.newaxis]//8
res[mask] = 0

pal = [ Color(0,0,0,0) ] + [ Color( *[ int(255*x) for x in inferno(i/128)] ) for i in range(255) ]

# res[res<0.1] = 0
# res = (res*256).astype('B')

res = res[:,:-3,...]
nz = len(res.nonzero()[0])
print(nz, 'non-zero')
if nz:
    vox = Vox.from_dense(res)
    vox.palette = pal

    fn = 'test-%s.vox'%datetime.now().isoformat().replace(':', '_')
    print('wrote', fn)
    VoxWriter(fn, vox).write()