def __init__(self, i, b, w, bins=10): # set the model parameters self.i = i self.b = b self.w = w # extract additional information self.num_polls = b.shape[0] self.num_candidates = b.shape[1] # set computational parameters self.bins = bins self.quantiles = np.linspace(0,1,bins+1) self.states = np.linspace(0,(bins-1)/bins,bins) + np.diff(self.quantiles)/2
def SBM_trials(N_tot, N_comm, edges, alpha, frac_res, trials, beta): with np.errstate(invalid='ignore'): frac_modules = np.linspace(.2, 1, frac_res, endpoint=False) mod_opts, hMod_opts = np.zeros(frac_res), np.zeros(frac_res) scores_mod_orig, scores_hMod_orig = np.zeros(frac_res), np.zeros( frac_res) scores_mod_s, scores_hMod_s = np.zeros(frac_res), np.zeros(frac_res) for i in range(frac_res): for j in range(trials): mod, parMod = gg.get_random_modular(N_tot, N_comm, edges, frac_modules[i]) hMod, parhMod = gg.get_hierarchical_modular( N_tot, N_comm, edges, frac_modules[i], alpha) mod_s, mod_opt, score_mod_orig, score_mod_s = optimize_one_param_learnability( mod, parMod, beta) hMod_s, hMod_opt, score_hMod_orig, score_hMod_s = optimize_one_param_learnability( hMod, parhMod, beta) mod_opts[i] += mod_opt hMod_opts[i] += hMod_opt scores_mod_orig[i] += score_mod_orig scores_hMod_orig[i] += score_hMod_orig scores_mod_s[i] += score_mod_s scores_hMod_s[i] += score_hMod_s mod_opts /= trials hMod_opts /= trials scores_mod_orig /= trials scores_hMod_orig /= trials scores_mod_s /= trials scores_hMod_s /= trials return frac_modules, mod_opts, hMod_opts, scores_mod_orig, scores_hMod_orig, scores_mod_s, scores_hMod_s
def optimizeColormap(name, cmap_type=None, l_range=(0.0, 1.0)): cmap = plt.get_cmap(name) # Get values, discard alpha x = np.linspace(0, 1, 256) values = cmap(x)[:, :3] lab_colors = [] for rgb in values: lab_colors.append(convert_color(sRGBColor(*rgb), target_cs=LabColor)) if cmap_type == "flat": mean = np.mean([_i.lab_l for _i in lab_colors]) target_lightness = optimalLightness(len(x), cmap_type=cmap_type, l_range=(mean, mean)) else: target_lightness = optimalLightness( len(x), cmap_type=cmap_type, l_range=l_range) * 100.0 for color, lightness in zip(lab_colors, target_lightness): color.lab_l = lightness # Go back to rbg. rgb_colors = [convert_color(_i, target_cs=sRGBColor) for _i in lab_colors] # Clamp values as colorspace of LAB is larger then sRGB. rgb_colors = [(_i.clamped_rgb_r, _i.clamped_rgb_g, _i.clamped_rgb_b) for _i in rgb_colors] cm = matplotlib.colors.LinearSegmentedColormap.from_list(name=name + "_optimized", colors=rgb_colors) return cm
def __new__(self, M=10, a=0.54, phi=0, normalised=True): # Create the window if phi == 0: wc = a + (1 - a) * np.cos(2 * pi * np.linspace(-0.5, 0.5, M)) win = wc / sum(wc) # Normalised window else: n = np.linspace(-0.5, 0.5, M) wc = a + (1 - a) * np.cos(2 * pi * n) # Window coefficients m = np.arange(0, M) # Create M indeces from 0 to 1 aa = exp(-1j * 2 * pi * m * phi) # Steering vector ws = dot(wc, aa) # Normalisation factor win = aa * wc / ws # Steered and normalised window w = np.Ndarray.__new__(self, win) # axes=('M',), # desc = 'Rectangular (phi=%d)'%phi) # desc='Rectangular (phi=%d)'%phi, # shape_desc=('M','1')) return w
def setColorBar( fig, cbar_coord, # left, bottom, width, height vbounds=[-50, 0], cmap=pl.cm.YlGnBu_r, text='Dynamic Range [dBr]', custom_ticks=[], custom_ticklabels=[]): cax = fig.add_axes(cbar_coord) cax.grid(False) cax.imshow(np.linspace(1, 0, 10e3)[:, None], aspect='auto', extent=(0, 1, vbounds[0], vbounds[1]), cmap=cmap) cax.yaxis.set_ticks_position('right') cax.yaxis.set_label_position('right') cax.set_ylabel(text) pl.rcParams['text.usetex'] = True if len(custom_ticks) > 0: cax.set_yticks(custom_ticks) if len(custom_ticklabels) > 0: cax.set_yticklabels(custom_ticklabels) return cax else: db_min = vbounds[0] db_max = vbounds[1] db_diff = db_max - db_min db_step = 5 * int(db_diff / 50 + 1) db_start = int(np.floor((db_min + 500) / db_step)) * db_step - 500 db_ticks = [db_min] db_labels = ["$\le$ %d" % db_min] while True: db_start += db_step if db_start > db_max - float(db_step) / 2 + 1: break if db_start - db_min > float(db_step) / 2 - 1: db_ticks.append(db_start) db_labels.append("%d" % db_start) db_ticks.append(db_max) db_labels.append("$\ge$ %d" % db_max) cax.set_yticks(db_ticks) cax.set_yticklabels(db_labels) pl.setp(cax.get_xticklabels(), visible=False) return cax
def configure(self, conf): if conf.has_key('p'): self.type = 'custom' self.p = conf['p'] elif conf.has_key('M') and conf.has_key('d'): self.type = 'ula' self.type = type # Store type self.prop.M = conf['M'] # Number of elements self.prop.d = conf['d'] # Element distance D = conf['M']*conf['d'] # Array length self.p = linspace( -D/2, D/2, conf['M'] ) # Element positions else: print 'WW Array.configure() - Neither \'p\', \'M\', nor \'d\' was specified.'
def slicer(m, key, slices, interp_keys=None, method='linear'): result = mydas() if interp_keys is None: interp_keys = m.keys() if isinstance(interp_keys, str): interp_keys = (interp_keys,) old_index = m.__data__[key] new_index = mynumpy.linspace(min(old_index), max(old_index), slices, True) result[key] = new_index for i, k in enumerate(interp_keys): if k == key: continue result[k] = mynumpy.interp(new_index, old_index, m.__data__[k], method=method) return result
def derive_system_parameters(s): from Array import Array from Coordinate import Coordinate if s != None: if s.findAttr('p') == None: M = s.findAttr('M') d = s.findAttr('d') if (M,d) != (None,None): x = np.linspace(-0.5,0.5,M)*M*d if not 'array' in s.__dict__: s.array = Array() s.array.p = Coordinate(x=x, y=None, z=None, axes=['M',('dim',['x','y','z'])])
def process(trial_no, name): new_dir = head_dir + name + "/" f = open(new_dir + str(trial_no) + "_" + name + ".txt", "r") param_vals = [] opts = [] scores_orig = [] scores = [] beta = np.linspace(1e-3, 1, 25)[trial_no] for x in f.readline().strip().split("\t"): param_vals.append(float(x)) for x in f.readline().strip().split("\t"): opts.append(float(x)) for x in f.readline().strip().split("\t"): scores_orig.append(float(x)) for x in f.readline().strip().split("\t"): scores.append(float(x)) f.close() return beta, param_vals, opts, scores_orig, scores
def optimalLightness(npts, cmap_type, l_range=(0.0, 1.0)): """ Helper function defining the optimality condition for a colormap. Depending on the colormap this might mean different things. The l_range argument can be used to restrict the lightness range so it does have to equal the full range. """ if cmap_type == "sequential_rising": opt = np.linspace(l_range[0], l_range[1], npts) elif cmap_type == "sequential_falling": opt = np.linspace(l_range[1], l_range[0], npts) elif cmap_type == "diverging_center_top": s = npts // 2 opt = np.empty(npts) opt[:s] = np.linspace(l_range[0], l_range[1], s) opt[s:] = np.linspace(l_range[1], l_range[0], npts - s) elif cmap_type == "diverging_center_bottom": s = npts // 2 opt = np.empty(npts) opt[:s] = np.linspace(l_range[1], l_range[0], s) opt[s:] = np.linspace(l_range[0], l_range[1], npts - s) elif cmap_type == "flat": opt = np.ones(npts) * l_range[0] return opt
# #plt.scatter(new_pairs[:, 0], new_pairs[:, 1]) # #plt.errorbar(new_pairs[:, 0], new_pairs[:, 1], xerr = stdev_pairs[:,0], yerr=stdev_pairs[:,1], fmt='o', capsize = 2, elinewidth= .5) def numberToBase(n, b): if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1] if __name__ == '__main__': betas = np.linspace(1e-3, .2, 15) beta_index = 14 textbook_index = 8 #arg_1 = 0 # arg_1 = int(sys.argv[1]) - 1 # from 0 to 149 # beta_index = arg_1 % len(betas) # textbook_index = arg_1 // 15 beta = betas[beta_index] # A_0 = gg.regularized_sierpinski(3,5) # symInfo = get_pickleable_params(A_0, include_nonexistent= False, force_unique= False) # numParams, parameterized = sm.getSymReducedParams(A_0, include_nonexistent=False, force_unique=False) # betas2 = np.linspace(1e-3, 1, 150) # # outcomes = np.zeros((len(betas2), numParams)) # # scores = np.zeros((len(betas2), 2)) # # for i in range(len(betas2)):
def W(p=None, w=None, k=None, fc=100e3, c=1480, N=500): if p==None: error('\'p\' are missing. Aborting.') return if k!=None: k_abs = k elif p!=None and fc!=None and c!=None: k_abs = 2*pi*fc/c else: error('Either \'k\', or \'c\' and \'fc\' must be supplied. Aborting.') return theta = np.linspace(-0.5,0.5,N)*pi k = Coordinate(r=k_abs, theta=theta, phi=None) def compute_W(ax,ay,az, w): Wx = dot( ax, w ) Wy = dot( ay, w ) Wz = dot( az, w ) Wxyz = vstack((Wx,Wy,Wz)).T return Wxyz # pT = p.T.copy() ax = exp(1j*outer( k[:,0], p[:,0])) ay = exp(1j*outer( k[:,1], p[:,1])) az = exp(1j*outer( k[:,2], p[:,2])) if type(w) == list: W = [] for wi in w: W.append(compute_W(ax,ay,az, wi)) elif is_np_array_type(w.__class__): if w.ndim == 1: W = [] W.append( compute_W(ax,ay,az,w) ) elif w.ndim == 2: W1 = compute_W(ax,ay,az,w[0]) W = np.zeros((w.shape[0],W1.shape[0],W1.shape[1]),dtype=W1.dtype) W[0] = W1 for i in range(1,w.shape[0]): W[i] = compute_W(ax,ay,az, w[i]) elif w.ndim == 3: W1 = compute_W(ax,ay,az,w[0,0]) # Not exactly efficient, but shouldn't be noticeable W = np.zeros((w.shape[0],w.shape[1],W1.shape[0],W1.shape[1]),dtype=W1.dtype) for i in range(0,w.shape[0]): for j in range(0,w.shape[1]): W[i,j] = compute_W(ax,ay,az, w[i,j]) else: print 'EE: Not implemented.' else: W = [] W.append( compute_W(ax,ay,az,w) ) return W
for j in range(4): f.readline() x_parts = f.readline().split(" ") y_parts = f.readline().split(" ") x_coord = float(x_parts[-1][:-2]) y_coord = float(y_parts[-1][:-1]) output[currID].append(x_coord) output[currID].append(y_coord) for j in range(3): f.readline() return output if __name__ == '__main__': betas = np.linspace(1e-3, 1, 25) num_betas = 8 name = 'mod' x = np.ones((num_betas, 3)) y = np.ones((num_betas, 3)) # blue to purple, use 8 x[:, 0:3] = (0, .5, .5) y[:, 0:3] = (.5, 0, .5) # green to orange, use 6 # x[:, 0:3] = (0, .5, 0) # y[:, 0:3] = (1, .5, 0) #sw colorscheme # x[:, 0:3] = (.75, .25, 0) # y[:, 0:3] = (0, .75, .5)
def getWindow( image, tx_coords, # x,y tx_angle, # radians img_coords, # x_min, x_max, y_min, y_max width=0.8, scale=1): Nx, Ny = image.shape N = Nx img_width = img_coords[1] - img_coords[0] img_length = img_coords[3] - img_coords[2] x_mean = np.mean(img_coords[0:2]) y_mean = np.mean(img_coords[2:4]) dx = float(img_width) / Nx dy = float(img_length) / Ny image_window = np.ones(image.shape) x_old = np.zeros(N) x_new = np.zeros(N) # tx_img_range = img_coords[2] r = img_coords[2] + dy / 2 has_overflowed = False for row in range(Ny): row_data = image_window[:, row] x_cut = r * np.sin(tx_angle / 2) # x_cut_rel = x_cut / extent[0] # w_idx = np.linspace(0,1,N) x_old[:] = np.linspace(x_mean - (2 - width) * x_cut, x_mean + (2 - width) * x_cut, N) #*0.5/img_width + 0.5 x_new[:] = np.linspace(img_coords[0], img_coords[1], Nx) #*0.5/img_width + 0.5 up = x_new[x_new > x_old[0]] updown = up[up <= x_old[-1]] # print(x_cut, updown.shape[0]) Nlower = Nx - up.shape[0] Nhigher = Nx - updown.shape[0] - Nlower transition = (0.5 + 0.5 * np.cos( np.linspace(0, np.pi, int(Nx * width * x_cut / (2 * img_width))))) * scale + (1 - scale) # fn = None # if row == 0: # fn = pl.figure() # ax = fn.add_subplot(121) # ax.plot(transition) Nt = transition.shape[0] if N <= 2 * Nt: w = np.ones(N) has_overflowed = True else: w = np.hstack( (2 - scale - transition, np.ones(N - 2 * Nt), transition)) w_new_center = np.interpolate1D(x_old, w, updown, kind='linear', fill_value=1 - scale) w_new = np.hstack((np.ones(Nlower) * (1 - scale), w_new_center, np.ones(Nhigher) * (1 - scale))) image_window[:, row] = w_new # if row == 0: # ax = fn.add_subplot(122) # ax.plot(w_new) # fn.savefig('test2.eps') r = r + dy if has_overflowed: print("WARNING: Not making a window") return image_window
def setColorBar(self, clims, cbar_coord=None, text='Dynamic Range [dBr]', thresholded=[True, True], custom_ticks=[], custom_ticklabels=[]): cbar_coord = [ 1.0 - self.cbar_width - self.rmargin, self.bmargin, self.cbar_width, self.drawable_height ] self.cax = self.fig.add_axes(cbar_coord) self.cax.grid(False) self.cax.imshow(np.linspace(1, 0, 10e3)[:, None], aspect='auto', extent=(0, 1, clims[0], clims[1]), cmap=self.plot_colormap) self.cax.yaxis.set_ticks_position('right') self.cax.yaxis.set_label_position('right') self.cax.set_ylabel(text) pl.setp(self.cax.get_xticklabels(), visible=False) pl.rcParams['text.usetex'] = True if len(custom_ticks) > 0: self.cax.set_yticks(custom_ticks) if len(custom_ticklabels) > 0: self.cax.set_yticklabels(custom_ticklabels) return self.cax else: db_min = self.plot_vbounds[0] db_max = self.plot_vbounds[1] # db_min = "$\le$ %d"%db_min # db_max = "$\ge$ %d"%db_max db_diff = db_max - db_min db_step = 5 * int(db_diff / 50 + 1) db_start = int(np.floor((db_min + 500) / db_step)) * db_step - 500 db_ticks = [db_min] if thresholded[0]: db_labels = ["$\le$ %d" % db_min] else: db_labels = ["%d" % db_min] while True: db_start += db_step if db_start > db_max - float(db_step) / 2 + 1: break if db_start - db_min > float(db_step) / 2 - 1: db_ticks.append(db_start) db_labels.append("%d" % db_start) db_ticks.append(db_max) if thresholded[1]: db_labels.append("$\ge$ %d" % db_max) else: db_labels.append("%d" % db_max) # db_labels = ["%s" % item for item in self.cax.get_yticks()] # [item.get_text() for item in cax.get_yticklabels()] # db_labels[0] = '$\le$ %d'%self.plot_vbounds[0] self.cax.set_yticks(db_ticks) self.cax.set_yticklabels(db_labels)