def butter_filter(freq, fs=RATE, order=5): nyq = 0.5 * fs low = freq / nyq b, a = butter(order, low, 'lowpass') for i in streamData: i = np.asArray(i) i = lfilter(b, a, i) i = np.tolist(i)
def convert_NP_to_LIST(self, np) -> list: """ numpy의 array 형식의 데이터를 list로 변환 :return: list 자료형의 값 """ list = np.tolist() return list
def concDisOxySaturated(pressure_mmHg, Temperature_degC): # Calibration Table # 160910 # http://www.vernier.com/files/manuals/odo-bta/odo-bta.pdf # 100% SATURATED VALUES x_pressmmHg = [770., 760., 750., 740.] # PRESSURE mmHg x_pressmmHg = np.array(x_pressmmHg) y_degC = [ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12., 14., 16., 18., 20., 22., 24., 26., 28., 30., 32., 34. ] # TEMPERATURE degC y_degC = np.array(y_degC) z_mgPerL = [ # 770 , 760 , 750 ,740 [14.76, 14.57, 14.38, 14.19], # 0 degC [14.38, 14.19, 14, 13.82], # 1 [14.01, 13.82, 13.64, 13.46], # 2 [13.65, 13.47, 13.29, 13.12], # 3 [13.31, 13.13, 12.96, 12.79], # 4 [12.97, 12.81, 12.64, 12.47], # 5 [12.66, 12.49, 12.33, 12.16], # 6 [12.35, 12.19, 12.03, 11.87], # 7 [12.05, 11.90, 11.74, 11.58], # 8 [11.77, 11.62, 11.46, 11.31], #9 [11.50, 11.35, 11.20, 11.05], #10 [11.24, 11.09, 10.94, 10.80], #11 [10.98, 10.84, 10.70, 10.56], #12 [10.51, 10.37, 10.24, 10.10], #14 [10.07, 9.94, 9.81, 9.68], #16 [9.67, 9.54, 9.41, 9.29], #18 [9.29, 9.17, 9.05, 8.93], #20 [8.94, 8.83, 8.71, 8.59], #22 [8.62, 8.51, 8.40, 8.28], #24 [8.32, 8.21, 8.10, 7.99], #26 [8.04, 7.93, 7.83, 7.72], #28 [7.77, 7.67, 7.57, 7.47], #30 [7.51, 7.42, 7.32, 7.22], #32 [7.27, 7.17, 7.08, 6.98], #34 ] z_mgPerL = np.array(z_mgPerL) # scipy.interpolate.interp2d # http://docs.scipy.org/doc/scipy-0.13.0/reference/generated/scipy.interpolate.interp2d.html # # Define function to call _concDisOxySaturated = interpolate.interp2d(x_pressmmHg, y_degC, z_mgPerL, kind='linear') x = _concDisOxySaturated(pressure_mmHg, Temperature_degC) return np.tolist()
def convert_NP_to_LIST(self, np, dtype=None): """ numpy의 array 형식의 데이터를 list로 변환 :param np: :param dtype: :return: list 자료형의 값 """ list = np.tolist() return list
def np_to_list(self, np, dtype=None): list = np.tolist() return list
#Support multidimensional arrays and matrices. #It also support wide range of mathematical operations. #Numpy import numpy as np ndarray - an N-dimensional array, which describes a collection of “items” of the same type array(list) # constructor asarray(a[, dtype, order]) # Convert the input to an array Constants: ndarray.shape #tuple of array dimensions ndarray.size #number of elements in array ndarray.itemsize #size of one element ndarray.dtype #data type of elements ndarray.flat #1D iterator over elements of array Common Functions np.tolist() #Return the array as a (possibly nested) list. np.reshape(a, (3,2)) #Returns an array containing the same data with a new shape. np.swapaxes(axis1, axis2) #Return a view of the array with axis1 and axis2 interchanged. np.copy() #Return a copy of the array. np.arange() #Return evenly spaced values within a given interval. Statistics Functions: np.sum(a, axis) #Sum of array elements over a given axis. np.prod #Return the product of array elements over a given axis. np.min #Return the minimum along a given axis. np.max #Return the maximum along a given axis. np.mean #Compute the arithmetic mean along the specified axis. np.std #Compute the standard deviation along the specified axis. np.var #Compute the variance along the specified axis. np.sort(axis) #Return a sorted copy of an array. Other Functions: String operations #A set of vectorized string operations for arrays.
def array2param(array,ptype): if ptype == 'list': return np.tolist(array) if ptype == 'scalar': return array[0]
def heat_eq_ui(): """ Solve heat equation with arguments (all are optional) from the commands line; Type of solver, constants, initial dist. from file, animation etc. Run with "-h" for a complete description of available commands. When using timeit via "-time RUNS ITER" animation and other output are ignored. User settings i.e. f, m, t0 etc. are used if acceptable. """ parser = argparse.ArgumentParser() parser.add_argument("-time", nargs=2, help="Turn on timeit-module. "+ \ "Run ARG1 tests with ARG2 iterations", type=int) parser.add_argument("-n", default=50, help="The mesh points in X-direction", type=int) parser.add_argument("-m", default=100, help="The mesh points in Y-direction", type=int) parser.add_argument("-t0", default=0, help="The start time of computations [sec]", type=int) parser.add_argument("-t1", default=1000, help="The end time of computations [sec]", type=int) parser.add_argument("-dt", default=0.1, help="The time step (temporal resolution)", type=float) parser.add_argument("-nu", default=1.0, help="The thermal diffusivity", type=float) parser.add_argument("-f", default=1.0, help="The constant heat source term", type=float) parser.add_argument("-o", "-output", help="Filename (save to disk) of final solution u", type=str) parser.add_argument("-i", "-input", help="Filename (read from disk) of initial u", type=str) parser.add_argument("-s", "-save", help='Save plot of last solution: "last_u.png"', action="store_true") parser.add_argument("-v", "-verbose", help="Increase output verbosity", action="store_true") parser.add_argument("-a", "-anim", help="Animate solution while computation runs", action="store_true") group = parser.add_mutually_exclusive_group( ) # Pick only one solver-method group.add_argument("-python", help="Solve problem with pure python objects", action="store_true") group.add_argument("-numpy", help="Solve problem with NumPy", action="store_true") group.add_argument("-weave", help="Solve problem with Weave", action="store_true") # Store user options with readable names args = parser.parse_args() dt = args.dt n = args.n m = args.m t0 = args.t0 t1 = args.t1 nu = args.nu f_constant = args.f verbose = args.v save_last_fig = args.s show_animation = args.a # File handling switches use_timeit = False if not args.time else True output_last_u_to_file = False if not args.o else True change_initial_u = False if not args.i else True print_progress = True if verbose else False if use_timeit: timeit_repeats = args.time[0] timeit_iter = args.time[1] # Set method for solver method = SolverPurePython if args.python else SolverNumpy if args.numpy else SolverWeave if args.weave else None scheme_name = 'Python' if args.python else 'Numpy' if args.numpy else 'Weave' if args.weave else None if not method: if verbose: print "\nNo method specified. Choosing 'weave' for speed!" method = SolverWeave scheme_name = 'Weave' # Give the user options if dt is unstable/too large # dt <= dx*dy / (4*nu) (and we have dx=dy=1 for any mesh size, see report) max_stable_dt = 1.0 / (4 * nu) if dt > max_stable_dt: print "\nThe chosen dt (%.2e) is too large, solution might be unstable!" % dt print "Choose what to do:" print "- Press enter to use the max. stable dt (%.2e) and continue" % max_stable_dt print "- Enter 'c' or 'cont' to continue anyway, or" user_choice = raw_input( "- Enter 'exit' (or anything else than the above options) to quit\n" ) if not user_choice: dt = max_stable_dt elif user_choice in ['c', 'cont']: pass else: sys.exit(1) # Check that time parameters makes sense if t0 >= t1 or t0 < 0: print "\nStart time must be larger then end time. Also, start time can't be negative" sys.exit(1) # Load initial temp. dist. from file if specified. # Using a human readable text format (little slower than np.save or pickle) if change_initial_u: if verbose: print "\nReading initial temperature distribution u0 from file" filename = args.i try: initial_u = np.loadtxt(filename) except: print "File does not exit or is not in txt-format. Exiting..." sys.exit(1) if method == SolverPurePython: # Must convert to nested list initial_u = np.tolist(initial_u) n_i = initial_u.shape[0] m_i = initial_u.shape[1] if n != n_i or m != m_i: print "\nMesh dimensions of initial u from file (%d,%d) does NOT match" % ( n_i, m_i) print "user (or default) specified values: (%d,%d)\nExiting..." % ( n, m) sys.exit(1) else: initial_u = None # If timeit is used and method = PurePython, give the user a warning if method == SolverPurePython and use_timeit: timeit_total_iter = timeit_repeats * timeit_iter # Total number of iterations (i.e. runs of solver) if timeit_total_iter >= 2 and t1 - t0 >= 200: estimate_time_used = int((t1 - t0) / 1000. * 55) print "\nWarning: Testing the pure python implementation is really slow. " if verbose: print "Rough time estimate per iteration (and total time): %d, (%d) seconds" \ %(estimate_time_used, timeit_total_iter*estimate_time_used) raw_input('Press enter to continue..') # Fill the source term f (as a list or array) if method == SolverPurePython: f = SourceTermF_LIST(n, m, f_constant) else: # All other methods use arrays f = SourceTermF_ARRAY(n, m, f_constant) # One call to rule them all if use_timeit: if verbose: print "\nWhen running timeit, some user specified settings might" print "be ignored for consistency and reproducability" if method == SolverPurePython: # Sorry for long lines of code, but I get indent error otherwise... setup_timeit = "from heat_equation import SolverPurePython, SourceTermF_LIST; method = SolverPurePython; f = SourceTermF_LIST(%d,%d,%f)" % ( n, m, f_constant) elif method == SolverNumpy: setup_timeit = "from heat_equation_numpy import SolverNumpy, SourceTermF_ARRAY; method = SolverNumpy; f = SourceTermF_ARRAY(%d,%d,%f)" % ( n, m, f_constant) else: setup_timeit = "from heat_equation_weave import SolverWeave, SourceTermF_ARRAY; method = SolverWeave; f = SourceTermF_ARRAY(%d,%d,%f)" % ( n, m, f_constant) solver_call = "u = method(f,%f,%f,%d,%d,%d,%d,None,False,False)" % ( nu, dt, n, m, t0, t1) timeit_results = timeit.Timer(solver_call, setup=setup_timeit).repeat( timeit_repeats, timeit_iter) best_time = min(timeit_results) / float( timeit_iter ) # All noise in data is "positive", so minimum time is most accurate if verbose: print "\nTest repeats: %d, each with %d iterations" % ( timeit_repeats, timeit_iter) print "Settings: f=1,nu=%.1f,dt=%.1f,n=%d,m=%d,t0=%d,t1=%d" % ( nu, dt, n, m, t0, t1) print "Minimum CPU-time of scheme '%s': %f seconds" % (scheme_name, best_time) else: print "Min. CPU-time: %f sec. (%s)" % (best_time, scheme_name) else: u = method(f,nu,dt,n,m,t0,t1,initial_u, \ show_animation=show_animation,print_progress=verbose) if verbose: # Need to add some spacing for aesthetical purposes print "" print u.max() # Save last u if output_last_u_to_file: if verbose: print "\nSaving final temperature distribution u to file" filename = args.o np.savetxt(filename, u) # Works with both nested list and array if save_last_fig: if verbose: print "\nSaving the final temperature plot of u to 'last_u.png'" plt.ion() im = plt.imshow(zip(*u), cmap='gray') # Initiate plotting / animation plt.title('u(x,y,t=%d)' % (t1)) # Update title time plt.xlabel('X') plt.ylabel('Y') if not show_animation: # Do not add a second colorbar if already added! plt.colorbar(im) plt.savefig('last_u.png')
def heat_eq_ui(): """ Solve heat equation with arguments (all are optional) from the commands line; Type of solver, constants, initial dist. from file, animation etc. Run with "-h" for a complete description of available commands. When using timeit via "-time RUNS ITER" animation and other output are ignored. User settings i.e. f, m, t0 etc. are used if acceptable. """ parser = argparse.ArgumentParser() parser.add_argument("-time", nargs=2, help="Turn on timeit-module. "+ \ "Run ARG1 tests with ARG2 iterations", type=int) parser.add_argument("-n", default=50, help="The mesh points in X-direction", type=int) parser.add_argument("-m", default=100, help="The mesh points in Y-direction", type=int) parser.add_argument("-t0", default=0, help="The start time of computations [sec]", type=int) parser.add_argument("-t1", default=1000, help="The end time of computations [sec]", type=int) parser.add_argument("-dt", default=0.1, help="The time step (temporal resolution)", type=float) parser.add_argument("-nu", default=1.0, help="The thermal diffusivity", type=float) parser.add_argument("-f", default=1.0, help="The constant heat source term", type=float) parser.add_argument("-o", "-output", help="Filename (save to disk) of final solution u", type=str) parser.add_argument("-i", "-input", help="Filename (read from disk) of initial u" , type=str) parser.add_argument("-s", "-save", help='Save plot of last solution: "last_u.png"', action="store_true") parser.add_argument("-v", "-verbose", help="Increase output verbosity", action="store_true") parser.add_argument("-a", "-anim", help="Animate solution while computation runs", action="store_true") group = parser.add_mutually_exclusive_group() # Pick only one solver-method group.add_argument("-python", help="Solve problem with pure python objects", action="store_true") group.add_argument("-numpy", help="Solve problem with NumPy", action="store_true") group.add_argument("-weave", help="Solve problem with Weave", action="store_true") # Store user options with readable names args = parser.parse_args() dt = args.dt n = args.n; m = args.m t0 = args.t0; t1 = args.t1 nu = args.nu f_constant = args.f verbose = args.v save_last_fig = args.s show_animation = args.a # File handling switches use_timeit = False if not args.time else True output_last_u_to_file = False if not args.o else True change_initial_u = False if not args.i else True print_progress = True if verbose else False if use_timeit: timeit_repeats = args.time[0] timeit_iter = args.time[1] # Set method for solver method = SolverPurePython if args.python else SolverNumpy if args.numpy else SolverWeave if args.weave else None scheme_name = 'Python' if args.python else 'Numpy' if args.numpy else 'Weave' if args.weave else None if not method: if verbose: print "\nNo method specified. Choosing 'weave' for speed!" method = SolverWeave scheme_name = 'Weave' # Give the user options if dt is unstable/too large # dt <= dx*dy / (4*nu) (and we have dx=dy=1 for any mesh size, see report) max_stable_dt = 1.0/(4*nu) if dt > max_stable_dt: print "\nThe chosen dt (%.2e) is too large, solution might be unstable!" %dt print "Choose what to do:" print "- Press enter to use the max. stable dt (%.2e) and continue" %max_stable_dt print "- Enter 'c' or 'cont' to continue anyway, or" user_choice = raw_input("- Enter 'exit' (or anything else than the above options) to quit\n") if not user_choice: dt = max_stable_dt elif user_choice in ['c','cont']: pass else: sys.exit(1) # Check that time parameters makes sense if t0 >= t1 or t0 < 0: print "\nStart time must be larger then end time. Also, start time can't be negative" sys.exit(1) # Load initial temp. dist. from file if specified. # Using a human readable text format (little slower than np.save or pickle) if change_initial_u: if verbose: print "\nReading initial temperature distribution u0 from file" filename = args.i try: initial_u = np.loadtxt(filename) except: print "File does not exit or is not in txt-format. Exiting..."; sys.exit(1) if method == SolverPurePython: # Must convert to nested list initial_u = np.tolist(initial_u) n_i = initial_u.shape[0] m_i = initial_u.shape[1] if n != n_i or m != m_i: print "\nMesh dimensions of initial u from file (%d,%d) does NOT match" %(n_i,m_i) print "user (or default) specified values: (%d,%d)\nExiting..." %(n,m) sys.exit(1) else: initial_u = None # If timeit is used and method = PurePython, give the user a warning if method == SolverPurePython and use_timeit: timeit_total_iter = timeit_repeats*timeit_iter # Total number of iterations (i.e. runs of solver) if timeit_total_iter >= 2 and t1-t0 >= 200: estimate_time_used = int((t1-t0)/1000. * 55) print "\nWarning: Testing the pure python implementation is really slow. " if verbose: print "Rough time estimate per iteration (and total time): %d, (%d) seconds" \ %(estimate_time_used, timeit_total_iter*estimate_time_used) raw_input('Press enter to continue..') # Fill the source term f (as a list or array) if method == SolverPurePython: f = SourceTermF_LIST(n,m,f_constant) else: # All other methods use arrays f = SourceTermF_ARRAY(n,m,f_constant) # One call to rule them all if use_timeit: if verbose: print "\nWhen running timeit, some user specified settings might" print "be ignored for consistency and reproducability" if method == SolverPurePython: # Sorry for long lines of code, but I get indent error otherwise... setup_timeit = "from heat_equation import SolverPurePython, SourceTermF_LIST; method = SolverPurePython; f = SourceTermF_LIST(%d,%d,%f)" %(n,m,f_constant) elif method == SolverNumpy: setup_timeit = "from heat_equation_numpy import SolverNumpy, SourceTermF_ARRAY; method = SolverNumpy; f = SourceTermF_ARRAY(%d,%d,%f)" %(n,m,f_constant) else: setup_timeit = "from heat_equation_weave import SolverWeave, SourceTermF_ARRAY; method = SolverWeave; f = SourceTermF_ARRAY(%d,%d,%f)" %(n,m,f_constant) solver_call = "u = method(f,%f,%f,%d,%d,%d,%d,None,False,False)" %(nu,dt,n,m,t0,t1) timeit_results = timeit.Timer(solver_call, setup=setup_timeit).repeat(timeit_repeats, timeit_iter) best_time = min(timeit_results)/float(timeit_iter) # All noise in data is "positive", so minimum time is most accurate if verbose: print "\nTest repeats: %d, each with %d iterations" %(timeit_repeats, timeit_iter) print "Settings: f=1,nu=%.1f,dt=%.1f,n=%d,m=%d,t0=%d,t1=%d" %(nu,dt,n,m,t0,t1) print "Minimum CPU-time of scheme '%s': %f seconds" %(scheme_name, best_time) else: print "Min. CPU-time: %f sec. (%s)" %(best_time, scheme_name) else: u = method(f,nu,dt,n,m,t0,t1,initial_u, \ show_animation=show_animation,print_progress=verbose) if verbose: # Need to add some spacing for aesthetical purposes print "" print u.max() # Save last u if output_last_u_to_file: if verbose: print "\nSaving final temperature distribution u to file" filename = args.o np.savetxt(filename, u) # Works with both nested list and array if save_last_fig: if verbose: print "\nSaving the final temperature plot of u to 'last_u.png'" plt.ion() im = plt.imshow(zip(*u), cmap='gray') # Initiate plotting / animation plt.title('u(x,y,t=%d)' %(t1)) # Update title time plt.xlabel('X'); plt.ylabel('Y') if not show_animation: # Do not add a second colorbar if already added! plt.colorbar(im) plt.savefig('last_u.png')
def np_to_vec(np): np=np.tolist() if np[3]: return vec3d(np[0], np[1], np[2], np[3]) return vec3d(np[0], np[1], np[2])