def trapezes(f,a,b,n): pas=(b-a)/n x=a+pas somme=(f(a)+f(b))/2 for _ in range(n-1): somme+=f(x) x+=pas return somme*pas
def test_f_with_logger(self): original_stdout = sys.stdout self.common_test(f(T_LOG, 'w', True)(self.inner), T_LOG) with f(filename=T_LOG, mode='a', stdout=True): assert self.inner() == RETURN_VALUE self.assert_equal(T_LOG, original_stdout, TEXT * 2)
def assertArrayEqual(self, a, b, n=[], almost=False): '''Convenience function for testing arrays exactly.''' if hasattr(a, '__getitem__') and hasattr(b, '__getitem__'): n = n[:]; n.append(0) for m,(i,j) in enumerate(zip(a,b)): n[-1] = m self.assertArrayEqual(i,j, n, almost) else: f = self.assertEqual if not almost else self.assertAlmostEqual f(a,b, msg='Elements differ at %s' % n)
def PanelIntegratorSimp(n, a, b, f): #import f # Define the intervals x = a h = float(b - a) / n I = 0.0 # Iterate through the panels for i in range(0, n): I += (h / 6.) * (f(x) + 4. * f(x + (h / 2.)) + f(x + h)) x += h return I
def runTests(f, tests): global total out = "" passed = 0 for (i, o) in tests: if f(i) == o: print("test \"%s\" passed:" % str(i)) passed += 1 else: print( "test \"%s\" failed: you said \"%s\", it should have been \"%s\"" % (str(i), f(i), o)) total += passed print("passed %d/5\n" % passed)
def Runge_Kutta(mode, x_l, x_r, y, n, f): if mode == 0: h = (x_r - x_l) / n graph = [y] last = y for i in range(0, n): cur = [0, 0] cur[0] = x_l + i * h cur[1] = last last = cur[1] + (h / 2) * (f(cur[0], cur[1]) + f( cur[0] + h, cur[1] + h * f(cur[0], cur[1]))) graph.append(last) return graph elif mode == 1: h = (x_r - x_l) / n graph = [y] last = y for i in range(0, n): cur = [0, 0] coef = [0, 0, 0] cur[0] = x_l + i * h cur[1] = last coef[0] = f(cur[0] + (h / 2), cur[1] + (h / 2) * f(cur[0], cur[1])) coef[1] = f(cur[0] + (h / 2), cur[1] + (h / 2) * coef[0]) coef[2] = f(cur[0] + h, cur[1] + h * coef[1]) last = cur[1] + (h / 6) * (f(cur[0], cur[1]) + 2 * (coef[0] + coef[1]) + coef[2]) graph.append(last) return graph else: c = len(y) h = (x_r - x_l) / n graph = [[], []] graph[0].append(y[0]) graph[1].append(y[1]) last = y for i in range(0, n): cur = [0, 0] coef = [] for j in range(4): coef.append(np.empty(c)) cur[0] = x_l + i * h cur[1] = last coef[0] = np.fromiter((f[j](cur[0], cur[1]) for j in range(c)), float) coef[1] = np.fromiter( (f[j](cur[0] + .5 * h, cur[1] + .5 * h * coef[0]) for j in range(c)), float) coef[2] = np.fromiter( (f[j](cur[0] + .5 * h, cur[1] + .5 * h * coef[1]) for j in range(c)), float) coef[3] = np.fromiter((f[j](cur[0] + h, cur[1] + h * coef[2]) for j in range(c)), float) last = cur[1] + (h / 6) * (coef[0] + 2 * (coef[1] + coef[2]) + coef[3]) graph[0].append(last[0]) graph[1].append(last[1]) return graph
def sliceWhile(l, f): if l == []: return ([], []) if not f(l[0]): return ([], l) s, l1 = sliceWhile(l[1:], f) return ([l[0]] + s, l1)
def test_complex_func(): f, s = fg.generate_complex_function(func_list, 4) print(s) x = np.arange(P.x_interval[0], P.x_interval[1], 0.01) y = np.array([f(i) for i in x]) plt.plot(x, y) plt.show()
def add_list_style(self, style): self.finish() if self.list_style: # The template included by python-docx only has 3 list styles. level = min(len(self.list_style) + 1, 3) style = f("{style} {level}") # requires python 3.6+ # style = f"{style} {level}" self.list_style.append(style)
def test_f_as_context_manager(self): original_stdout = sys.stdout with f: assert self.inner() == RETURN_VALUE self.assert_equal(TMP_LOG, original_stdout) with f(filename=T_LOG, mode='a'): assert self.inner() == RETURN_VALUE self.assert_equal(TMP_LOG, original_stdout)
def PanelIntegratorRect(n, a, b, f): #import f # Define the intervals x = a h = float(b - a) / n I = 0.0 # Iterate through the panels for i in range(0, n): I += h * f(x) x += h return I
def __call__(self, **params): p = ParamOverrides(self, params, allow_extra_keywords=True) self._apply_cmd_overrides(p) self.metadata = AttrDict(p.metadata) for fn in p.metadata_fns: self.metadata.update(fn(p.inputs, p.outputs)) output_names = self.metadata.outputs.keys() input_names = self.metadata.inputs.keys() inputs = dict.fromkeys(input_names) if p.input_patterns: for k, ip in p.input_patterns.items(): inputs[k] = ip for name in [k for k, ip in inputs.items() if ip is None]: self.warning("No pattern specified for input %s, defaulting" "to blank Constant pattern." % name) inputs[name] = imagen.Constant(scale=0) else: for k in inputs.keys(): inputs[k] = copy.deepcopy(p.pattern_generator) for f in p.pre_presentation_hooks: f() responses = p.pattern_response_fn(inputs, output_names, durations=p.durations) for f in p.post_presentation_hooks: f() label = inputs.values()[0].__class__.__name__ results = self._collate_results(responses, label) if p.measurement_storage_hook: p.measurement_storage_hook(results) return results
def test_f_with_two_keyword_arguments(self): self.common_test(f(filename=T_LOG, mode='a')(self.inner), T_LOG)
def test_f_with_two_mixed_arguments(self): self.common_test(f(T_LOG, mode='a')(self.inner), T_LOG)
def test_f_with_two_positional_arguments(self): self.common_test(f(T_LOG, 'a')(self.inner), T_LOG)
def test_f_with_one_argument(self): self.common_test(f(T_LOG)(self.inner), T_LOG)
def test_f_without_argument(self): self.common_test(f(self.inner), TMP_LOG)
from f import * assert f(1) == 1 assert f(3) == 'fizz' assert f(5) == 'buzz' assert f(15) == 'fizzbuzz'
def update(self): self.rotated_image = copy.copy(self.rotated_image_base) for f in self.updates: f()
pop.remove(j) fronts[str(i)] = tmp #Adiciona ele no dicionario i += 1 #Incrementa o contador #==============================================================================# #Loop principal #==============================================================================# #==============================================================================# #Plot dos fronts #==============================================================================# #Plot dos fronts [f1:] for i in range(1, len(fronts)): for j in fronts[str(i)]: k = [] for f in fit: k.append(f(j)) plt.plot(k[0], k[1], 'o', color='b') plt.plot(k[0], k[1], 'o', color='b') #Plot do fornt f0, fiz isso pq existem alguns ind que ficam em dois fronts, #e assim o f0 sempre fica em destaque for i in fronts['0']: k = [] for f in fit: k.append(f(i)) plt.plot(k[0], k[1], 'o', color='r') plt.plot(k[0], k[1], 'o', color='r', label='f0') #Exibe o plot plt.legend(loc='best') plt.show()
import re,nltk,csv from nltk import word_tokenize import numpy as np import feature_functions as f r = open('data.csv','rb') targets = [] inputs = [] tags = ['Defended','Left alone','Beaten','Edged','Caught','Runout','Stumped','Bowled','LBW','Boundary_scored_by_batsman','Runs_by_batsman','Boundary_scored_extras','Runs_by_extras','Catch_dropped','Stumping Missed','Runout Missed','Bouncer','Yorker','Overthrow','great_save','poor_fielding','Free hit'] funcs = [f.f1,f.f2,f.f3,f.f4,f.f5,f.f6,f.f7,f.f8,f.f9,f.f10,f.f11,f.f12,f.f13,f.f14,f.f15,f.f16,f.f17,f.f18,f.f19,f.f20,f.f21,f.f22] reader = csv.reader(r) i = 0 for row in reader: i += 1 if i == 1 or i == 2: continue else: comment = word_tokenize(row[1]) # print i inputs.append([f(comment) for f in funcs]) targets.append(list(map(lambda x: 0 if x=='' else int(x), row[2:])))
def forEach(f, l): for x in l: f(x)
def fprime(lcst_parameters,flow_solver_run): # Call the flow solver if needed if flow_solver_run == 1: drag = f(lcst_parameters) else: drag = 'Not called' # # Residual part of optimisation # # Create parameter file for residual run process = subprocess.Popen(['cp','rae2822.para_primal','rae2822.para_residual']) process.wait() # Write necessary lines on bottom of residual parameter file appended_text = 'Solver type: Residual_only' with open('rae2822.para_residual','a') as myfile: myfile.write('\n') myfile.write(appended_text) # Submit residual job to Tau process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_residual','log/log_file.residual','use_mpi']) process.wait() # # Adjoint part of optimisation # # Create adjoint parameter file process = subprocess.Popen(['cp','rae2822.para_residual','rae2822.para_adjoint']) process.wait() # Write necessary lines on bottom of adjoint parameter file with open('rae2822.para_adjoint','a') as myfile: myfile.write('\n') myfile.write('Solver type: DAdjoint') myfile.write('\n') myfile.write('Solve dissipation error equation (0/1): 0') myfile.write('\n') myfile.write('Solve linear problem on grid level: 1') myfile.write('\n') myfile.write('Cost function part total/pressure/viscous (0/1/2): 0') myfile.write('\n') myfile.write('Point of point pressure cost function: 0') myfile.write('\n') myfile.write('Cost function: C-drag') myfile.write('\n') myfile.write('Design variable: Farfield-alpha') myfile.write('\n') myfile.write('Monitoring values: Residual_dJ/da-1_dJ/da-2_dJ/da') myfile.write('\n') myfile.write(' Monitoring significant figures: 4_8_8_8') myfile.write('\n') myfile.write('Jacobian variables: Cons') myfile.write('\n') myfile.write('Jacobian constant laminar viscosity (0/1): 0') myfile.write('\n') myfile.write('Jacobian frozen turbulence (0/1): 0') myfile.write('\n') myfile.write('Jacobian constant dissipation coeffs (0/1): 0') myfile.write('\n') myfile.write('Krylov loop: GMRes') myfile.write('\n') myfile.write('GMRes inner iterations: 40') myfile.write('\n') myfile.write('GMRes preconditioning iterations: 40') myfile.write('\n') myfile.write('Minimum residual: 1e-4') myfile.write('\n') myfile.write('Preconditioning: (none)') # Submit adjoint job process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_adjoint','log/adjoint.C-func','use_mpi']) process.wait() # # Calculating the gradient section # # Create the Volgrad parameter file to get the sensitivity process = subprocess.Popen(['cp','rae2822.para_adjoint','rae2822.para_volgrad']) process.wait() with open('rae2822.para_volgrad','a') as myfile: myfile.write('\n') myfile.write('Primary grid filename: rae2822.taumesh_def') myfile.write('\n') myfile.write('Grid prefix: grid2/') myfile.write('\n') myfile.write('Solver type: Volgrad') myfile.write('\n') myfile.write('Automatic parameter update (0/1): 0') # Create del to use for each parameter when doing finite difference delta = 0.00005*np.ones(len(lcst_parameters)) gradient = range(len(delta)) # Create deformed meshes for each parameter for i in range(len(delta)): print('Volgrad iteration: ',str(i)) temp = copy.deepcopy(lcst_parameters) temp[i] = lcst_parameters[i] + delta[i] delaunay_deform(temp,'rae2822.taumesh_def') # This outputs the deformed mesh process = subprocess.Popen(['ptau3d.preprocessing','rae2822.para_volgrad']) process.wait() process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_volgrad','log/log_file.volgrad','use_mpi']) process.wait() [alpha_drag_sensitivity,alpha_residual_sensitivity1] = get_alpha_sensitivities() drag_sensitivity = get_sensitivity() drag_gradient_term[i] = drag_sensitivity # Compute adjoint and gradient for the lift # Obtain additional term for the gradient equation due to the implicit # angle of attack variable which is used to ensure the correct lift is # achieved # # Adjoint part of optimisation # # Create adjoint parameter file process = subprocess.Popen(['cp','rae2822.para_residual','rae2822.para_adjoint_lift']) process.wait() # Write necessary lines on bottom of adjoint parameter file with open('rae2822.para_adjoint_lift','a') as myfile: myfile.write('\n') myfile.write('Solver type: DAdjoint') myfile.write('\n') myfile.write('Solve dissipation error equation (0/1): 0') myfile.write('\n') myfile.write('Solve linear problem on grid level: 1') myfile.write('\n') myfile.write('Cost function part total/pressure/viscous (0/1/2): 0') myfile.write('\n') myfile.write('Point of point pressure cost function: 0') myfile.write('\n') myfile.write('Cost function: C-lift') myfile.write('\n') myfile.write('Design variable: Farfield-alpha') myfile.write('\n') myfile.write('Monitoring values: Residual_dJ/da-1_dJ/da-2_dJ/da') myfile.write('\n') myfile.write(' Monitoring significant figures: 4_8_8_8') myfile.write('\n') myfile.write('Jacobian variables: Cons') myfile.write('\n') myfile.write('Jacobian constant laminar viscosity (0/1): 0') myfile.write('\n') myfile.write('Jacobian frozen turbulence (0/1): 0') myfile.write('\n') myfile.write('Jacobian constant dissipation coeffs (0/1): 0') myfile.write('\n') myfile.write('Krylov loop: GMRes') myfile.write('\n') myfile.write('GMRes inner iterations: 40') myfile.write('\n') myfile.write('GMRes preconditioning iterations: 40') myfile.write('\n') myfile.write('Minimum residual: 1e-4') myfile.write('\n') myfile.write('Preconditioning: (none)') # Submit adjoint job process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_adjoint_lift','log/adjoint.C-func','use_mpi']) process.wait() # Calculating the gradient section # # Create the Volgrad parameter file to get the sensitivity process = subprocess.Popen(['cp','rae2822.para_adjoint_lift','rae2822.para_volgrad_lift']) process.wait() with open('rae2822.para_volgrad_lift','a') as myfile: myfile.write('\n') myfile.write('Primary grid filename: rae2822.taumesh_def') myfile.write('\n') myfile.write('Grid prefix: grid2/') myfile.write('\n') myfile.write('Solver type: Volgrad') myfile.write('\n') myfile.write('Automatic parameter update (0/1): 0') # Create del to use for each parameter when doing finite difference delta = 0.00005*np.ones(len(lcst_parameters)) gradient = range(len(delta)) # Create deformed meshes for each parameter for i in range(len(delta)): print('Volgrad iteration: ',str(i)) temp = copy.deepcopy(lcst_parameters) temp[i] = lcst_parameters[i] + delta[i] delaunay_deform(temp,'rae2822.taumesh_def') # This outputs the deformed mesh process = subprocess.Popen(['ptau3d.preprocessing','rae2822.para_volgrad']) process.wait() process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_volgrad','log/log_file.volgrad','use_mpi']) process.wait() lift_sensitivity = get_sensitivity() [alpha_lift_sensitivity,alpha_residual_sensitivity2] = get_alpha_sensitivities() alpha_gradient_term[i] = -(lift_sensitivity/delta[i])/((alpha_lift_sensitivity+residual_lift_sensitivity2)/delta[i]) # Write the corrected gradient vector gradient = drag_gradient_term + (alpha_drag_sensitivity+alpha_residual_sensitivity1)*alpha_gradient_term # Clear up parameter files for next gradient call process = subprocess.call(['rm','rae2822.para_volgrad']) process = subprocess.call(['rm','rae2822.para_adjoint']) process = subprocess.call(['rm','rae2822.para_adjoint_lift']) process = subprocess.call(['rm','rae2822.para_residual']) gradient = np.asarray(gradient) # Write all gradients to file with open('gradients.txt','a') as myfile: myfile.write('\n') myfile.write(str(gradient)) myfile.write('\n') return gradient, drag
def f(): try: print "try" finally: print "fianally" f() import csv as f: print f
def test_f(tpl, namespace, output): a = 2 # noqa b = 3 # noqa c = 'hello' # noqa d = 'world' # noqa assert f(tpl, namespace=namespace) == output
def test_f_with_append_mode(self): f(filename=T_LOG)(self.inner)() self.common_test( f(filename=T_LOG, mode='a')(self.inner), T_LOG, TEXT * 2)
def acidentes_date_func(date, f): res = [] for i, l in enumerate(incident_date): if (f(l)): res.append(i) return res
#First year programmer, Python def fact5(x): res = 1 for i in xrange(2, x + 1): res *= i return res print fact5(6) #Lazy Python programmer def fact6(x): return x > 1 and x * fact(x - 1) or 1 print fact6(6) #Lazier Python programmer f = lambda x: x and x * f(x - 1) or 1 print f(6) #Python expert programmer import operator as op import functional as f fact7 = lambda x: f.foldl(op.mul, 1, xrange(2, x + 1)) print fact7(6) #Python hacker import sys @tailcall def fact8(x, acc=1): if x: return fact(x.__sub__(1), acc.__mul__(x)) return acc sys.stdout.write(str(fact8(6)) + '\n')
def fprime(lcst_parameters): # Call the flow solver if needed process = subprocess.Popen(['rm',str(lcst_parameters[1])]) exitcode = process.wait() if exitcode != 0: drag = f(lcst_parameters) # # Residual part of optimisation # # Create parameter file for residual run process = subprocess.Popen(['cp','rae2822.para_primal','rae2822.para_residual']) process.wait() # Write necessary lines on bottom of residual parameter file appended_text = 'Solver type: Residual_only' with open('rae2822.para_residual','a') as myfile: myfile.write('\n') myfile.write(appended_text) # Submit residual job to Tau process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_residual','log/log_file.residual','use_mpi']) process.wait() # # Adjoint part of optimisation # # Create adjoint parameter file process = subprocess.Popen(['cp','rae2822.para_residual','rae2822.para_adjoint']) process.wait() # Write necessary lines on bottom of adjoint parameter file with open('rae2822.para_adjoint','a') as myfile: myfile.write('\n') myfile.write('Solver type: DAdjoint') myfile.write('\n') myfile.write('Solve dissipation error equation (0/1): 0') myfile.write('\n') myfile.write('Solve linear problem on grid level: 1') myfile.write('\n') myfile.write('Cost function part total/pressure/viscous (0/1/2): 0') myfile.write('\n') myfile.write('Point of point pressure cost function: 0') myfile.write('\n') myfile.write('Cost function: C-drag') myfile.write('\n') myfile.write('Design variable: Farfield-alpha') myfile.write('\n') myfile.write('Monitoring values: Residual_dJ/da-1_dJ/da-2_dJ/da') myfile.write('\n') myfile.write(' Monitoring significant figures: 4_8_8_8') myfile.write('\n') myfile.write('Jacobian variables: Cons') myfile.write('\n') myfile.write('Jacobian constant laminar viscosity (0/1): 0') myfile.write('\n') myfile.write('Jacobian frozen turbulence (0/1): 0') myfile.write('\n') myfile.write('Jacobian constant dissipation coeffs (0/1): 0') myfile.write('\n') myfile.write('Krylov loop: GMRes') myfile.write('\n') myfile.write('GMRes inner iterations: 40') myfile.write('\n') myfile.write('GMRes preconditioning iterations: 40') myfile.write('\n') myfile.write('Minimum residual: 1e-4') myfile.write('\n') myfile.write('Preconditioning: (none)') # Submit adjoint job process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_adjoint','log/adjoint.C-func','use_mpi']) process.wait() # # Calculating the gradient section # # Create the Volgrad parameter file to get the sensitivity process = subprocess.Popen(['cp','rae2822.para_adjoint','rae2822.para_volgrad']) process.wait() with open('rae2822.para_volgrad','a') as myfile: myfile.write('\n') myfile.write('Primary grid filename: rae2822.taumesh_def') myfile.write('\n') myfile.write('Grid prefix: grid2/') myfile.write('\n') myfile.write('Solver type: Volgrad') myfile.write('\n') myfile.write('Automatic parameter update (0/1): 0') # Create del to use for each parameter when doing finite difference delta = 0.00000001*np.ones(len(lcst_parameters)) gradient = range(len(delta)) # Create deformed meshes for each parameter for i in range(len(delta)): print('Volgrad iteration: ',str(i)) temp = copy.deepcopy(lcst_parameters) temp[i] = lcst_parameters[i] + delta[i] delaunay_deform(temp,'rae2822.taumesh_def') # This outputs the deformed mesh process = subprocess.Popen(['ptau3d.preprocessing','rae2822.para_volgrad']) process.wait() process = subprocess.Popen(['mpirun','-n','7','ptau3d.turb1eq','rae2822.para_volgrad','log/log_file.volgrad','use_mpi']) process.wait() sensitivity = get_sensitivity() gradient[i] = sensitivity/delta[i] # Clear up parameter files for next gradient call process = subprocess.call(['rm','rae2822.para_volgrad']) process = subprocess.call(['rm','rae2822.para_adjoint']) process = subprocess.call(['rm','rae2822.para_residual']) gradient = np.asarray(gradient) # Write all gradients to file with open('gradients.txt','a') as myfile: myfile.write('\n') myfile.write(str(gradient)) myfile.write('\n') gradient = 0.01 * gradient return gradient
g[:, a: b:,]**c d[:,: e:,]**f g[:,...,]**a b[:, c: d: e,]**f for g, a, in b: import c; else: import d; for e, in f: import g; else: import a; for b in c, d,: import e; else: import f; for g in a,: import b; else: import c; {d: e, f: g,} class a(b): import c; class d: import e; f(g, **a)**b c(d, e,)**f g(a, *b, **c)**d e(f for g in a, **b)**c d(e = f, **g)**a [b for c in d if e] [f for g in a for b in c] [d for e in f for g in a] [b for c in d if e for f in g] [a for b in c if d] (e for f in g for a in b) (c for d in e if f) (g for a in b for c in d) (e for f in g if a for b in c) `d, e` `f`
result = lambda x, y, z: x**2 + y**2 print(result(2, 2, 2)) x = lambda i: i * i print(x(5)) #Ternary Operator with Lambda: s = lambda x, y, z: x if (x > 10) else (y if x > z else z) print(s(10, 20, 30)) # Lambda functions with relational operator expression f = lambda x, y, z: ( x * y + z ) > 100 # x,y,z are formal arguments and the expression evaluates to True/False print(f(1, 2, 3)) ######################################################################################### # map function will have two arguments 1. function 2.sequence/iterator (list,tuple ..) # Syntax: map(function,iterator) # The map(aFunction, aSequence) function applies a passed-in function to each item # .. in an iterable object and returns a list containing all the function call results. def sqrt(x): return (x * x) # print("Square root value={}".format(sqrt(4))) # Applying this function with map()
def fget(self): return f(self)
def combined_func(*args, **kwargs): for f in funcs: f(*args, **kwargs)
def default(f,a,b): return b if f(a) else a
def test_function_f(self): K1 = 0b000110110000001011101111111111000111000001110010 R0 = 0b11110000101010101111000010101010 expect = "00100011010010101010100110111011" # bin(f(R0, K1, self.e_bit_table, self.__sbox, self.p_table))[2:].zfill(32) self.assertEqual(expect, str(bin(f(R0, K1, self.e_bit_table, self.__sbox, self.p_table))[2:].zfill(32)), 'Testing f')