def test_pcte_f2py(self): """ test solve_pcte_f2py""" N = 128; Yp = 0.24; z=3.0 fcA_H2 = fcA_He2 = fcA_He3 = 0.0 nH = np.linspace( 1.0e-4, 1.0e-3, N ) / ra.U.cm**3 nHe = nH * 0.25 * Yp / (1-Yp) T = np.linspace( 1.0e4, 1.0e5, N ) * ra.U.K hmr = ra.uv_bgnd.HM12_Photorates_Table() H1i = np.ones(N) * hmr.H1i(z) He1i = np.ones(N) * hmr.He1i(z) He2i = np.ones(N) * hmr.He2i(z) kchem = ra.atomic.ChemistryRates( T, fcA_H2, fcA_He2, fcA_He3, H1i=H1i, He1i=He1i, He2i=He2i ) H1h = np.ones(N) * hmr.H1h(z) He1h = np.ones(N) * hmr.He1h(z) He2h = np.ones(N) * hmr.He2h(z) kcool = ra.atomic.CoolingRates( T, fcA_H2, fcA_He2, fcA_He3, H1h=H1h, He1h=He1h, He2h=He2h ) x_pcte = ra.f2py.Solve_PCTE( nH, nHe, kchem, kcool, z ) y = ( x_pcte.He2 + 2 * x_pcte.He3 ) * nHe / nH xH1 = H.analytic_soltn_xH1( nH, y, x_pcte.kchem ) err = np.abs( (x_pcte.H1 - xH1) / xH1 ) ok = not np.any( err > TOL ) self.assertTrue( ok )
def get_grid_from_gid(gid, rotated=False): Ni = codes.codes_get(gid, 'Ni') Nj = codes.codes_get(gid, 'Nj') lat_start = codes.codes_get(gid, 'latitudeOfFirstGridPointInDegrees') lon_start = codes.codes_get(gid, 'longitudeOfFirstGridPointInDegrees') lat_stop = codes.codes_get(gid, 'latitudeOfLastGridPointInDegrees') lon_stop = codes.codes_get(gid, 'longitudeOfLastGridPointInDegrees') print("LL: ({0},{1})".format(lon_start, lat_start)) print("UR: ({0},{1})".format(lon_stop, lat_stop)) lat_sp = codes.codes_get(gid, 'latitudeOfSouthernPole') lon_sp = codes.codes_get(gid, 'longitudeOfSouthernPole') ang_rot = codes.codes_get(gid, 'angleOfRotation') print("SP: ({0},{1}) - Ang:{2}".format(lon_sp, lat_sp, ang_rot)) # create grid arrays from grid details # iarr, jarr one-dimensional data iarr = np.linspace(lon_start, lon_stop, num=Ni, endpoint=False) jarr = np.linspace(lat_start, lat_stop, num=Nj, endpoint=False) # converted by meshgrid to 2d-arrays i2d, j2d = np.meshgrid(iarr, jarr) grid_rot = np.dstack((i2d, j2d)) if not rotated: return rotated_grid_transform(grid_rot, 1, [lon_sp, lat_sp]) else: return grid_rot
def _setup_rank1(self): # a.size should be greated than b.size for the tests a = np.linspace(0, 3, 4).astype(self.dt) b = np.linspace(1, 2, 2).astype(self.dt) y_r = np.array([0, 2, 5, 8, 3]).astype(self.dt) return a, b, y_r
def test_pce_f2py(self): """ test solve_pce_f2py """ N = 128; Yp = 0.24; Nrho = NT = N; z=3.0 T = np.linspace( 1.0e4, 1.0e5, NT ) * ra.U.K fcA_H2 = 1.0; fcA_He2 = 1.0; fcA_He3 = 1.0 hmr = ra.uv_bgnd.HM12_Photorates_Table() H1i = np.ones(N) * hmr.H1i(z) He1i = np.ones(N) * hmr.He1i(z) He2i = np.ones(N) * hmr.He2i(z) kchem = ra.atomic.ChemistryRates( T, fcA_H2, fcA_He2, fcA_He3, H1i=H1i, He1i=He1i, He2i=He2i ) nH = np.linspace( 1.0e-4, 1.0e-3, Nrho ) / ra.U.cm**3 nHe = nH * 0.25 * Yp / (1-Yp) x_pce_1D = ra.f2py.Solve_PCE( nH, nHe, kchem ) y = ( x_pce_1D.He2 + 2 * x_pce_1D.He3 ) * nHe / nH xH1 = H.analytic_soltn_xH1( nH, y, kchem ) err = np.abs( (x_pce_1D.H1 - xH1) / xH1 ) ok = not np.any( err > TOL ) self.assertTrue( ok )
def _setup_rank3(self): a = np.linspace(0, 39, 40).reshape((2, 4, 5), order='F').astype(self.dt) b = np.linspace(0, 23, 24).reshape((2, 3, 4), order='F').astype(self.dt) y_r = array([[[ 0., 184., 504., 912., 1360., 888., 472., 160.,], [ 46., 432., 1062., 1840., 2672., 1698., 864., 266.,], [ 134., 736., 1662., 2768., 3920., 2418., 1168., 314.,], [ 260., 952., 1932., 3056., 4208., 2580., 1240., 332.,] , [ 202., 664., 1290., 1984., 2688., 1590., 712., 150.,] , [ 114., 344., 642., 960., 1280., 726., 296., 38.,]], [[ 23., 400., 1035., 1832., 2696., 1737., 904., 293.,], [ 134., 920., 2166., 3680., 5280., 3306., 1640., 474.,], [ 325., 1544., 3369., 5512., 7720., 4683., 2192., 535.,], [ 571., 1964., 3891., 6064., 8272., 4989., 2324., 565.,], [ 434., 1360., 2586., 3920., 5264., 3054., 1312., 230.,], [ 241., 700., 1281., 1888., 2496., 1383., 532., 39.,]], [[ 22., 214., 528., 916., 1332., 846., 430., 132.,], [ 86., 484., 1098., 1832., 2600., 1602., 772., 206.,], [ 188., 802., 1698., 2732., 3788., 2256., 1018., 218.,], [ 308., 1006., 1950., 2996., 4052., 2400., 1078., 230.,], [ 230., 692., 1290., 1928., 2568., 1458., 596., 78.,], [ 126., 354., 636., 924., 1212., 654., 234., 0.,]]], dtype=self.dt) return a, b, y_r
def solve(initial_conds, radius, num_r, constant, timescale): # Grid points in space r, dr = np.linspace(0, radius, num_r+1, retstep=True) # Grid points in time dt = 0.1 Nt = int(round(timescale/float(dt))) t = np.linspace(0, timescale, Nt+1) surfd = np.zeros(num_r+1) surfd_1 = np.zeros(num_r+1) # Set up initial condition for i in range(0, num_r+1): surfd_1[i] = initial_conds(r[i]) for j in range(0, len(t)): for n in range(1, num_r): surfd[n] = surfd_1[n] + (3*constant*dt/r[n])*(((r[n+1]**0.5 - \ r[n]**0.5)/dr) *(surfd_1[n+1]*r[n+1]**2 - 2*(surfd_1[n]*r[n]**1) \ + surfd_1[n-1]*r[n-1]**2)) # Insert boundary conditions surfd[0] = 0.087 surfd[num_r] = 0 # Switch variables before next step surfd_1, surfd = surfd, surfd_1 return surfd_1, r, t
def hex_cube(x0, x1, y0, y1, z0, z1, Mx, My, Mz): """Creates a uniform hexahedral Q1 mesh covering [x0,x1]*[y0,y1]*[z0,z1].""" x = np.linspace(x0, x1, Mx) y = np.linspace(y0, y1, My) z = np.linspace(z0, z1, Mz) def ii(i, j, k): return (Mx*My)*k + (j*Mx + i) pts = np.zeros((Mx*My*Mz, 3), dtype='f8') for k in xrange(Mz): for j in xrange(My): for i in xrange(Mx): pts[ii(i,j,k), :] = (x[i], y[j], z[k]) hexes = np.zeros(((Mx-1)*(My-1)*(Mz-1), 8), dtype='i') n = 0 for k in xrange(Mz-1): for j in xrange(My-1): for i in xrange(Mx-1): hexes[n] = [ii(i,j,k), ii(i+1,j,k), ii(i+1,j+1,k), ii(i,j+1,k), ii(i,j,k+1), ii(i+1,j,k+1), ii(i+1,j+1,k+1), ii(i,j+1,k+1)] n += 1 return x, y, z, pts, hexes
def grid_xyz(xyz, n_x, n_y, **kwargs): """ Grid data as a list of X,Y,Z coords into a 2D array Parameters ---------- xyz: np.array Numpy array of X,Y,Z values, with shape (n_points, 3) n_x: int Number of points in x direction (fastest varying!) n_y: int Number of points in y direction Returns ------- gridded_data: np.array 2D array of gridded data, with shape (n_x, n_y) Notes ----- 'x' is the inner dimension, i.e. image dimensions are (n_y, n_x). This is counterintuitive (to me at least) but in line with numpy definitions. """ x, y, z = xyz[:, 0], xyz[:, 1], xyz[:, 2] x_ax = np.linspace(np.min(x), np.max(x), n_x) y_ax = np.linspace(np.min(y), np.max(y), n_y) xg, yg = np.meshgrid(x_ax, y_ax) data = griddata(xyz[:, :2], z, (xg, yg), **kwargs) return data
def plotISVar(): plt.figure() plt.title('Variance minimization problem (call).\nVertical lines mark the minima.') for K in [0.6, 0.8, 1.0, 1.2]: theta = np.linspace(-0.6, 2) var = [BS.exactCallVar(K*s0, theta) for theta in theta] minth = theta[np.argmin(var)] line, = plt.plot(theta, var, label=str(K)) plt.axvline(minth, color=line.get_color()) plt.xlabel(r'$\theta$') plt.ylabel('call variance') plt.legend(title=r'$K/s_0$', loc='upper left') plt.autoscale(tight=True) plt.figure() plt.title('Variance minimization problem (put).\nVertical lines mark the minima.') for K in [0.8, 1.0, 1.2, 1.4]: theta = np.linspace(-2, 0.5) var = [BS.exactPutVar(K*s0, theta) for theta in theta] minth = theta[np.argmin(var)] line, = plt.plot(theta, var, label=str(K)) plt.axvline(minth, color=line.get_color()) plt.xlabel(r'$\theta$') plt.ylabel('put variance') plt.legend(title=r'$K/s_0$', loc='upper left') plt.autoscale(tight=True)
def graph(f, n, xmin, xmax, resolution=1001): xlist = np.linspace(xmin, xmax, n) ylist = f(xlist) xlist_fine = np.linspace(xmin, xmax, resolution) ylist_fine = p_L(xlist_fine, xlist, ylist) plt.plot(xlist, ylist, 'ro') plt.plot(xlist_fine, ylist_fine)
def mpl_palette(name, n_colors=6): """Return discrete colors from a matplotlib palette. Note that this handles the qualitative colorbrewer palettes properly, although if you ask for more colors than a particular qualitative palette can provide you will fewer than you are expecting. Parameters ---------- name : string name of the palette n_colors : int number of colors in the palette Returns ------- palette : list of tuples palette colors in r, g, b format """ brewer_qual_pals = {"Accent": 8, "Dark2": 8, "Paired": 12, "Pastel1": 9, "Pastel2": 8, "Set1": 9, "Set2": 8, "Set3": 12} cmap = getattr(mpl.cm, name) if name in brewer_qual_pals: bins = np.linspace(0, 1, brewer_qual_pals[name])[:n_colors] else: bins = np.linspace(0, 1, n_colors + 2)[1:-1] palette = list(map(tuple, cmap(bins)[:, :3])) return palette
def test_known_parametrization(): R = 1 P = 1 toll = 2.e-3 n = 10 ii = np.linspace(0,1,n+1) control_points_3d = np.asarray(np.zeros([n+1,3]))#[np.array([R*np.cos(5*i * np.pi / (n + 1)), R*np.sin(5*i * np.pi / (n + 1)), P * i]) for i in range(0, n+1)] print (control_points_3d.shape) control_points_3d[:,0] = np.array([R*np.cos(5*i * np.pi / (n + 1))for i in ii]) control_points_3d[:,1] = np.array([R*np.sin(5*i * np.pi / (n + 1))for i in ii]) control_points_3d[:,2] = np.array([P*i for i in range(n+1)]) vsl = AffineVectorSpace(UniformLagrangeVectorSpace(n+1),0,1) arky = ArcLengthParametrizer(vsl, control_points_3d) new_control_points_3d = arky.reparametrize() #new_arky = ArcLengthParametrizer(vsl, new_control_points_3d) #new_new_control_points_3d = arky.reparametrize() tt = np.linspace(0, 1, 128) vals = vsl.element(control_points_3d)(tt) #print vals new_vals = vsl.element(new_control_points_3d)(tt) #print vals.shape, new_vals.shape print (np.amax((np.abs(vals-new_vals)))) assert np.amax(np.abs(control_points_3d-new_control_points_3d))/P < toll
def test_more_known_parametrization_together(): R = 1 P = 1 toll = 7.e-3 intervals = 5 vs_order = 2 n = (intervals*(vs_order)+1-1) #n = 18 ii = np.linspace(0,1,n+1) n_1 = 2 n_2 = 4 control_points_3d = np.asarray(np.zeros([n+1,n_1,n_2,3]))#[np.array([R*np.cos(5*i * np.pi / (n + 1)), R*np.sin(5*i * np.pi / (n + 1)), P * i]) for i in range(0, n+1)] for k in range(n_1): for j in range(n_2): control_points_3d[:,k,j,0] = np.array([R*np.cos(5*i * np.pi / (n + 1))for i in ii]) control_points_3d[:,k,j,1] = np.array([R*np.sin(5*i * np.pi / (n + 1))for i in ii]) control_points_3d[:,k,j,2] = np.array([(k+j+1)*P*i for i in range(n+1)]) #vsl = IteratedVectorSpace(UniformLagrangeVectorSpace(vs_order+1), np.linspace(0,1,intervals+1)) vsl = AffineVectorSpace(UniformLagrangeVectorSpace(n+1),0,1) arky = ArcLengthParametrizer(vsl, control_points_3d) new_control_points_3d = arky.reparametrize() #print control_points_3d.shape, new_control_points_3d.shape tt = np.linspace(0,1,128) for k in range(n_1): for j in range(n_2): vals = vsl.element(control_points_3d)(tt) new_vals = vsl.element(new_control_points_3d)(tt) print (np.amax(np.abs(vals-new_vals))/(k+j+1)/P, (k+j+1)) assert np.amax(np.abs(vals-new_vals))/(k+j+1)/P < toll
def color_cycle_example(ax): L = 6 x = np.linspace(0, L) ncolors = len(plt.rcParams['axes.prop_cycle']) shift = np.linspace(0, L, ncolors, endpoint=False) for s in shift: ax.plot(x, np.sin(x + s), 'o-')
def test_BadBCDerivativesNoParam(): problem = scikits.bvp_solver.ProblemDefinition(num_ODE = 1, num_parameters =0, num_left_boundary_conditions = 1, boundary_points = (-numpy.pi/2.0, numpy.pi/2.0), function = functionNoParamGood, boundary_conditions = boundary_conditionsNoParamGood, function_derivative = dfunctionNoParamGood, boundary_conditions_derivative = dbconditionsNoParamBad1) nose.tools.assert_raises(ValueError, scikits.bvp_solver.solve, problem, solution_guess = 0, initial_mesh = numpy.linspace(problem.boundary_points[0],problem.boundary_points[1], 21)) problem2 = scikits.bvp_solver.ProblemDefinition(num_ODE = 1, num_parameters =0, num_left_boundary_conditions = 0, boundary_points = (-numpy.pi/2.0, numpy.pi/2.0), function = functionNoParamGood, boundary_conditions = boundary_conditionsNoParamGood2, function_derivative = dfunctionNoParamGood, boundary_conditions_derivative = dbconditionsNoParamBad2) nose.tools.assert_raises(ValueError, scikits.bvp_solver.solve, problem2, solution_guess = 0, initial_mesh = numpy.linspace(problem2.boundary_points[0],problem2.boundary_points[1], 21))
def testFunctionCallInDifferentVariableScopes(self): @function.Defun(dtypes.float32) def Foo(inputs): var = variable_scope.get_variable( "var", shape=[10], dtype=dtypes.float32, initializer=init_ops.ones_initializer()) return inputs + var input_op = array_ops.placeholder(shape=[10], dtype=dtypes.float32) with variable_scope.variable_scope("vs1"): out1_op = Foo(input_op) with variable_scope.variable_scope("vs2"): out2_op = Foo(input_op) global_vars = variables.global_variables() self.assertEqual(len(global_vars), 1) self.assertEqual(global_vars[0].name, "vs1/var:0") with session.Session() as sess: sess.run(variables.global_variables_initializer()) out1, out2 = sess.run( [out1_op, out2_op], feed_dict={input_op: np.linspace(1, 10, 10)}) self.assertAllEqual(out1, np.linspace(2, 11, 10)) self.assertAllEqual(out2, np.linspace(2, 11, 10))
def mesh(npts=(101, 101), closed=False): """Generate a meshgrid on the unit sphere. Uniformly sample the polar angle, theta, and the azimuthal angle, phi. Parameters ---------- npts : int or tuple Number of angle points sampled. closed : bool Whether to generate an open mesh (like `np.ogrid`) or a closed mesh like `np.mgrid` or `np.meshgrid`. By default, an open grid is generated. Returns ------- theta, phi : (N,) or (N,M) ndarray Sampling of the polar angle. Shape depends on ``open``. """ if np.isscalar(npts): npts = (npts, npts) theta = np.linspace(0, np.pi, npts[0])[:, None] phi = np.linspace(0, 2 * np.pi, npts[1]) if open: return theta, phi else: mg_phi, mg_theta = np.meshgrid(phi_grid, theta_grid) return mg_theta, mg_phi
def get_synthetic_data_dict(self): data_dict = {} data_dict['x'] = np.linspace(-70, 470, 200) data_dict['y'] = np.linspace(10, 340, 100) data_dict['z'] = np.array([-0, -3, -10, -25, -100]) # Make a horizontal slice xg, yg = np.meshgrid(data_dict['x'], data_dict['y']) slice1 = np.ma.array(np.cos(np.radians(xg)) + np.sin(np.radians(yg))) # Add some holes slice1[0:40, 50:60] = np.nan slice1[40:60, 100:120] = np.nan slice1[20:22, 30:32] = np.nan slice1 = np.ma.masked_invalid(slice1) # Make another horizontal slice ("below") with more holes slice2 = slice1*1.1 slice2[70:80, 20:28] = np.nan # Add a 2D and a 3D variable to dictionary data_dict['var2d'] = slice1 data_dict['var3d'] = np.ma.array([slice1, slice2, 1.2*slice1, 1*3*slice1, 10*slice1]) data_dict['time'] = datetime.now() # Generate some points x = np.linspace(data_dict['x'].min(), data_dict['x'].max(), 100) y = np.linspace(data_dict['y'].min(), data_dict['y'].max(), 100) z = np.linspace(data_dict['z'].min(), data_dict['z'].max(), 100) return data_dict, x, y, z
def visualize(u1, t1, u2, t2, U, omega): plt.figure(1) plt.plot(t1, u1, 'r--o') t_fine = np.linspace(0, t1[-1], 1001) # мелкая сетка для точного решения u_e = u_exact(t_fine, U, omega) plt.hold('on') plt.plot(t_fine, u_e, 'b-') plt.legend([u'приближенное', u'точное'], loc='upper left') plt.xlabel('$t$') plt.ylabel('$u$') tau = t1[1] - t1[0] plt.title('$\\tau = $ %g' % tau) umin = 1.2*u1.min(); umax = -umin plt.axis([t1[0], t1[-1], umin, umax]) plt.savefig('tmp1.png'); plt.savefig('tmp1.pdf') plt.figure(2) plt.plot(t2, u2, 'r--o') t_fine = np.linspace(0, t2[-1], 1001) # мелкая сетка для точного решения u_e = u_exact(t_fine, U, omega) plt.hold('on') plt.plot(t_fine, u_e, 'b-') plt.legend([u'приближенное', u'точное'], loc='upper left') plt.xlabel('$t$') plt.ylabel('$u$') tau = t2[1] - t2[0] plt.title('$\\tau = $ %g' % tau) umin = 1.2 * u2.min(); umax = -umin plt.axis([t2[0], t2[-1], umin, umax]) plt.savefig('tmp2.png'); plt.savefig('tmp2.pdf')
def test_parse_spot_request(self): tests = [('spot:20S,154W|4,3', {'location': {'latitude': -20., 'longitude':-154.}, 'model': 'gfs', 'type': 'spot', 'send-image': False, 'hours': np.linspace(0, 96, 33).astype('int'), 'vars': ['wind'], 'warnings': ['No variable requested, defaulting to WIND']}), ('spot: 20S,154W |4 ,3', {'location': {'latitude': -20., 'longitude':-154.}, 'model': 'gfs', 'send-image': False, 'type': 'spot', 'hours': np.linspace(0, 96, 33).astype('int'), 'vars': ['wind'], 'warnings': ['No variable requested, defaulting to WIND']}), ('spot:20S,154W|4,3|wind|image', {'location': {'latitude': -20., 'longitude':-154.}, 'model': 'gfs', 'type': 'spot', 'send-image': True, 'hours': np.linspace(0, 96, 33).astype('int'), 'vars': ['wind'], 'warnings': []}), ] for request, expected in tests: self.maxDiff = 3000 actual = saildocs.parse_spot_request(request) np.testing.assert_array_equal(actual.pop('hours'), expected.pop('hours')) self.assertDictEqual(actual, expected)
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6): """ Customized visualization of jacobian matrices for observing sparsity patterns """ plt.figure() fig, ax = plt.subplots() if normalize is True: plt.imshow(A, interpolation='none', cmap=cmap, norm = mpl.colors.Normalize(vmin=-1.,vmax=1.)) else: plt.imshow(A, interpolation='none', cmap=cmap) plt.colorbar(format=ticker.FuncFormatter(fmt)) ax.spy(A, marker='.', markersize=0, precision=precision) ax.spines['right'].set_visible(True) ax.spines['bottom'].set_visible(True) ax.xaxis.set_ticks_position('top') ax.yaxis.set_ticks_position('left') xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int) ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int) plt.xticks(xlabels) plt.yticks(ylabels) plt.savefig(name, bbox_inches='tight', pad_inches=0.05) plt.close() return
def disc_norm(): x = np.linspace(-3,3,100) y = st.norm.pdf(x,0,1) fig, ax = plt.subplots() fig.canvas.draw() ax.plot(x,y) fill1_x = np.linspace(-2,-1.5,100) fill1_y = st.norm.pdf(fill1_x,0,1) fill2_x = np.linspace(-1.5,-1,100) fill2_y = st.norm.pdf(fill2_x,0,1) ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75) ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75) for label in ax.get_yticklabels(): label.set_visible(False) for tick in ax.get_xticklines(): tick.set_visible(False) for tick in ax.get_yticklines(): tick.set_visible(False) plt.rc("font", size = 16) plt.xticks([-2,-1.5,-1]) labels = [item.get_text() for item in ax.get_xticklabels()] labels[0] = r"$v_k$" labels[1] = r"$\varepsilon_k$" labels[2] = r"$v_{k+1}$" ax.set_xticklabels(labels) plt.ylim([0, .45]) plt.savefig('discnorm.pdf') plt.clf()
def test_cmac(self): input_train = np.reshape(np.linspace(0, 2 * np.pi, 100), (100, 1)) input_train_before = input_train.copy() input_test = np.reshape(np.linspace(np.pi, 2 * np.pi, 50), (50, 1)) input_test_before = input_test.copy() target_train = np.sin(input_train) target_train_before = target_train.copy() target_test = np.sin(input_test) cmac = algorithms.CMAC( quantization=100, associative_unit_size=32, step=0.2, verbose=False, ) cmac.train(input_train, target_train, epochs=100) predicted_test = cmac.predict(input_test) predicted_test = predicted_test.reshape((len(predicted_test), 1)) error = metrics.mean_absolute_error(target_test, predicted_test) self.assertAlmostEqual(error, 0.0024, places=4) # Test that algorithm didn't modify data samples np.testing.assert_array_equal(input_train, input_train_before) np.testing.assert_array_equal(input_train, input_train_before) np.testing.assert_array_equal(target_train, target_train_before)
def allowed_region( V_nj, ave_j ): # read PCs PC1 = V_nj[0] PC2 = V_nj[1] n_band = len( PC1 ) band_ticks = np.arange( n_band ) x_ticks = np.linspace(-0.4,0.2,RESOLUTION) y_ticks = np.linspace(-0.2,0.4,RESOLUTION) x_mesh, y_mesh, band_mesh = np.meshgrid( x_ticks, y_ticks, band_ticks, indexing='ij' ) vec_mesh = x_mesh * PC1[ band_mesh ] + y_mesh * PC2[ band_mesh ] + ave_j[ band_mesh ] x_grid, y_grid = np.meshgrid( x_ticks, y_ticks, indexing='ij' ) prohibited_grid = np.zeros_like( x_grid ) for ii in xrange( len( x_ticks ) ) : for jj in xrange( len( y_ticks ) ) : if np.any( vec_mesh[ii][jj] < 0. ) : prohibited_grid[ii][jj] = 1 if np.any( vec_mesh[ii][jj] > 1. ) : prohibited_grid[ii][jj] = 3 elif np.any( vec_mesh[ii][jj] > 1. ) : prohibited_grid[ii][jj] = 2 else : prohibited_grid[ii][jj] = 0 return x_grid, y_grid, prohibited_grid
def make_let_im(let_file, dim = 16, y_lo = 70, y_hi = 220, x_lo = 10, x_hi = 200, edge_pix = 150, plot_let = False): letter = mpimg.imread(let_file) letter = letter[y_lo:y_hi, x_lo:x_hi, 0] for i in range(letter.shape[1]): if letter[0:edge_pix, i].any() == 0: # here is to remove the edge letter[0:edge_pix, i] = 1 plt.imshow(letter, cmap='gray') plt.grid('off') plt.show() x = np.arange(letter.shape[1]) y = np.arange(letter.shape[0]) f2d = interp2d(x, y, letter) x_new = np.linspace(0, letter.shape[1], dim) # dim = 16 y_new = np.linspace(0, letter.shape[0], dim) letter_new = f2d(x_new, y_new) letter_new -= np.mean(letter_new) if plot_let: plt.imshow(letter_new, cmap = 'gray') plt.grid('off') plt.show() letter_flat = letter_new.flatten() # letter_flat is a 1-dimensional array containing 256 elements return letter_new, letter_flat
def all_GL(self, q, maxpiv=None): """return (piv, f_binodal_gas, f_binodal_liquid, f_spinodal_gas, f_spinodal_liquid) at insersion works piv sampled between the critical point and maxpiv (default to 2.2*critical pressure)""" fc, pivc = self.critical_point(q) Fc = np.log(fc) #start sensibly above the critical point startp = pivc*1.1 fm = fminbound(self.mu, fc, self.maxf(), args=(startp, q)) fM = fminbound(lambda f: -self.pv(f, startp, q), 0, fc) initial_guess = np.log([0.5*fM, 0.5*(fm+self.maxf())]) #construct the top of the GL binodal if maxpiv is None: maxpiv = startp*2 topp = 1./np.linspace(1./startp, 1./maxpiv) topGL = [initial_guess] for piv in topp: topGL.append(self.binodalGL(piv, q, topGL[-1])) #construct the GL binodal between the starting piv and the critical point botp = np.linspace(startp, pivc)[:-1] botGL = [initial_guess] for piv in botp: botGL.append(self.binodalGL(piv, q, botGL[-1])) #join the two results and convert back from log binodal = np.vstack(( [[pivc, fc, fc]], np.column_stack((botp, np.exp(botGL[1:])))[::-1], np.column_stack((topp, np.exp(topGL[1:])))[1:] )) #spinodal at the same pivs spinodal = self.spinodalGL(q, binodal[:,0]) #join everything return np.column_stack((binodal, spinodal[:,1:]))
def normalize_input(params): if pc_id == 0: print 'normalize_input' dt = params['dt_rate'] # [ms] time step for the non-homogenous Poisson process L_input = np.zeros((params['n_exc'], params['t_stimulus']/dt)) v_max = params['v_max'] if params['log_scale']==1: v_rho = np.linspace(v_max/params['N_V'], v_max, num=params['N_V'], endpoint=True) else: v_rho = np.logspace(np.log(v_max/params['N_V'])/np.log(params['log_scale']), np.log(v_max)/np.log(params['log_scale']), num=params['N_V'], endpoint=True, base=params['log_scale']) v_theta = np.linspace(0, 2*np.pi, params['N_theta'], endpoint=False) index = 0 for i_RF in xrange(params['N_RF_X']*params['N_RF_Y']): index_start = index for i_v_rho, rho in enumerate(v_rho): for i_theta, theta in enumerate(v_theta): fn = params['input_rate_fn_base'] + str(index) + '.dat' L_input[index, :] = np.loadtxt(fn) print 'debug', fn index += 1 index_stop = index print 'before', i_RF, L_input[index_start:index_stop, :].sum() if (L_input[index_start:index_stop, :].sum() > 1): L_input[index_start:index_stop, :] /= L_input[index_start:index_stop, :].sum() print 'after', i_RF, L_input[index_start:index_stop, :].sum() for i in xrange(params['n_exc']): output_fn = params['input_rate_fn_base'] + str(i) + '.dat' print 'output_fn:', output_fn np.savetxt(output_fn, L_input[i, :]) if comm != None: comm.barrier()
def plot_mle_graph(function, mle_params, x_start=eps, x_end=1 - eps, y_start=eps, y_end=1 - eps, resolution=100, x_label="x", y_label="y", show_constraint=False, show_optimum=False): x = np.linspace(x_start, x_end, resolution) y = np.linspace(y_start, y_end, resolution) xx, yy = np.meshgrid(x, y) np_func = np.vectorize(lambda x, y: function(x, y)) z = np_func(xx, yy) optimal_loss = function(*mle_params) levels_before = np.arange(optimal_loss - 3.0, optimal_loss, 0.25) levels_after = np.arange(optimal_loss, min(optimal_loss + 2.0, -0.1), 0.25) fig = plt.figure() contour = plt.contour(x, y, z, levels=np.concatenate([levels_before, levels_after])) plt.xlabel(x_label) plt.ylabel(y_label) if show_constraint: plt.plot(x, 1 - x) if show_optimum: plt.plot(mle_params[0], mle_params[1], 'ro') plt.clabel(contour) return mpld3.display(fig)
def simulate(): # Plotting the PDF of Unif(0, 1) pyplot.subplot(211) x = np.linspace(stats.uniform.ppf(0), stats.uniform.ppf(1), 100) pyplot.title('PDF of Unif(0, 1)') pyplot.plot(x, stats.uniform.pdf(x)) print("Xn is for n=1000: ", get_xn(1000)) E_Xn = 0.5 # As we know, E(Xn) is equal to mu which is 0.5 print("E(Xn) is : ", E_Xn) n = np.linspace(1, 1000, 1000) X_ns = [] for i in range(1, 1001): X_ns.append(get_xn(i)) pyplot.subplot(212) pyplot.title('f(n,Xn)') pyplot.plot(n, X_ns, '-g') print("Xn for n=1", get_xn(1)) print("Xn for n=5", get_xn(5)) print("Xn for n=25", get_xn(25)) print("Xn for n=100", get_xn(100)) pyplot.show()
def get_nxnyr_cd(): box = cfg.pms['shape'] boxMpc = np.array([cfg.pms['xyMpc'],cfg.pms['xyMpc'],cfg.pms['zMpc']]) lx = boxMpc[0]/2.; ly = boxMpc[1]/2.; lz = boxMpc[2] z,d = get_z_d(cfg.pms['zi'],cfg.pms['zf']) # front of box -- don't use bc grid will extend # outside the standard box # nx_max = lx / np.sqrt(lx*lx+d[0]*d[0]) # nx_min = - nx_max # ny_max = ly / np.sqrt(ly*ly+d[0]*d[0]) # ny_min = - ny_max # r_max = np.sqrt(lx*lx+ly*ly+(d[0]+lz)*(d[0]+lz)) # r_min = d[0] # back of box -- throws away half the box but whatever df = d[0]+lz nx_max = lx / np.sqrt(lx*lx+df*df) # nx_min = - nx_max ny_max = ly / np.sqrt(ly*ly+df*df) # ny_min = - ny_max r_max = np.sqrt(lx*lx+ly*ly+df*df) # r_min = d[0] print nx_max, ny_max nxcd = np.linspace(-nx_max,nx_max,box[0]) nycd = np.linspace(-ny_max,ny_max,box[1]) print 2*nx_max/box[0], 2*ny_max/box[1] rcd = np.linspace(d[0],r_max,box[2]) return nxcd,nycd,rcd
def plot_BSC_BAC(title, error_probability, R): """ :param title: Figure title :param e0: linspace of all epsilon0 :param error_probability: error probability dictionary (BER or BLER) :param R: Coding rate R=k/N :return: plot """ """ """ fig = plt.figure(figsize=(7, 3.5), dpi=180, facecolor='w', edgecolor='k') fig.subplots_adjust(wspace=0.4, top=0.8) fig.suptitle(title, fontsize=14) ax1 = plt.subplot2grid((1, 2), (0, 0), rowspan=1, colspan=1) ax2 = plt.subplot2grid((1, 2), (0, 1), rowspan=1, colspan=1) marker = itertools.cycle(('h', 'p', '*', '.', '+', 'o', 'h', 's', ',')) linestyle = itertools.cycle(('-', '--', '-.', ':')) legends = [] for keys in error_probability: bac_fer = [] bsc_fer = [] legends.append(keys) # print(keys,error_probability,e0) e0_bac = [] for ep0 in error_probability[keys]: e0_bac.append(ep0) for ep0 in e0_bac: bac_fer.append(error_probability[keys][ep0][0]) if ep0 <= 0.5: bsc_fer.append(error_probability[keys][ep0][-1]) # print(keys) # print('BAC', ["{:.4f}".format(a) for a in bac_fer]) # print('BSC', ["{:.4f}".format(a) for a in bsc_fer]) e0_bsc = [x for x in e0_bac if x <= 0.5] m = next(marker) # l = next(linestyle) l = '-' ax1.semilogy(e0_bac, [bac_fer[a] for a in range(len(bac_fer))], linestyle=l, marker=m, ms=0.5, linewidth=0.5) ax2.semilogy(e0_bsc, [bsc_fer[a] for a in range(len(bsc_fer))], linestyle=l, marker=m, ms=0.5, linewidth=0.5) E0 = np.linspace(0.0001, 0.99999, 901) ax1.semilogy(E0, cut_off_epsilon(E0, e0_bac[0], R, 'BAC'), 'k', linestyle='-', ms=0.1, linewidth=0.15) E0 = np.linspace(0.0001, 0.49999, 451) ax2.semilogy(E0, cut_off_epsilon(E0, 0, R, 'BSC'), 'k', linestyle='-', ms=0.1, linewidth=0.15) ax1.legend(legends, prop={'size': 5}, loc="lower right") ax1.set_title(f"BAC($\epsilon_1$={e0_bac[0]},$\epsilon_0$)", fontsize=8) ax1.set_xlabel('$\epsilon_0$', fontsize=8) ax1.set_ylabel('Error Probability', fontsize=8) # ax1.set_xticklabels(np.arange(0, 1, step=0.2)) ax1.grid(which='both', linewidth=0.2) ax2.legend(legends, prop={'size': 5}, loc="lower right") ax2.set_title('BSC($\epsilon$)', fontsize=8) ax2.set_xlabel('$\epsilon$', fontsize=8) ax2.grid(which='both', linewidth=0.2)
def create(dataset, dataset_name, output_directory, num_shards, num_threads, shuffle=True): """Create the tfrecord files to be used to train or test a model. Args: dataset : [{ "filename" : <REQUIRED: path to the image file>, "id" : <REQUIRED: id of the image>, "class" : { "label" : <[0, num_classes)>, "text" : <text description of class> }, "object" : { "bbox" : { "xmin" : [], "xmax" : [], "ymin" : [], "ymax" : [], "label" : [] } } }] dataset_name: a name for the dataset output_directory: path to a directory to write the tfrecord files num_shards: the number of tfrecord files to create num_threads: the number of threads to use shuffle : bool, should the image examples be shuffled or not prior to creating the tfrecords. Returns: list : a list of image examples that failed to process. """ # Images in the tfrecords set must be shuffled properly if shuffle: random.shuffle(dataset) # Break all images into batches with a [ranges[i][0], ranges[i][1]]. spacing = np.linspace(0, len(dataset), num_threads + 1).astype(np.int) ranges = [] threads = [] for i in xrange(len(spacing) - 1): ranges.append([spacing[i], spacing[i + 1]]) # Launch a thread for each batch. print('Launching %d threads for spacings: %s' % (num_threads, ranges)) sys.stdout.flush() # Create a mechanism for monitoring when all threads are finished. coord = tf.train.Coordinator() # Create a generic TensorFlow-based utility for converting all image codings. coder = ImageCoder() # A Queue to hold the image examples that fail to process. error_queue = Queue() threads = [] for thread_index in xrange(len(ranges)): args = (coder, thread_index, ranges, dataset_name, output_directory, dataset, num_shards, error_queue) t = threading.Thread(target=_process_image_files_batch, args=args) t.start() threads.append(t) # Wait for all the threads to terminate. coord.join(threads) print('%s: Finished writing all %d images in data set.' % (datetime.now(), len(dataset))) # Collect the errors errors = [] while not error_queue.empty(): errors.append(error_queue.get()) print('%d examples failed.' % (len(errors), )) return errors
def _process_image_files_batch(coder, thread_index, ranges, name, output_directory, dataset, num_shards, error_queue): """Processes and saves list of images as TFRecord in 1 thread. Args: coder: instance of ImageCoder to provide TensorFlow image coding utils. thread_index: integer, unique batch to run index is within [0, len(ranges)). ranges: list of pairs of integers specifying ranges of each batches to analyze in parallel. name: string, unique identifier specifying the data set (e.g. `train` or `test`) output_directory: string, file path to store the tfrecord files. dataset: list, a list of image example dicts num_shards: integer number of shards for this data set. error_queue: Queue, a queue to place image examples that failed. """ # Each thread produces N shards where N = int(num_shards / num_threads). # For instance, if num_shards = 128, and the num_threads = 2, then the first # thread would produce shards [0, 64). num_threads = len(ranges) assert not num_shards % num_threads num_shards_per_batch = int(num_shards / num_threads) shard_ranges = np.linspace(ranges[thread_index][0], ranges[thread_index][1], num_shards_per_batch + 1).astype(int) num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0] counter = 0 error_counter = 0 for s in xrange(num_shards_per_batch): # Generate a sharded version of the file name, e.g. 'train-00002-of-00010' shard = thread_index * num_shards_per_batch + s output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards) output_file = os.path.join(output_directory, output_filename) writer = tf.python_io.TFRecordWriter(output_file) shard_counter = 0 files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int) for i in files_in_shard: image_example = dataset[i] filename = str(image_example['filename']) try: if 'encoded' in image_example: image_buffer = image_example['encoded'] height = image_example['height'] width = image_example['width'] colorspace = image_example['colorspace'] image_format = image_example['format'] num_channels = image_example['channels'] example = _convert_to_example(image_example, image_buffer, height, width, colorspace, num_channels, image_format) else: image_buffer, height, width = _process_image( filename, coder) example = _convert_to_example(image_example, image_buffer, height, width) writer.write(example.SerializeToString()) shard_counter += 1 counter += 1 except Exception as e: error_counter += 1 error_msg = repr(e) image_example['error_msg'] = error_msg error_queue.put(image_example) if not counter % 1000: print( '%s [thread %d]: Processed %d of %d images in thread batch, with %d errors.' % (datetime.now(), thread_index, counter, num_files_in_thread, error_counter)) sys.stdout.flush() print('%s [thread %d]: Wrote %d images to %s, with %d errors.' % (datetime.now(), thread_index, shard_counter, output_file, error_counter)) sys.stdout.flush() shard_counter = 0 print('%s [thread %d]: Wrote %d images to %d shards, with %d errors.' % (datetime.now(), thread_index, counter, num_files_in_thread, error_counter)) sys.stdout.flush()
color='g') # Mean value of cross validation scores plt.show() # # Learning Curve # # Learning curve enables us decide a model is over fitting to given training data and training under appropriate bias and variance balance. Now we try to plot learning curve of this model. # In[ ]: from sklearn.model_selection import learning_curve train_sizes, train_scores, test_scores = learning_curve( estimator=pipe_svc, X=X_train, y=y_train, train_sizes=np.linspace(0.1, 1.0, 10), cv=10) # Mean value of accuracy against training data train_mean = np.mean(train_scores, axis=1) # Standard deviation of training accuracy per number of training samples train_std = np.std(train_scores, axis=1) # Same as above for test data test_mean = np.mean(test_scores, axis=1) test_std = np.std(test_scores, axis=1) # Plot training accuracies plt.plot(train_sizes, train_mean,
top=True, right=True) ax.tick_params(axis='both', which='major', length=5) # set spacing of tick marks #ax.xaxis.set_major_locator(ticker.MultipleLocator(0.0005)) #ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.0001)) ax.xaxis.set_major_locator(ticker.MultipleLocator(0.0010)) ax.xaxis.set_minor_locator(ticker.MultipleLocator(0.0001)) ### ----- GET FILES ----- ### doppler_files = f'/Users/calebharada/3D_RT_Code/2stream_new/OUT/{case}/*_dopp-ON_phase-*.dat' # set up color cycle color_idx = np.linspace(0, 1, len(glob.glob(doppler_files))) const1 = 1 ### ----- PLOT THE SPECTRA ----- ### # plot Doppler-shifted spectra for i, file in enumerate(sorted(glob.glob(doppler_files))): wl, flux = np.loadtxt(file, unpack=True) # load data # convert units to kW / m^2 / um flux = flux * const.c / (wl * wl) * 1e-9 # convert wavelenths to microns wl *= 1e+6
#Berechnung der effektiven Länge p0=1013 x0=2 x=x0*(p/p0) print('effektive Länge=',x) def f(x, a, b): return a*x+b params, cov = curve_fit(f, x1, N1) errors = np.sqrt(np.diag(cov)) print('a =', params[0], '±', errors[0]) print('b =', params[1], '±', errors[1]) a=ufloat(params[0], errors[0]) b=ufloat(params[1], errors[1]) t=np.linspace(0.6, 8) #plt.plot (x, y, 'rx', label='Messwerte') plt.plot(x,N , 'rx', label='Messwerte') #plt.plot(t,f(t, *params), 'b-' ,label='Ausgleichsgerade') plt.axhline(y=67691) plt.text(-0.1, 65707,'N/2') #plt.axvline(x=7.4) #plt.yscale('log') plt.xlabel(r'$ x/cm$') plt.ylabel(r'$ N$') plt.tight_layout() plt.legend() plt.savefig('plot2.pdf') plt.show()
def on_epoch_start(self, trainer): # pylint: disable=unused-argument noise_schedule = self.config["train_noise_schedule"] betas = np.linspace(noise_schedule["min_val"], noise_schedule["max_val"], noise_schedule["num_steps"]) self.compute_noise_level(betas)
data['U2'] = data['U2'] / 2 * 1e-3 cdata = np.array([ # umeritvena tabela kondenzatorja [20, 16], [30, 31], [40, 50], [50, 65], [60, 87], [70, 110], [80, 145], [90, 185], [120, 320], [130, 380], [140, 445], [160, 580], [180, 710], [200, 860] ]) x = cdata[:, 0] y = cdata[:, 1] count_to_pF = np.poly1d(np.polyfit(x, y, 3)) ufig, uax = plt.subplots() uax.plot(x, y, ".", label='podatki iz umeritvene tabele') _x = np.linspace(min(x), max(x), 1000) # umeritvena krivulja uax.plot(_x, count_to_pF(_x), "--", label='polinom 3. reda') uax.legend() uax.set_xlabel('count (število razdelkov na kondenzatorju)') uax.set_ylabel('C [pF]') uax.grid(color='lightgray') #ufig.show() #C_0 = ufloat(count_to_pF(173), 10) * 1e-12 C = count_to_pF(data['count'].values) * 1e-12 y = (data['U2'] / data['U1']).values r = data['R'].values w = np.where(r == 0) freq = 560e3
def curvedspace(begin, end, curve, num=100): ans = np.linspace(0., (end - begin)**(1.0/curve), num) ** (curve) + begin ans[-1] = end #so that the last element is exactly end return ans
# hot pixel plots matplotlib.rcParams.update({'font.size': 8}) if narrowfig: F = plt.figure(figsize=(3.5,6)) else: F = plt.figure(figsize=(7,6)) # # hot pixel locations if narrowfig: S = F.add_subplot(2,1,1) else: S = F.add_subplot(2,2,1) S.set_title('hot pixel locations: '+mydet) S.set_xlim(0,N); S.set_ylim(0,N); S.set_aspect('equal') S.xaxis.set_ticks(numpy.linspace(0,N,num=5)); S.yaxis.set_ticks(numpy.linspace(0,N,num=5)) S.grid(True, color='g', linestyle='-') S.scatter(hotX+.5, hotY+.5, s=3, marker='.', color='r') # # these two panels only in the full version, not the narrow version if not narrowfig: # hot pixel level S = F.add_subplot(2,2,2) S.set_xlabel(r'Signal level $S_{1,' + '{:d}'.format(htsteps[-1]) +'}$ [DN]') S.set_ylabel(r'IPC $\alpha$ [%]') SX = hotpix_signal[:,-1] SY = hotpix_alpha[:,-1]/.01 S.set_title(r'IPC $\alpha$ for hot pixels') S.set_xlim(.95*(htsteps[-1]-1)/(NTMAX-1.0)*hotpix_ADU_range[0], 1.05*hotpix_ADU_range[1]) S.set_ylim(0,4.) S.grid(True, color='g', linestyle='-')
# mask.show() ############################################################################# # Generate the kspace # ------------------- # # From the 2D brain slice and the acquisition mask, we retrospectively # undersample the k-space using a radial acquisition mask # We then reconstruct the zero order solution as a baseline # Get the locations of the kspace samples and the associated observations fourier_op = NFFT(samples=kspace_loc, shape=image.shape) kspace_obs = fourier_op.op(image.data) # Gridded solution grid_space = np.linspace(-0.5, 0.5, num=image.shape[0]) grid2D = np.meshgrid(grid_space, grid_space) grid_soln = gridded_inverse_fourier_transform_nd(kspace_loc, kspace_obs, tuple(grid2D), 'linear') image_rec0 = pysap.Image(data=grid_soln) # image_rec0.show() base_ssim = ssim(image_rec0, image) print('The Base SSIM is : ' + str(base_ssim)) ############################################################################# # FISTA optimization # ------------------ # # We now want to refine the zero order solution using a FISTA optimization. # The cost function is set to Proximity Cost + Gradient Cost
#interconnected HUC12 filename="P:/2021/ArizonaStorm/BasinAvg/AORC/InterHUC12_IntersAORC_EPSG4269_CorrArea.csv" df_agg=pd.read_csv(filename.lstrip('\u202a')) df_agg['AreaSqMile']=df_agg.AreaSqKm*c Area_agg=df_agg['AreaSqMile'] #HUC12s filename1="P:/2021/ArizonaStorm/BasinAvg/AORC/SelectedHUC12_IntersAORC_EPSG4269_CorrArea.csv" df_huc12s=pd.read_csv(filename1.lstrip('\u202a')) df_huc12s['AreaSqMile']=df_huc12s.AreaSqKm*c Areahuc12=df_huc12s['AreaSqMile'] Area_agg=Area_agg[Area_agg<600] Areahuc12=Areahuc12[Areahuc12<600] binBoundaries = np.linspace(0,600,60) # Generate histogram of the whole study area plt.style.use('ggplot') plt.rc('font', size=20) # plt.rcParams["figure.autolayout"] = True fig,ax=plt.subplots(3, figsize=(24,8)) fig.tight_layout(w_pad=2) ax1 = plt.subplot(1,3,1) ax1.hist(Areahuc12, bins=binBoundaries, color='cornflowerblue', edgecolor="white") ax1.set_xlim([0,300]) ax1.set_ylim([0,2000]) ax1.set_yticks([0,500,1000,1500,2000]) ax1.set_xlabel('Area ($mile^{2}$)') ax1.set_ylabel('Count') ax1.set_title('HUC12s')
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt def signal(t): return np.sin(2 * np.pi * t) + 2 * np.sin(4 * np.pi * t) ts = np.linspace(0, 5, 128) ts2 = np.linspace(-5, 5, 100) samples = signal(ts) samples_rect = np.where(abs(ts2) <= 0.5, 1, 0) amp = np.fft.fft(samples) amp_rect = np.fft.fft(samples_rect) freq = np.fft.fftfreq(len(ts)) freq2 = np.fft.fftfreq(len(ts2)) fig = plt.figure("DFT & DWT Demo") fig.set_tight_layout(True) (td, td2), (fd, fd2) = fig.subplots(2, 2) td.set_title("Time domain $f(t)=\sin(2\pi t)+2\sin(4\pi t)$") td.plot(ts, samples, label=r"$f(t)$") td.legend() fd.set_title(r"Frequency domain $F(\omega)=\mathcal{F}\{f(t)\}$") fd.plot(freq, amp.real, label=r"$\Re[F(\omega)]$") fd.plot(freq, amp.imag, label=r"$\Im[F(\omega)]$")
#mag_global = [] #for i in range (73728): #mag_global.append(br[i]) nlat_max=1937 #number of latitudinal gridpoints in magnetogram nlat = nlat_max nlon=nlat*2 cth = gaussquad_legendre(nlat) theta = np.arccos(cth[0]) lat=90-theta*180/math.pi lon=np.linspace(0,360, nlon+1)[0:nlon] phi=lon*(math.pi/180) dlatinterp=get_interpolation_index(lat_global, lat) dloninterp=get_interpolation_index(lon_global, lon) #IDL 'interpolate' function #?????????????????????????????????????????????????????????????????? ################################################################### #mags_interpolated = scipy.interpolate.interpn(mag_global,dloninterp,dlatinterp,method='linear') #mags_interpolated = scipy.ndimage.map_coordinates(mag_global, [dlatinterp, dloninterp], order=1, mode='nearest') #xi,yi =np.meshgrid(dlatinterp,dloninterp)
def fields_fs_lower(efit_file_name,flux_surface,ngrid_r,ngrid_z): fs = float(flux_surface) psip_n, Rgrid, Zgrid, F, p, ffprime, pprime, psirz, qpsi, rmag, zmag, nw, psiax, psisep = read_EFIT_file(efit_file_name) Z_fs = np.empty(0) R_fs_out_grid = np.empty(0) B_pol_fs_out = np.empty(0) B_tor_fs_out = np.empty(0) R_fs_in_grid = np.empty(0) B_pol_fs_in = np.empty(0) B_tor_fs_in = np.empty(0) Z0_ind = np.argmin(abs(Zgrid-zmag)) #decrease Z from midplane until the lowest psip at that Z is larger than fs while (np.min((psirz[Z0_ind,:]-psiax)/(psisep-psiax))<fs): psi_pol = psirz[Z0_ind,:] #Rmag_ind is the position of lowest psip at that Z Rmag_ind = np.argmin(abs(psi_pol)) psi_pol_out = psi_pol[Rmag_ind:].copy() psip_n_temp = (psi_pol_out-psiax)/(psisep-psiax) R_fs_ind_out = np.argmin(abs(psip_n_temp-fs)) #print ((psirz[Z0_ind,Rmag_ind+R_fs_ind_out]-psiax)/(psisep-psiax)-fs)/fs unif_R_out = np.linspace(Rgrid[Rmag_ind],Rgrid[-1],nw*10) psip_n_unifR_out = interp(Rgrid[Rmag_ind:],psip_n_temp,unif_R_out) #psifs_ind_out is the postition of psip_n = fs psifs_ind_out = np.argmin(abs(psip_n_unifR_out-fs)) #psip_n_fs_out is the local grid of psip_n around fs psip_n_fs_out = psip_n_unifR_out[psifs_ind_out-ngrid_r:psifs_ind_out+ngrid_r].copy() #R_fs_out is the local grid of R around fs R_fs_out = unif_R_out[psifs_ind_out-ngrid_r:psifs_ind_out+ngrid_r].copy() #B_pol_Z_out is the z component of B_pol at fs, B_pol_Z = 1/R d psip /d R B_pol_Z_out = fd_d1_o4(psip_n_fs_out*(psisep-psiax)+psiax,R_fs_out)/R_fs_out F_out = interp(psip_n,F,psip_n_fs_out) B_tor_out = F_out/R_fs_out # psi_pol_z selects ngrid_z points above and below Z0 and R_fs from psirz psi_pol_z = psirz[Z0_ind-ngrid_z:Z0_ind+ngrid_z,R_fs_ind_out+Rmag_ind] unif_z = np.linspace(Zgrid[Z0_ind-ngrid_z],Zgrid[Z0_ind+ngrid_z],10*ngrid_z) psi_pol_unifz = interp(Zgrid[Z0_ind-ngrid_z:Z0_ind+ngrid_z],psi_pol_z,unif_z) ###plt.plot(Zgrid[Z0_ind-ngrid_z:Z0_ind+ngrid_z],psi_pol_z,'x') ###plt.plot(unif_z,psi_pol_unifz,'.') ###plt.show() #B_pol_R_out is the R component of B_pol at fs, B_pol_R = 1/R d psip/d Z B_pol_R_out = fd_d1_o4(psi_pol_unifz,unif_z)/R_fs_out[ngrid_r] #z_fs_ind is the position of Z0_ind in the newly constructed array unif_z z_fs_ind=np.argmin(abs(unif_z-Zgrid[Z0_ind])) #B_pol_out is the total B_pol field at psip=fs B_pol_out = np.sqrt(B_pol_Z_out[ngrid_r]**2+B_pol_R_out[z_fs_ind]**2) #similar procedure at inner side psi_pol_in = psi_pol[:Rmag_ind].copy() psip_n_temp = (psi_pol_in-psiax)/(psisep-psiax) R_fs_ind_in = np.argmin(abs(psip_n_temp-fs)) unif_R_in = np.linspace(Rgrid[0],Rgrid[Rmag_ind],nw*10) psip_n_unifR_in = interp(Rgrid[:Rmag_ind],psip_n_temp,unif_R_in) psifs_ind_in = np.argmin(abs(psip_n_unifR_in-fs)) psip_n_fs_in = psip_n_unifR_in[psifs_ind_in-ngrid_r:psifs_ind_in+ngrid_r].copy() R_fs_in = unif_R_in[psifs_ind_in-ngrid_r:psifs_ind_in+ngrid_r].copy() B_pol_Z_in = fd_d1_o4(psip_n_fs_in*(psisep-psiax)+psiax,R_fs_in)/R_fs_in F_in = interp(psip_n,F,psip_n_fs_in) B_tor_in = F_in/R_fs_in psi_pol_z = psirz[Z0_ind-ngrid_z:Z0_ind+ngrid_z,R_fs_ind_in] psi_pol_unifz = interp(Zgrid[Z0_ind-ngrid_z:Z0_ind+ngrid_z],psi_pol_z,unif_z) B_pol_R_in = fd_d1_o4(psi_pol_unifz,unif_z)/R_fs_in[ngrid_r] B_pol_in = np.sqrt(B_pol_Z_in[ngrid_r]**2+B_pol_R_in[z_fs_ind]**2) Z_fs = np.append(Z_fs,Zgrid[Z0_ind]) R_fs_out_grid = np.append(R_fs_out_grid,R_fs_out[ngrid_r]) B_pol_fs_out = np.append(B_pol_fs_out,B_pol_out) B_tor_fs_out = np.append(B_tor_fs_out,B_tor_out[ngrid_r]) R_fs_in_grid = np.append(R_fs_in_grid,R_fs_in[ngrid_r]) B_pol_fs_in = np.append(B_pol_fs_in,B_pol_in) B_tor_fs_in = np.append(B_tor_fs_in,B_tor_in[ngrid_r]) Z0_ind = Z0_ind+1 R_fs_out_grid_r = np.flipud(R_fs_out_grid) B_pol_fs_out_r = np.flipud(B_pol_fs_out) B_tor_fs_out_r = np.flipud(B_tor_fs_out) B_tot_fs_out_r = np.sqrt(B_tor_fs_out_r**2+B_pol_fs_out_r**2) B_tot_fs_in = np.sqrt(B_tor_fs_in**2+B_pol_fs_in**2) theta_out_r = np.arctan(abs(Z_fs)/R_fs_out_grid_r) theta_in = -np.arctan(abs(Z_fs)/R_fs_in_grid)+np.pi R_fs = np.concatenate([R_fs_in_grid,R_fs_out_grid_r]) B_pol = np.concatenate([B_pol_fs_in,B_pol_fs_out_r]) B_tor = np.concatenate([B_tor_fs_in,B_tor_fs_out_r]) B_tot = np.concatenate([B_tot_fs_in,B_tot_fs_out_r]) theta_fs = np.concatenate([theta_in,theta_out_r]) f=open('fs_'+efit_file_name+'.dat','w') f.write('# R B_pol B_tor B_tot theta\n') np.savetxt(f,np.column_stack((R_fs,B_pol,B_tor,B_tot,theta_fs))) f.close() return R_fs, B_pol, B_tor, B_tot
nX=['n0/','n1/','n2/','n3/','n4/','n5/','n6/','n7/','n8/'] diz_pths={pth1:[nX],pth2:[nX],pth3:[nX],pth4:[nX],pth5:[['n0/']]} diz_labels={pth1:"$\Delta T=5.0\\times 10^3$",pth2:"$\Delta T= 1.0\\times 10^4$",pth3:"$\Delta T= 1.5 \\times 10^4$",pth4:"$\Delta T= 2.0\\times 10^4$",pth5:"$\Delta T=\infty$"} for key in diz_pths: rnX=[] for mu in range(RUNS): #not considering extinctions if all(os.listdir(key+'RUN'+str(mu)+'/'+x)==[] for x in diz_pths[key][0]): pass else: rnX.append('RUN'+str(mu)+'/') diz_pths[key].append(rnX) #plotting distribution of len for each c value comparing different DTs for c_value in nX: fig, axesa = plt.subplots(1,figsize=(16, 8),sharey=True) color=iter(cm.rainbow(np.linspace(0,1,5))) labels=[] line2d=[] for time_gap in [pth1,pth2,pth3,pth4,pth5]: efflen=[] telen=[] if time_gap!=pth5: for run in diz_pths[time_gap][1]: j=1 #print type(time_gap) #print type(run) #print run #print type(c_value) fin=time_gap+run+c_value+'pts'+str(j)+'plotdata.p' while os.path.exists(fin):
import numpy as np import seaborn as sns import matplotlib.pyplot as plt import pandas as pd sns.set() sns.set_context("paper", rc={"lines.linewidth": 2}) data = pd.read_csv("./training_loss", sep=',') val_data = pd.read_csv("./val_loss", sep=',') x = np.linspace(0, 10, 61) x_val = np.linspace(0, 10, 11) fig, ax1 = plt.subplots() plots = [] color = 'tab:red' fontsize = 15 ax1.set_xlabel('Epoch', fontsize=fontsize) ax1.set_ylabel('Loss', color=color, fontsize=fontsize) p = ax1.plot(x, data["Loss"], color=color, label="Training Loss") plots.extend(p) # Set markers on epoch where we plot eigenspectrum markers = [0, 4, 10] marker_shapes = ['^', 'o', 's'] colors = ["purple", "orange", "green"] for i, m in enumerate(markers): ax1.scatter(m, data["Loss"][m * 6], c=colors[i], marker=marker_shapes[i], s=200)
def fields_fs_upper(efit_file_name,flux_surface,ngrid_r,ngrid_z,extra_r,extra_z): fs = float(flux_surface) psip_n, Rgrid, Zgrid, F, p, ffprime, pprime, psirz, qpsi, rmag, zmag, nw, psiax, psisep = read_EFIT_file(efit_file_name) Z_fs = np.empty(0) R_fs_out_grid = np.empty(0) B_pol_fs_out = np.empty(0) B_tor_fs_out = np.empty(0) R_fs_in_grid = np.empty(0) B_pol_fs_in = np.empty(0) B_tor_fs_in = np.empty(0) Z0_ind = np.argmin(abs(Zgrid-zmag)) #decrease Z from midplane until the lowest psip at that Z is larger than fs while (np.min((psirz[Z0_ind,:]-psiax)/(psisep-psiax))<fs): psi_pol = psirz[Z0_ind,:] #Rmag_ind is the position of lowest psip at that Z Rmag_ind = np.argmin(abs(psi_pol)) #R_fs_ind_out is the index of psip_n_temp that is on fs psi_pol_out = psi_pol[Rmag_ind:].copy() psip_n_temp = (psi_pol_out-psiax)/(psisep-psiax) R_fs_ind_out = np.argmin(abs(psip_n_temp-fs)) #unif_R_out is a fine grid of Rgrid on the outer unif_R_out = np.linspace(Rgrid[Rmag_ind],Rgrid[-1],nw*10) psip_n_unifR_out = interp(Rgrid[Rmag_ind:],psip_n_temp,unif_R_out) #psifs_ind_out is the postition of psip_n = fs psifs_ind_out = np.argmin(abs(psip_n_unifR_out-fs)) #psip_n_fs_out is the local grid of psip_n around fs psip_n_fs_out = psip_n_unifR_out[psifs_ind_out-ngrid_r:psifs_ind_out+ngrid_r].copy() #R_fs_out is the local grid of R around fs R_fs_out = unif_R_out[psifs_ind_out-ngrid_r:psifs_ind_out+ngrid_r].copy() #B_pol_Z_out is the z component of B_pol at fs, B_pol_Z = 1/R d psip /d R B_pol_Z_out = fd_d1_o4(psip_n_fs_out*(psisep-psiax)+psiax,R_fs_out)/R_fs_out #B_tor = F/R F_out = interp(psip_n,F,psip_n_fs_out) B_tor_out = F_out/R_fs_out #psi_pol_z selects ngrid_z points above and below (R_fs,Z0) from psirz psi_pol_z = psirz[Z0_ind-ngrid_z:Z0_ind+ngrid_z,R_fs_ind_out+Rmag_ind] #unif_z is a local fine grid of Z unif_z = np.linspace(Zgrid[Z0_ind-ngrid_z],Zgrid[Z0_ind+ngrid_z],10*ngrid_z) #psi_pol_unifz is a local grid of psi_pol psi_pol_unifz = interp(Zgrid[Z0_ind-ngrid_z:Z0_ind+ngrid_z],psi_pol_z,unif_z) #B_pol_R_out is the R component of B_pol at fs, B_pol_R = 1/R d psip/d Z B_pol_R_out = fd_d1_o4(psi_pol_unifz,unif_z)/R_fs_out[ngrid_r] #z_fs_ind is the position of Z0_ind in the newly constructed array unif_z z_fs_ind=np.argmin(abs(unif_z-Zgrid[Z0_ind])) #B_pol_out is the total B_pol field at psip=fs B_pol_out = np.sqrt(B_pol_Z_out[ngrid_r]**2+B_pol_R_out[z_fs_ind]**2) #similar procedure at inner side psi_pol_in = psi_pol[:Rmag_ind].copy() psip_n_temp = (psi_pol_in-psiax)/(psisep-psiax) R_fs_ind_in = np.argmin(abs(psip_n_temp-fs)) unif_R_in = np.linspace(Rgrid[0],Rgrid[Rmag_ind],nw*10) psip_n_unifR_in = interp(Rgrid[:Rmag_ind],psip_n_temp,unif_R_in) psifs_ind_in = np.argmin(abs(psip_n_unifR_in-fs)) psip_n_fs_in = psip_n_unifR_in[psifs_ind_in-ngrid_r:psifs_ind_in+ngrid_r].copy() R_fs_in = unif_R_in[psifs_ind_in-ngrid_r:psifs_ind_in+ngrid_r].copy() B_pol_Z_in = fd_d1_o4(psip_n_fs_in*(psisep-psiax)+psiax,R_fs_in)/R_fs_in F_in = interp(psip_n,F,psip_n_fs_in) B_tor_in = F_in/R_fs_in psi_pol_z = psirz[Z0_ind-ngrid_z:Z0_ind+ngrid_z,R_fs_ind_in] psi_pol_unifz = interp(Zgrid[Z0_ind-ngrid_z:Z0_ind+ngrid_z],psi_pol_z,unif_z) B_pol_R_in = fd_d1_o4(psi_pol_unifz,unif_z)/R_fs_in[ngrid_r] B_pol_in = np.sqrt(B_pol_Z_in[ngrid_r]**2+B_pol_R_in[z_fs_ind]**2) Z_fs = np.append(Z_fs,Zgrid[Z0_ind]) R_fs_out_grid = np.append(R_fs_out_grid,R_fs_out[ngrid_r]) B_pol_fs_out = np.append(B_pol_fs_out,B_pol_out) B_tor_fs_out = np.append(B_tor_fs_out,B_tor_out[ngrid_r]) R_fs_in_grid = np.append(R_fs_in_grid,R_fs_in[ngrid_r]) B_pol_fs_in = np.append(B_pol_fs_in,B_pol_in) B_tor_fs_in = np.append(B_tor_fs_in,B_tor_in[ngrid_r]) Z0_ind = Z0_ind-1 extra_Rgrid = np.linspace(R_fs_in[ngrid_r],R_fs_out[ngrid_r],extra_r) extra_Zgrid = np.linspace(Zgrid[Z0_ind],Zgrid[Z0_ind+3],extra_z) Zgrid_frame = Zgrid[Z0_ind-ngrid_z:Z0_ind+1+ngrid_z] psip_extra_frame = np.empty([1+2*ngrid_z,extra_r]) psip_extra = np.empty([extra_z,extra_r]) for i in arange(0,2*ngrid_z+1): psi_pol = psirz[Z0_ind-ngrid_z+i,:] psip_extra_frame[i,:] = interp(Rgrid,psi_pol,extra_Rgrid) #plt.plot(extra_Rgrid,psip_extra[i,:]) #plt.show() for i in arange(0,extra_r): psip_z_frame = psip_extra_frame[:,i] psip_extra[:,i]=interp(Zgrid_frame,psip_z_frame,extra_Zgrid) #plt.plot(extra_Zgrid,psip_extra[:,i],'.') #plt.show() B_pol_bottom_out = np.empty(0) B_tor_bottom_out = np.empty(0) R_bottom_out = np.empty(0) B_pol_bottom_in = np.empty(0) B_tor_bottom_in = np.empty(0) R_bottom_in = np.empty(0) for i in arange(0,extra_z): psip_n_extra = (psip_extra[i,:]-psiax)/(psisep-psiax) r_ind = np.argmin(psip_n_extra) psip_n_extra_out = psip_n_extra[r_ind:].copy() extra_r_ind_out = np.argmin(psip_n_extra_out-fs) B_pol_Z_extra_out = \ fd_d1_o4(psip_n_extra_out*(psisep-psiax)+psiax,extra_Rgrid[r_ind:])/extra_Rgrid[r_ind:] F_extra_out = interp(psip_n,F,psip_n_extra_out) B_tor_extra_out = F_extra_out/extra_Rgrid[r_ind:] B_pol_R_extra_out = \ fd_d1_o4(psip_extra[:,r_ind+extra_r_ind_out],extra_Zgrid)/extra_Rgrid[r_ind+extra_r_ind_out] this_B_pol = np.sqrt(B_pol_R_extra_out[i]**2+B_pol_Z_extra_out[extra_r_ind_out]**2) if this_B_pol>1.E-3 : B_pol_bottom_out = np.append(B_pol_bottom_out,this_B_pol) R_bottom_out = np.append(R_bottom_out,extra_Rgrid[r_ind+extra_r_ind_out]) B_tor_bottom_out = np.append(B_tor_bottom_out,B_tor_extra_out[extra_r_ind_out]) psip_n_extra_in = psip_n_extra[:r_ind].copy() extra_r_ind_in = np.argmin(psip_n_extra_in-fs) B_pol_Z_extra_in = \ fd_d1_o4(psip_n_extra_in*(psisep-psiax)+psiax,extra_Rgrid[:r_ind])/extra_Rgrid[:r_ind] F_extra_in = interp(psip_n,F,psip_n_extra_in) B_tor_extra_in = F_extra_in/extra_Rgrid[:r_ind] B_pol_R_extra_in = \ fd_d1_o4(psip_extra[:,extra_r_ind_in],extra_Zgrid)/extra_Rgrid[extra_r_ind_in] this_B_pol = np.sqrt(B_pol_R_extra_in[i]**2+B_pol_Z_extra_in[extra_r_ind_in]**2) if this_B_pol>1.E-3 : B_pol_bottom_in = np.append(B_pol_bottom_in,this_B_pol) R_bottom_in = np.append(R_bottom_in,extra_Rgrid[extra_r_ind_in]) B_tor_bottom_in = np.append(B_tor_bottom_in,B_tor_extra_in[extra_r_ind_in]) R_bottom_out_r = np.flipud(R_bottom_out) B_pol_bottom_out_r = np.flipud(B_pol_bottom_out) B_tor_bottom_out_r = np.flipud(B_tor_bottom_out) B_tot_bottom_out_r = np.sqrt(B_tor_bottom_out_r**2+B_pol_bottom_out_r**2) B_tot_bottom_in = np.sqrt(B_tor_bottom_in**2+B_pol_bottom_in**2) R_fs_out_grid_r = np.flipud(R_fs_out_grid) B_pol_fs_out_r = np.flipud(B_pol_fs_out) B_tor_fs_out_r = np.flipud(B_tor_fs_out) B_tot_fs_out_r = np.sqrt(B_tor_fs_out_r**2+B_pol_fs_out_r**2) B_tot_fs_in = np.sqrt(B_tor_fs_in**2+B_pol_fs_in**2) #theta_out_r = np.arctan(abs(Z_fs)/R_fs_out_grid_r) #theta_in = -np.arctan(abs(Z_fs)/R_fs_in_grid)+np.pi R_fs = np.concatenate([R_fs_in_grid,R_bottom_in,R_bottom_out_r,R_fs_out_grid_r]) B_pol = np.concatenate([B_pol_fs_in,B_pol_bottom_in,B_pol_bottom_out_r,B_pol_fs_out_r]) B_tor = np.concatenate([B_tor_fs_in,B_tor_bottom_in,B_tor_bottom_out_r,B_tor_fs_out_r]) B_tot = np.concatenate([B_tot_fs_in,B_tot_bottom_in,B_tot_bottom_out_r,B_tot_fs_out_r]) #theta_fs = np.concatenate([theta_in,theta_out_r]) #f=open('fs_'+efit_file_name+'.dat','w') #f.write('# R B_pol B_tor B_tot theta\n') #np.savetxt(f,np.column_stack((R_fs,B_pol,B_tor,B_tot,theta_fs))) #f.close() return R_fs, B_pol, B_tor, B_tot
# -*- coding: utf-8 -*- from __future__ import unicode_literals import numpy as np import sklearn.cluster as sc import sklearn.metrics as sm import matplotlib.pyplot as mp x = [] with open('../../data/perf.txt', 'r') as f: for line in f.readlines(): data = [float(substr) for substr in line.split(',')] x.append(data) x = np.array(x) epsilons, scores, models = np.linspace(0.3, 1.2, 10), [], [] for epsilon in epsilons: model = sc.DBSCAN(eps=epsilon, min_samples=5) model.fit(x) score = sm.silhouette_score(x, model.labels_, sample_size=len(x), metric='euclidean') scores.append(score) models.append(model) scores = np.array(scores) best_index = scores.argmax() best_epsilon = epsilons[best_index] print(best_epsilon) best_score = scores[best_index] best_model = models[best_index] pred_y = best_model.fit_predict(x) core_mask = np.zeros(len(x), dtype=bool) core_mask[best_model.core_sample_indices_] = True
xlabsize, ylabsize, ticksize = 15,15,12 fig, ax_array = plt.subplots(3, figsize=(18,10), sharex = True, gridspec_kw = {'height_ratios':height_ratio}) fig.subplots_adjust(hspace = .05, left = None, bottom = None, right = None, top = None) ylabel_coords = [0.0, 0.25] EvTDPD.plot_raw_TS(data.reshape(T,S1*S2), indices = [0], xlab = None, show_MAP_CPs = True, time_range = np.linspace(1,T, T, dtype=int), print_plt = False, ylab = "Response", ax = ax_array[0], custom_colors_series = ["black"]*5, custom_colors_CPs = [DPD_CP_color]* 100, custom_linestyles = [CP_style_DPD]*100, custom_linewidth = CP_linewidth_DPD, custom_transparency = CP_transparence_DPD, ylab_fontsize = ylabsize, yticks_fontsize = ticksize, ylabel_coords = [-0.06,0.5], additional_CPs = additional_CPs, custom_colors_additional_CPs = [KL_CP_color] * 100, custom_linewidth_additional_CPs = CP_linewidth_KL, custom_linestyles_additional_CPs = [CP_style_KL] * 10,
def TSOverlay(self,Cycle,**kwargs): Tmin=kwargs.get('Tmin',220.) Tmax=kwargs.get('Tmax',400.) Ref=kwargs.get('Ref','R290') self.figure=Figure(figsize=(6,4),dpi=100,facecolor='w') self.axes=self.figure.add_subplot(111) self.canvas=FigureCanvas(self,wx.ID_ANY,self.figure) Tsat = np.linspace(Tmin,PropsSI(Ref,"Tcrit")-0.0000000001,1000) (ssatL,ssatV)=(0.0*Tsat,0.0*Tsat) hcrit=np.linspace(0,0,2) pcrit=np.linspace(0,0,2) for i in np.arange(len(Tsat)): ssatL[i] = Props('S','T',Tsat[i],'Q',0,Ref) ssatV[i] = Props('S','T',Tsat[i],'Q',1,Ref) self.axes.plot(ssatL,Tsat,'k') self.axes.plot(ssatV,Tsat,'k') self.axes.set_xlabel('Entropy [kJ/kg-K]') self.axes.set_ylabel('Temperature [K]') s_comp=np.r_[Cycle.Compressor.sin_r/1000.,Cycle.Compressor.sout_r/1000.] T_comp=np.r_[Cycle.Compressor.Tin_r,Cycle.Compressor.Tout_r] self.axes.plot(s_comp,T_comp,'b') self.axes.plot(s_comp[0],T_comp[0],'bo') self.axes.plot(s_comp[1],T_comp[1],'bo') self.axes.text(s_comp[0],T_comp[0],' 1',ha='left',va='top') self.axes.text(s_comp[1],T_comp[1],' 2',ha='left',va='bottom') #DX systems and secondary loop in cooling mode have condenser if (Cycle.CycleType=='Secondary' and Cycle.Mode=='AC') or Cycle.CycleType=='DX': sL=Props('S','T',Cycle.Tdew_cond,'Q',0,Ref) sV=Props('S','T',Cycle.Tdew_cond,'Q',1,Ref) s_cond=np.r_[Cycle.Condenser.sin_r/1000., sV,sL,Cycle.Condenser.sout_r/1000.] T_cond=np.r_[Cycle.Condenser.Tin_r, Cycle.Tdew_cond,Cycle.Tdew_cond,Cycle.Condenser.Tout_r] self.axes.plot(s_cond,T_cond,'b') self.axes.plot(s_cond[3],T_cond[3],'bo') self.axes.text(s_cond[3],T_cond[3],'3$\quad\quad$',ha='right',va='bottom') self.axes.plot([s_cond[3],s_cond[0]],[Cycle.Condenser.Tin_a,Cycle.Condenser.Tout_a],'r') self.axes.text(0.5*s_cond[0]+0.5*s_cond[3],Cycle.Condenser.Tin_a,'Outdoor Air',backgroundcolor='w',ha='center',va='center') elif Cycle.CycleType=='Secondary' and Cycle.Mode=='HP': sV=Props('S','T',Cycle.Tdew_evap,'Q',1,Ref) s_evap=np.r_[Cycle.Evaporator.sin_r/1000., sV,Cycle.Evaporator.sout_r/1000.] T_evap=np.r_[Cycle.Evaporator.Tin_r, Cycle.Tdew_evap,Cycle.Evaporator.Tout_r] self.axes.plot(s_evap,T_evap,'b') self.axes.plot(s_evap[0],T_evap[0],'bo') self.axes.text(s_evap[0],T_evap[0],'4$\quad\quad$',ha='right',va='bottom') self.axes.plot([s_evap[2],s_evap[0]],[Cycle.Evaporator.Tin_a,Cycle.Evaporator.Tout_a],'r') self.axes.text(0.5*s_evap[0]+0.5*s_evap[2],Cycle.Evaporator.Tin_a,'Outdoor Air',backgroundcolor='w',ha='center',va='center') if Cycle.CycleType=="Secondary": if Cycle.IHXType=='Coaxial': IHX=Cycle.CoaxialIHX sV=Props('S','T',Cycle.Tdew_evap,'Q',1,Ref) s_IHX=np.r_[IHX.sin_r/1000., sV,IHX.sout_r/1000.] T_IHX=np.r_[IHX.Tin_r, Cycle.Tdew_evap,IHX.Tout_r] s_XV=np.r_[IHX.sin_r/1000.,Cycle.Condenser.sout_r/1000.] T_XV=np.r_[IHX.Tin_r,Cycle.Condenser.Tout_r] T_IHXg=np.r_[IHX.Tout_g,IHX.Tin_g] s_IHXg=np.r_[s_IHX[0],s_IHX[len(s_IHX)-1]] elif Cycle.IHXType=='PHE': if Cycle.Mode=='AC': IHX=Cycle.PHEIHX sV=Props('S','T',Cycle.Tdew_evap,'Q',1,Ref) s_IHX=np.r_[IHX.sin_c/1000., sV,IHX.sout_c/1000.] T_IHX=np.r_[IHX.Tin_c, Cycle.Tdew_evap,IHX.Tout_c] s_XV=np.r_[IHX.sin_c/1000.,Cycle.Condenser.sout_r/1000.] T_XV=np.r_[IHX.Tin_c,Cycle.Condenser.Tout_r] T_IHXg=np.r_[IHX.Tout_h,IHX.Tin_h] s_IHXg=np.r_[s_IHX[0],s_IHX[len(s_IHX)-1]] self.axes.text(s_IHX[0],T_IHX[0],'4$\quad\quad$',ha='right',va='top') self.axes.plot(s_IHX[0],T_IHX[0],'bo') else: IHX=Cycle.PHEIHX sL=Props('S','T',Cycle.Tbubble_cond,'Q',0,Ref) sV=Props('S','T',Cycle.Tdew_cond,'Q',1,Ref) s_IHX=np.r_[IHX.sin_h/1000., sV,sL,IHX.sout_h/1000.] T_IHX=np.r_[IHX.Tin_h, Cycle.Tdew_cond,Cycle.Tbubble_cond,IHX.Tout_h] s_XV=np.r_[Cycle.Evaporator.sin_r/1000.,IHX.sout_h/1000.] T_XV=np.r_[Cycle.Evaporator.Tin_r,IHX.Tout_h] T_IHXg=np.r_[IHX.Tout_c,IHX.Tin_c] s_IHXg=np.r_[s_IHX[0],s_IHX[len(s_IHX)-1]] self.axes.text(s_IHX[3],T_IHX[3],'3$\quad\quad$',ha='right',va='top') self.axes.plot(s_IHX[3],T_IHX[3],'bo') else: raise ValueError('Secondary loop system must have a coaxial or PHE heat exchanger') self.axes.plot(s_IHX,T_IHX,'b') self.axes.plot(s_XV,T_XV,'b') self.axes.plot([s_IHX[2],s_IHX[0]],[Cycle.CoolingCoil.Tin_a,Cycle.CoolingCoil.Tout_a],'r') self.axes.text(0.5*s_IHX[2]+0.5*s_IHX[0],Cycle.CoolingCoil.Tin_a,'Indoor Air',backgroundcolor='w',ha='center',va='center') self.axes.text(0.5*s_IHXg[0]+0.5*s_IHXg[1],np.mean(T_IHXg),'Glycol IHX',backgroundcolor='w',ha='center',va='center') self.axes.plot(s_IHXg,T_IHXg,'g-.') elif Cycle.CycleType=="DX": sL=Props('S','T',Cycle.Tdew_evap,'Q',0,Ref) sV=Props('S','T',Cycle.Tdew_evap,'Q',1,Ref) s_evap=np.r_[Cycle.Evaporator.sin_r/1000., sV,Cycle.Evaporator.sout_r/1000.] T_evap=np.r_[Cycle.Evaporator.Tsat_r, Cycle.Tdew_evap,Cycle.Evaporator.Tout_r] self.axes.plot(s_evap,T_evap,'b') self.axes.plot(s_evap[0],T_evap[0],'bo') self.axes.text(s_evap[0],T_evap[0],'4$\quad\quad$',ha='right',va='top') s_XV=np.r_[Cycle.Evaporator.sin_r/1000.,Cycle.Condenser.sout_r/1000.] T_XV=np.r_[Cycle.Evaporator.Tsat_r,Cycle.Condenser.Tout_r] self.axes.plot(s_XV,T_XV,'b') self.axes.plot([s_evap[2],s_evap[0]],[Cycle.Evaporator.Tin_a,Cycle.Evaporator.Tout_a],'r') self.axes.text(0.5*s_evap[2]+0.5*s_evap[0],Cycle.Evaporator.Tin_a,'Indoor Air',backgroundcolor='w',ha='center',va='center')
noise_variance = 0.25 #noise variance deviation = 4 #uncertainty in randomness of nonuniform spacing array_length = (L - 1) * d #Time = 1 #ts = 1/1e2 # duration in secs #t = np.arange(0,Time-ts,ts) #time snapshoots N = 40 #len(t) #number of snapshots received m = 1 #Number of sources Iterations = 200000 X_columns = 2 * L X_D = np.zeros(([Iterations, N, X_columns, 1])) X_data = np.zeros(([Iterations, N, L]), dtype=complex) Y_data = np.zeros(Iterations) position_x_u = np.linspace(-array_length / 2, array_length / 2, L) position_x_u = position_x_u.reshape(L, 1) #uniform positions for ULA def generate_random_signals(lower_bound, upper_bound, size, scale=None): sample_space = (lower_bound + upper_bound) / 2 if scale is None: scale = (upper_bound - lower_bound) / 2 results = [] while len(results) < size: samples = np.random.normal(loc=sample_space, scale=scale, size=size - len(results)) results += [ sample for sample in samples if lower_bound <= sample <= upper_bound
model = np.zeros(1400,dtype=np.float) def func2min(a): model = np.zeros(1400,dtype=np.float) for line in linelist: model = model + Q*profile_function(a,line[0],line[1]) return sum((model-data)**2/data) + 0*(sum(a**2)+sum(np.diff(a)**2)) x0 = np.ones(40,dtype=np.float) x = np.linspace(0,40, 40) x0 = np.exp(-np.power(x - len(x)/2., 2.) / (2 * np.power(4.5, 2.))) ''' print func2min(x0) import pylab pylab.plot(range(1400), func2min(x0), 'r') #pylab.plot(x, fcn2min(params, x,data), 'r') pylab.show() ''' model = np.zeros(1400,dtype=np.float) for line in linelist: model = model + Q*profile_function(x0,line[0],line[1])
def __init__( self, num_qubits: Union[int, List[int]], mu: Optional[Union[float, List[float]]] = None, sigma: Optional[Union[float, List[float]]] = None, bounds: Optional[Union[Tuple[float, float], List[Tuple[float, float]]]] = None, upto_diag: bool = False, name: str = "P(X)", ) -> None: r""" Args: num_qubits: The number of qubits used to discretize the random variable. For a 1d random variable, ``num_qubits`` is an integer, for multiple dimensions a list of integers indicating the number of qubits to use in each dimension. mu: The parameter :math:`\mu` of the distribution. Can be either a float for a 1d random variable or a list of floats for a higher dimensional random variable. sigma: The parameter :math:`\sigma^2` or :math:`\Sigma`, which is the variance or covariance matrix. bounds: The truncation bounds of the distribution as tuples. For multiple dimensions, ``bounds`` is a list of tuples ``[(low0, high0), (low1, high1), ...]``. If ``None``, the bounds are set to ``(0, 1)`` for each dimension. upto_diag: If True, load the square root of the probabilities up to multiplication with a diagonal for a more efficient circuit. name: The name of the circuit. """ warnings.warn( "`LogNormalDistribution` is deprecated as of version 0.17.0 and will be " "removed no earlier than 3 months after the release date. " "It moved to qiskit_finance.circuit.library.LogNormalDistribution.", DeprecationWarning, stacklevel=2, ) _check_dimensions_match(num_qubits, mu, sigma, bounds) _check_bounds_valid(bounds) # set default arguments dim = 1 if isinstance(num_qubits, int) else len(num_qubits) if mu is None: mu = 0 if dim == 1 else [0] * dim if sigma is None: sigma = 1 if dim == 1 else np.eye(dim) if bounds is None: bounds = (0, 1) if dim == 1 else [(0, 1)] * dim if not isinstance(num_qubits, list): # univariate case super().__init__(num_qubits, name=name) x = np.linspace(bounds[0], bounds[1], num=2 ** num_qubits) # evaluation points else: # multivariate case super().__init__(sum(num_qubits), name=name) # compute the evaluation points using numpy's meshgrid # indexing 'ij' yields the "column-based" indexing meshgrid = np.meshgrid( *( np.linspace(bound[0], bound[1], num=2 ** num_qubits[i]) for i, bound in enumerate(bounds) ), indexing="ij", ) # flatten into a list of points x = list(zip(*(grid.flatten() for grid in meshgrid))) # compute the normalized, truncated probabilities probabilities = [] from scipy.stats import multivariate_normal for x_i in x: # map probabilities from normal to log-normal reference: # https://stats.stackexchange.com/questions/214997/multivariate-log-normal-probabiltiy-density-function-pdf if np.min(x_i) > 0: det = 1 / np.prod(x_i) probability = multivariate_normal.pdf(np.log(x_i), mu, sigma) * det else: probability = 0 probabilities += [probability] normalized_probabilities = probabilities / np.sum(probabilities) # store as properties self._values = x self._probabilities = normalized_probabilities self._bounds = bounds # use default the isometry (or initialize w/o resets) algorithm to construct the circuit # pylint: disable=no-member if upto_diag: self.isometry(np.sqrt(normalized_probabilities), self.qubits, None) else: from qiskit.extensions import Initialize # pylint: disable=cyclic-import initialize = Initialize(np.sqrt(normalized_probabilities)) circuit = initialize.gates_to_uncompute().inverse() self.compose(circuit, inplace=True)
def __init__(self, num_samples, batch_size, minimum_lr=1e-5, maximum_lr=10., lr_scale='exp', validation_data=None, validation_sample_rate=5, stopping_criterion_factor=4., loss_smoothing_beta=0.98, save_dir=None, verbose=True): """ This class uses the Cyclic Learning Rate history to find a set of learning rates that can be good initializations for the One-Cycle training proposed by Leslie Smith in the paper referenced below. A port of the Fast.ai implementation for Keras. # Note This requires that the model be trained for exactly 1 epoch. If the model is trained for more epochs, then the metric calculations are only done for the first epoch. # Interpretation Upon visualizing the loss plot, check where the loss starts to increase rapidly. Choose a learning rate at somewhat prior to the corresponding position in the plot for faster convergence. This will be the maximum_lr lr. Choose the max value as this value when passing the `max_val` argument to OneCycleLR callback. Since the plot is in log-scale, you need to compute 10 ^ (-k) of the x-axis # Arguments: num_samples: Integer. Number of samples in the dataset. batch_size: Integer. Batch size during training. minimum_lr: Float. Initial learning rate (and the minimum). maximum_lr: Float. Final learning rate (and the maximum). lr_scale: Can be one of ['exp', 'linear']. Chooses the type of scaling for each update to the learning rate during subsequent batches. Choose 'exp' for large range and 'linear' for small range. validation_data: Requires the validation dataset as a tuple of (X, y) belonging to the validation set. If provided, will use the validation set to compute the loss metrics. Else uses the training batch loss. Will warn if not provided to alert the user. validation_sample_rate: Positive or Negative Integer. Number of batches to sample from the validation set per iteration of the LRFinder. Larger number of samples will reduce the variance but will take longer time to execute per batch. If Positive > 0, will sample from the validation dataset If Megative, will use the entire dataset stopping_criterion_factor: Integer or None. A factor which is used to measure large increase in the loss value during training. Since callbacks cannot stop training of a model, it will simply stop logging the additional values from the epochs after this stopping criterion has been met. If None, this check will not be performed. loss_smoothing_beta: Float. The smoothing factor for the moving average of the loss function. save_dir: Optional, String. If passed a directory path, the callback will save the running loss and learning rates to two separate numpy arrays inside this directory. If the directory in this path does not exist, they will be created. verbose: Whether to print the learning rate after every batch of training. # References: - [A disciplined approach to neural network hyper-parameters: Part 1 -- learning rate, batch size, weight_decay, and weight decay](https://arxiv.org/abs/1803.09820) """ super(LRFinder, self).__init__() if lr_scale not in ['exp', 'linear']: raise ValueError("`lr_scale` must be one of ['exp', 'linear']") if validation_data is not None: self.validation_data = validation_data self.use_validation_set = True if validation_sample_rate > 0 or validation_sample_rate < 0: self.validation_sample_rate = validation_sample_rate else: raise ValueError( "`validation_sample_rate` must be a positive or negative integer other than o" ) else: self.use_validation_set = False self.validation_sample_rate = 0 self.num_samples = num_samples self.batch_size = batch_size self.initial_lr = minimum_lr self.final_lr = maximum_lr self.lr_scale = lr_scale self.stopping_criterion_factor = stopping_criterion_factor self.loss_smoothing_beta = loss_smoothing_beta self.save_dir = save_dir self.verbose = verbose self.num_batches_ = num_samples // batch_size - 1 self.current_lr_ = minimum_lr if lr_scale == 'exp': self.lr_multiplier_ = (maximum_lr / float(minimum_lr))**( 1. / float(self.num_batches_)) else: extra_batch = int((num_samples % batch_size) != 0) self.lr_multiplier_ = np.linspace(minimum_lr, maximum_lr, num=self.num_batches_ + extra_batch) # If negative, use entire validation set if self.validation_sample_rate < 0: self.validation_sample_rate = self.validation_data[0].shape[ 0] // batch_size self.current_batch_ = 0 self.current_epoch_ = 0 self.best_loss_ = 1e6 self.running_loss_ = 0. self.history = {}
def PHOverlay(self,Cycle,**kwargs): Tmin=kwargs.get('Tmin',220.) Tmax=kwargs.get('Tmax',400.) Ref=kwargs.get('Ref','R290') self.figure=Figure(figsize=(6,4),dpi=100,facecolor='w') self.axes=self.figure.add_subplot(111) self.canvas=FigureCanvas(self,wx.ID_ANY,self.figure) Tsat = np.linspace(Tmin,PropsSI(Ref,"Tcrit")-0.0000000001,1000) (hsatL,hsatV)=(0.0*Tsat,0.0*Tsat) (psatL,psatV)=(0.0*Tsat,0.0*Tsat) for i in np.arange(len(Tsat)): psatL[i] = Props('P','T',Tsat[i],'Q',0,Ref) psatV[i] = Props('P','T',Tsat[i],'Q',1,Ref) hsatL[i] = Props('H','T',Tsat[i],'Q',0,Ref) hsatV[i] = Props('H','T',Tsat[i],'Q',1,Ref) self.axes.plot(hsatL,psatL,'k') self.axes.plot(hsatV,psatV,'k') self.axes.set_xlabel('Enthalpy [kJ/kg]') self.axes.set_ylabel('Pressure [kPa]') h_comp=np.r_[Cycle.Compressor.hin_r/1000.,Cycle.Compressor.hout_r/1000.] p_comp=np.r_[Cycle.Compressor.pin_r,Cycle.Compressor.pout_r] self.axes.plot(h_comp,p_comp,'b') self.axes.plot(h_comp[0],p_comp[0],'bo') self.axes.plot(h_comp[1],p_comp[1],'bo') self.axes.text(h_comp[0],p_comp[0],' 1',ha='left',va='top') self.axes.text(h_comp[1],p_comp[1],' 2',ha='left',va='bottom') if Cycle.CycleType=='Secondary' and Cycle.Mode=='HP': h_evap=np.r_[Cycle.Evaporator.hin_r/1000.,Cycle.Evaporator.hout_r/1000.] p_evap=np.r_[Cycle.Evaporator.psat_r, Cycle.Evaporator.psat_r] self.axes.plot(h_evap,p_evap,'b') self.axes.plot(h_evap[0],p_evap[0],'bo') self.axes.text(h_evap[0],p_evap[0],'4$\quad\quad$',ha='right',va='bottom') else: h_cond=np.r_[Cycle.Condenser.hin_r/1000.,Cycle.Condenser.hout_r/1000.] p_cond=np.r_[Cycle.Condenser.psat_r, Cycle.Condenser.psat_r] self.axes.plot(h_cond,p_cond,'b') self.axes.plot(h_cond[1],p_cond[1],'bo') self.axes.text(h_cond[1],p_cond[1],'3$\quad\quad$',ha='right',va='bottom') if Cycle.CycleType=="Secondary": if Cycle.IHXType=='Coaxial': IHX=Cycle.CoaxialIHX h_IHX=np.r_[IHX.hin_r/1000., IHX.hout_r/1000.] p_IHX=np.r_[IHX.pin_r, IHX.pin_r] h_XV=np.r_[IHX.hin_r/1000.,Cycle.Condenser.hout_r/1000.] p_XV=np.r_[IHX.pin_r,Cycle.Condenser.psat_r] elif Cycle.IHXType=='PHE': IHX=Cycle.PHEIHX if Cycle.Mode=='AC': h_IHX=np.r_[IHX.hin_c/1000., IHX.hout_c/1000.] p_IHX=np.r_[IHX.pin_c, IHX.pin_c] h_XV=np.r_[IHX.hin_c/1000.,Cycle.Condenser.hout_r/1000.] p_XV=np.r_[IHX.pin_c,Cycle.Condenser.psat_r] self.axes.plot(h_IHX[0],p_IHX[0],'bo') self.axes.text(h_IHX[0],p_IHX[0],'4$\quad\quad$',ha='right',va='top') else: h_IHX=np.r_[IHX.hin_h/1000., IHX.hout_h/1000.] p_IHX=np.r_[IHX.pin_h, IHX.pin_h] h_XV=np.r_[Cycle.Evaporator.hin_r/1000.,IHX.hout_h/1000.] p_XV=np.r_[Cycle.Evaporator.psat_r,IHX.pin_h] self.axes.plot(h_IHX[1],p_IHX[1],'bo') self.axes.text(h_IHX[1],p_IHX[1],'3$\quad\quad$',ha='right',va='top') else: raise ValueError('Secondary loop system must have a coaxial or PHE heat exchanger') self.axes.plot(h_IHX,p_IHX,'b') self.axes.plot(h_XV,p_XV,'b') elif Cycle.CycleType=="DX": h_evap=np.r_[Cycle.Evaporator.hin_r/1000.,Cycle.Evaporator.hout_r/1000.] p_evap=np.r_[Cycle.Evaporator.psat_r,Cycle.Evaporator.psat_r] self.axes.plot(h_evap,p_evap,'b') self.axes.plot(h_evap[0],p_evap[0],'bo') self.axes.text(h_evap[0],p_evap[0],'4$\quad\quad$',ha='right',va='top') h_XV=np.r_[Cycle.Evaporator.hin_r/1000.,Cycle.Condenser.hout_r/1000.] p_XV=np.r_[Cycle.Evaporator.psat_r,Cycle.Condenser.psat_r] self.axes.plot(h_XV,p_XV,'b')
def test_DataSet_plotCutQELine(): Points = np.array([[0.7140393034102988,-0.4959224853328328], [1.128363301356428,-1.6520150761601147], [1.9002545852012716,-0.9393552598967219], [1.0432282332853056,-0.12375569239528339]],dtype=float) QPoints = np.zeros((Points.shape[0],3)) QPoints[:,:2]=Points EnergyBins = np.linspace(1.7,2.7,11) minPixel = 0.001 width=0.1 import matplotlib matplotlib.use('Agg') DataFile = [os.path.join(dataPath,'camea2018n000136.hdf'),os.path.join(dataPath,'camea2018n000137.hdf')] dataset = DataSet(convertedFiles=DataFile) dataset.convertDataFile(saveFile=False) try: # No Q-points dataset.plotCutQELine([],EnergyBins,width=width,minPixel=minPixel,rlu=False) assert False except AttributeError: assert True try: # No points in E range dataset.plotCutQELine(QPoints,EnergyBins+100,width=width,minPixel=minPixel,rlu=True,vmin=0.0,vmax=1.5e-6,ticks=10) assert False except AttributeError: assert True try: # No wrong dim of QPonts dataset.plotCutQELine(QPoints,EnergyBins,width=width,minPixel=minPixel,rlu=False) assert False except AttributeError: assert True try: # No wrong dim of QPonts dataset.plotCutQELine(QPoints[:,:2],EnergyBins,width=width,minPixel=minPixel,rlu=True) assert False except AttributeError: assert True fig = plt.figure() ax = fig.gca() ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = dataset.plotCutQELine( QPoints[:,:2],EnergyBins,width=width,minPixel=minPixel,rlu=False,ax=ax,vmin=0.0,vmax=1.5e-6,log=True,seperatorWidth=3) HKLPoints = np.array([[1.0,0.0,0.0], [0.5,1.5,0.0], [1.7,-0.1,0.0], [1.0,1.0,0.0]]) ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = dataset.plotCutQELine( HKLPoints,EnergyBins,width=width,minPixel=minPixel,rlu=True,plotSeperator = False,ticks=1,tickRound=1,colorbar=True,log=True) # 3D from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap cmap = plt.cm.coolwarm my_cmap = cmap(np.arange(cmap.N)) my_cmap[:,-1] = np.linspace(0, 1, cmap.N) my_cmap = ListedColormap(my_cmap) fig = plt.figure(figsize=(10,11)) ax = fig.add_subplot(111, projection='3d') Energies = np.concatenate(dataset.energy,axis=0) E = np.arange(Energies.min()+0.35,Energies.max(),0.35) ax,DataList,BinListTotal,centerPositionTotal,binDistanceTotal = \ dataset.plotCutQELine(QPoints=HKLPoints,EnergyBins=E,ax = ax,width=0.05,minPixel=0.01, vmin=7.5e-7,vmax=7e-6,cmap=cmap,rlu=True) plt.close('all')
imgplot = ax[0,1].imshow ( ColorE, extent = [ Xleft, Xright, Ydown, Yup ], origin = 'lower' , interpolation = 'gaussian' ) #ax[0,1]=plt.gca() circle = np.array( [ plt.Circle((x0[i], y0[i]), R[i], color='r', fill=False) for i in range(n) ] ).reshape(-1) #circle = np.array([[plt.Circle((x0[2*i], y0[2*i]), R[2*i], color='r', fill=False) , plt.Circle((x0[2*i+1], y0[2*i+1]), R[2*i+1], color='b', fill=False)] for i in range(n//2)]).reshape(-1) for i in range(n): ax[0,1].add_artist(circle[i]) ax[0,1].set_xlabel (r'$x$') #ax[0,1].set_ylabel (r'$y$') ax[0,1].set_title (r'$f = $%4.2f'%(f2)) countY1, countX1 = E1.shape ax[1,0].set_ylim((0,2.5)) ax[1,0].plot(np.linspace(Ydown, Yup, countY1), np.abs(E1[:,countX1//2])) ax[1,0].set_ylabel(r"$|E|$") ax[1,0].set_xlabel(r"$y$") countY2, countX2 = E2.shape ax[1,1].set_ylim((0,2.5)) ax[1,1].plot(np.linspace(Ydown, Yup, countY2), np.abs(E2[:,countX2//2])) #ax[1,1].set_ylabel(r"$|E|$") ax[1,1].set_xlabel(r"$y$") #plt.colorbar ( imgplot, orientation='horizontal' ) plt.savefig("./TeXy/images/"+plotName+".pdf", bbox_inches='tight') #plt.show ()
def test_DataSet_plotQPlane(): plt.ioff() import matplotlib matplotlib.use('Agg') convertFiles = [os.path.join(dataPath,'camea2018n000137.hdf')]#'TestData/ManuallyChangedData/A3.hdf')] Datset = DataSet(dataFiles = convertFiles) Datset.convertDataFile(saveFile=True) EmptyDS = DataSet() try: Datset.plotQPlane() # No Bins, Emin or Emax assert False except AttributeError: assert True try: Datset.plotQPlane(EBins=[10]) # Length of bins is 1 assert False except AttributeError: assert True try: Datset.plotQPlane(EMin=20,EMax=10) # EMin>EMax assert False except AttributeError: assert True try: EmptyDS.plotQPlane(EMin=2,EMax=3) # Empty DataSet assert False except AttributeError: assert True EMin = np.min(Datset.energy) EMax = EMin+0.5 Data,[Qx,Qy],ax1 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=True,log=False,rlu=True) Data,[Qx,Qy],ax2 = Datset.plotQPlane(EMin,EMax,binning='polar',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,log=True,rlu=True) fig,AX = plt.subplots() Data,[Qx,Qy],ax3 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,ax=AX,colorbar=True,vmin=0,vmax=1e-6,zorder=10) ax1.set_clim(-20,-15) ax2.set_clim(0,1e-6) Data,[Qx,Qy],ax3 = Datset.plotQPlane(EMin,EMax,binning='xy',xBinTolerance=0.05,yBinTolerance=0.05) cmap = plt.cm.coolwarm Dataset = DataSet(dataFiles=convertFiles) for d in Dataset.dataFiles: d.A3Off +=90 # rotate data to fall into problem of arctan2 Data,[Qx,Qy],ax2 = Datset.plotQPlane(EMin,EMax,binning='polar',xBinTolerance=0.05,yBinTolerance=0.05,enlargen=False,log=True,rlu=True,cmap=cmap) QxShape = np.array(Qx[0]).shape QyShape = np.array(Qy[0]).shape assert(QxShape==QyShape) assert(np.all(np.array(Data[0][0]).shape == np.array(QxShape)-np.array([1,1]))) try: Datset.plotQPlane(EMin,EMax,binning='notABinningMethod') assert False except: assert True # 3D from mpl_toolkits.mplot3d import Axes3D from matplotlib.colors import ListedColormap cmap = plt.cm.coolwarm my_cmap = cmap(np.arange(cmap.N)) my_cmap[:,-1] = np.linspace(0, 1, cmap.N) my_cmap = ListedColormap(my_cmap) fig = plt.figure(figsize=(10,11)) ax = fig.add_subplot(111, projection='3d') Energies = np.concatenate(Datset.energy,axis=0) E = np.arange(Energies.min()+0.35,Energies.max(),0.35) [I,Monitor,Norm,NormCount],[xBins,yBins],ax = \ Datset.plotQPlane(EBins=E,ax = ax,xBinTolerance=0.03,yBinTolerance=0.03, binning='polar',vmin=7.5e-7,vmax=7e-6,antialiased=True,cmap=cmap,rlu=True,extend='max') plt.close('all')
haldane.add_hop(t1, 1, 0, [ 0, 1]) # add second neighbour complex hoppings haldane.add_hop(t2 , 0, 0, [ 0, -1]) haldane.add_hop(t2 , 0, 0, [ 1, 0]) haldane.add_hop(t2 , 0, 0, [ -1, 1]) haldane.add_hop(t2 , 1, 1, [ -1, 0]) haldane.add_hop(t2 , 1, 1, [ 1,-1]) haldane.add_hop(t2 , 1, 1, [ 0, 1]) return haldane # Define the model for a fixed set of parameters haldane=HaldaneTB(2,1,1/3,np.pi/10) # Call the interface for TBmodels to define the system class syst = wb.System_TBmodels(haldane, berry=True, morb=True) Efermi=np.linspace(-4,6,1000) # Define some symmetries syst.set_symmetry(['C3z']) # After defining the symmetries, create the grid class grid=wb.Grid(syst,NK=(200,200,1),NKFFT=(20,20,1)) # Define which quantities are going to be integrated q_int=["dos","ahc","Morb"] seedname="tbmodels_Haldane" num_iter=10 wb.integrate(syst, grid=grid, Efermi=Efermi, smearEf=300, # 10K quantities=q_int, numproc=8, adpt_num_iter=num_iter,