def test_euler(self): graph = Graph() graph.add_nodes("A,B,C") graph.add_link("A", "B") graph.add_link("A", "C") graph.add_link("B", "C") node_a = graph.node("A") euler = Euler(graph, node_a) path = [] success = euler.euler(node_a, node_a, path) self.assertTrue(success) node_b = graph.node("B") euler = Euler(graph, node_a) path = [] success = euler.euler(node_a, node_b, path) self.assertFalse(success) graph.add_nodes("D,E") graph.add_link("B", "D") graph.add_link("B", "E") graph.add_link("E", "D") euler = Euler(graph, node_b) path = [] success = euler.euler(node_b, node_b, path) self.assertTrue(success)
def test_Euler(data): initial_x = data[0] initial_y = data[1] intervals = data[2] final_x = data[3] exp = data[4] exp = exp.replace('m', '*') exp = exp.replace('p', '**') exp = exp[1:len(exp)] # print(str(exp)) f = sympy.sympify(exp) assume(final_x > initial_x) assume(intervals > 0) y1 = Euler(exp, initial_x, initial_y, final_x, intervals) t = [] last = initial_x step = (final_x - initial_x) / intervals # print(step) for i in range(intervals): last += step t.append(last) x = sympy.symbols('x') y = sympy.symbols('y') fx = lambdify([x, y], f) # print(f) y2 = odeint(fx, initial_y, np.asarray(t)) # print(len(result)) # print(exp,initial_x,initial_y,final_x,intervals) # print(len(y1),len(y2)) for i in range(len(y2)): note("numpy sol %r" % y2[i][0]) note("app solution %r" % y1[i]) assert y2[i][0] == y1[i]
def __init__(self, parent=None): super(GUI, self).__init__(parent) self.euler = Euler(1.0, 1.0, 9.5, 100) self.exact = Exact(1.0, 1.0, 9.5, 100) self.improved_euler = Improved_euler(1.0, 1.0, 9.5, 100) self.rungekutta = RungeKutta(1.0, 1.0, 9.5, 100) self.createTopGroupBox() self.createSelectInitialBox() self.createMethodBox() self.createTabBox() mainLayout = QGridLayout() mainLayout.addWidget(self.topGroupBox, 0, 0) mainLayout.addWidget(self.selectInitialBox, 1, 0) mainLayout.addWidget(self.methodBox, 2, 0) mainLayout.addWidget(self.bottomTabWidget, 3, 0) self.setLayout(mainLayout)
def test_init(self): graph = Graph() graph.add_nodes("A,B,C") graph.add_link("A", "B") graph.add_link("A", "C") graph.add_link("B", "C") node = graph.node("A") euler = Euler(graph, node) self.assertEqual(euler.graph, graph) self.assertIsNotNone(euler.unused_links) self.assertEqual(len(euler.unused_links), 3) self.assertIsNotNone(euler.link_count) self.assertEqual(len(euler.link_count), 0)
def __init__(self, param, grid): self.list_param = [ 'modelname', 'tend', 'fixed_dt', 'dt', 'cfl', 'plot_var', 'cax', 'colorscheme', 'plot_interactive', 'fixed_dt', 'dtmax', 'freq_save', 'freq_plot' ] param.copy(self, self.list_param) self.list_grid = ['dx', 'nh', 'msk'] grid.copy(self, self.list_grid) if param.modelname == 'euler': from euler import Euler self.model = Euler(param, grid) if param.modelname == 'advection': from advection import Advection self.model = Advection(param, grid) if param.modelname == 'boussinesq': from boussinesq import Boussinesq self.model = Boussinesq(param, grid) if param.modelname == 'quasigeostrophic': from quasigeostrophic import QG self.model = QG(param, grid) self.diag = Diag(param, grid) self.plotting = Plotting(param) # here's a shortcut to the model state self.state = self.model.var.state self.t = 0. self.kt = 0 self.output = Output(param, grid, self.diag)
class TestEuler(unittest.TestCase): def setUp(self): self.euler = Euler("y'=y*cos(x),\ny(0)=1\n\n") def test_getCoord(self): self.assertEqual((self.euler.getCoord()), ([0.0, 1.0, 1.0, 2.4]), "Invalid initial or final conditions.") def test_getExactfunc(self): self.assertEqual((self.euler.getExactfunc()), (sy.sympify("exp(sin(x))")), "Invalid equation") def test_getExactfunc(self): self.assertEqual((self.euler.getEquation()), (sy.sympify("y*cos(x)")), "Invalid exact function") def test_getLstX(self): self.assertEqual( self.euler.getLstX(), ([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]), "Invalid argument x") def test_getLstY(self): self.assertEqual(self.euler.getSolution(), ([ 1.1, 1.209, 1.328, 1.455, 1.589, 1.728, 1.871, 2.014, 2.154, 2.288, 2.412 ]), "Invalid Euler's method solution") def test_getLstDiff(self): self.assertEqual(self.euler.getLstDiff(), ([ -0.1, -0.104, -0.108, -0.111, -0.113, -0.113, -0.112, -0.11, -0.105, -0.1, -0.092 ]), "Invalid difference") def test_getLstExac(self): self.assertEqual(self.euler.getLstExac(), ([ 1.0, 1.105, 1.22, 1.344, 1.476, 1.615, 1.759, 1.904, 2.049, 2.189, 2.32 ]), "Invalid exact solution")
def test_add_link(self): graph = Graph() node_a = Node("A") euler = Euler(graph, node_a) node_a = Node("A") node_b = Node("B") link = Link(node_a, node_b) euler.unused_links.add(link) self.assertEqual(len(euler.unused_links), 1) self.assertEqual(euler.link_count[link], 0) euler.add_link(link) self.assertEqual(len(euler.unused_links), 0) self.assertEqual(euler.link_count[link], 1) euler.add_link(link) self.assertEqual(len(euler.unused_links), 0) self.assertEqual(euler.link_count[link], 2)
def __init__(self, param, grid): # let's first check that no param is obviously incorrect param.checkall() # copy the launch script into 'expname.py' to allow # for experiment reproducibility launchscript = sys.argv[0] param.datadir = param.datadir.replace('~', os.getenv("HOME")) param.expdir = '%s/%s' % (param.datadir, param.expname) if param.myrank == 0: if os.path.isdir(param.expdir): pass else: os.makedirs(param.expdir) savedscript = '%s/%s.py' % (param.expdir, param.expname) outfile = '%s/output.txt' % param.expdir if os.path.exists(outfile): print( 'Warning: this experiment has already been ran, output.txt already exists' ) print('dummy.txt will be used instead') outfile = '%s/dummy.txt' % param.expdir sys.stdout = Logger(outfile) if os.path.exists(savedscript): print('Warning: the python script already exists in %s' % param.expdir) print('the script won' 't be copied') pass else: self.savedscript = savedscript call(['cp', launchscript, savedscript]) self.list_param = [ 'modelname', 'tend', 'adaptable_dt', 'dt', 'cfl', 'dtmax', 'myrank', 'nprint', 'exacthistime', 'rescaledtime', 'noslip', 'geometry', 'diag_fluxes', 'print_param', 'enforce_momentum', 'forcing', 'decay', 'plotting_module', 'freq_save', 'freq_plot', 'plot_interactive', 'nbproc', 'isisland', 'npx', 'npy', 'nx', 'ny' ] param.copy(self, self.list_param) self.dt0 = self.dt grid.finalize_msk() # print('momentum=',self.enforce_momentum) self.list_grid = ['dx', 'dy', 'nh', 'msk', 'xr0', 'yr0', 'x2', 'y2'] grid.copy(self, self.list_grid) if param.modelname == 'euler': if self.geometry not in ['closed', 'disc']: self.enforce_momentum = False from euler import Euler self.model = Euler(param, grid) else: # not yet implemented in other models self.enforce_momentum = False if param.modelname == 'advection': from advection import Advection self.model = Advection(param, grid) if param.modelname == 'boussinesq': from boussinesq import Boussinesq self.model = Boussinesq(param, grid) if param.modelname == 'boussinesqTS': from boussinesqTS import BoussinesqTS self.model = BoussinesqTS(param, grid) if param.modelname == 'quasigeostrophic': from quasigeostrophic import QG self.model = QG(param, grid) if param.modelname == 'thermalwind': from thermalwind import Thermalwind self.model = Thermalwind(param, grid) if self.modelname == 'quasigeostrophic': self.enstrophyname = 'pv2' else: self.enstrophyname = 'enstrophy' if self.isisland: grid.island.finalize(self.model.ope.mskp) self.model.ope.rhsp = grid.island.rhsp self.model.ope.psi = grid.island.psi # self.diag = Diag(param,grid) if self.diag_fluxes: self.flx = Flx.Fluxes(param, grid, self.model.ope) flxlist = self.flx.fullflx_list else: flxlist = None if self.plot_interactive: try: p = import_module(self.plotting_module) # print(self.plotting_module) except ImportError: print('problem with the interactive plotting') print('this might be due to a backend issue') print('try to rerun the code with') print('param.plot_interactive = False') exit(0) self.plotting = p.Plotting(param, grid, self.model.var, self.model.diags) self.tracer_list = param.tracer_list # here's a shortcut to the model state self.state = self.model.var.state self.t = 0. self.kt = 0 self.output = Output(param, grid, self.model.diags, flxlist=flxlist) self.print_config(param, start=True)
def update(self): """時間発展(タイムオーダーは成長よりも短くすること) 各点にかかる力は,それぞれに付いているバネから受ける力の合力。 Runge-Kutta法を用いて運動方程式を解く。 この内部でglow関数を呼ぶ --- Arguments --- point (class): 参照するPointクラスを指定する h (float): シミュレーションの時間発展の刻み t_max (float): シミュレーションを終了する時間 """ # 初期条件 X = np.array([self.point.position_x, self.point.position_y, self.point.vel_x, self.point.vel_y ]) # X = [[x0, x1, ... , xN-1], # [y1, y2, ... , yN-1], # [x'0, x'1, ... , x'N-1], # [y'1, y'2, ..., y'N-1]] # solver = RK4(self.force) # Runge-Kutta method # solver = RK4(self.force_with_more_viscosity) # Runge-Kutta method # solver = Euler(self.force) # Euler method solver = Euler(self.force_with_more_viscosity) # Euler method t_count, frame = 0, 0 while self.t < self.t_max: if not self.pause: X = solver.solve(X, self.t, self.h) # update values self.point.position_x, self.point.position_y = X[0], X[1] self.point.vel_x, self.point.vel_y = X[2], X[3] # 各バネの自然長を増加させる & バネ定数を変化させる self.point.grow(self.grow_func, self.grow_func_k) # 各点間の距離が基準値を超えていたら,間に新たな点を追加する X = self.point.divide_if_extended(X) # self avoiding if self.self_avoiding: self.update_position_self_avoiding() # 一定の間隔で描画を行う if self.t > self.h * 12 * frame: # TODO: 要検討 log.info(self.t) log.info("N: " + str(self.point.N)) log.info("x: " + str(self.point.position_x)) log.info("y: " + str(self.point.position_y)) log.info("d: " + str(self.point.get_distances( self.point.position_x, self.point.position_y))) log.info("nl: " + str(self.point.natural_length)) log.info("K: " + str(self.point.K)) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] frame += 1 t_count += 1 self.t = self.h * t_count else: time.sleep(0.1) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] print "Done!"
def decodeValue(jsonData): """Returns a constructed math value based on the provided json data. Args: jsondata (dict): The JSON data to use to decode into a Math value. Returns: object: The constructed math value """ if type(jsonData) is not dict: return jsonData if '__mathObjectClass__' not in jsonData: raise Exception("Invalid JSON data for constructing value:" + str(jsonData)) if jsonData['__mathObjectClass__'] == 'Vec2': val = Vec2() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Vec3': val = Vec3() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Vec4': val = Vec4() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Euler': val = Euler() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Quat': val = Quat() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Xfo': val = Xfo() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Mat33': val = Mat33() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Mat44': val = Mat44() val.jsonDecode(jsonData, decodeValue) else: raise Exception("Unsupported Math type:" + jsonData['__mathObjectClass__']) return val
kek(lambda x, y: (x+2*y)/x, "x*(x-1)",0,1,10,0.001), #101 kek(lambda x, y: (2*x-4*y+6)/(x+y-3), "-(2*((sqrt(3))/2-1/2))/(9*(sqrt(19)/(8*3**(3/2))-1/216)**(1/3))+(sqrt(19)/(8*3**(3/2))-1/216)**(1/3)*(-1/2-(sqrt(3))/2)+4/3",-1.577564625074028,0,10,0.01), #113 жесть kek(lambda x, y: 0 if y == 0 else -x/y, "sqrt(16-x**2)",4,0,4,0.001), #5 kek(lambda x, y: math.pow(2.71828,(2*x+3)), "2.71828**(2*x+3)-10.042768",0,0,30,1), kek(lambda x, y: 1/(x*x+4),"atan(x/2)/2",0,0,10,0.001), kek(lambda x, y: math.cos(x)/math.sin(x), "log(sin(x))",-0.17260374626,1,3,0.001), kek(lambda x, y: x/y, "sqrt(x**2+16)",4,0,1,0.001) ] if __name__ == '__main__': #fun = lambda x, y: 3*x+2*y #print (Euler.euler(fun,1,0,10,1)) p = Euler.rungeKutta1(lambda x, y: 2*x+2*y, 1,0,10,1) for x in p: print (x) #k = lambda x: print("\n",) i = 0 #for x in diffs: # e = Euler.euler(x.dif, x.init, x.a, x.b, x.step) # Plot.plotFunctionAndCurve(x.fa, e, str(i) + 'euler.png') # rk1 = Euler.rungeKutta1(x.dif, x.init, x.a, x.b, x.step) # Plot.plotFunctionAndCurve(x.fa, rk1, str(i) + 'rk1.png') # rk4 = Euler.rungeKutta4(x.dif, x.init, x.a, x.b, x.step) # Plot.plotFunctionAndCurve(x.fa, rk4, str(i) + 'rk4.png')
def update(self): """時間発展(タイムオーダーは成長よりも短くすること) 各点にかかる力は,それぞれに付いているバネから受ける力の合力。 Runge-Kutta法を用いて運動方程式を解く。 この内部でglow関数を呼ぶ --- Arguments --- point (class): 参照するPointクラスを指定する h (float): シミュレーションの時間発展の刻み t_max (float): シミュレーションを終了する時間 """ # 初期条件 X = np.array([ self.point.position_x, self.point.position_y, self.point.vel_x, self.point.vel_y ]) # X = [[x0, x1, ... , xN-1], # [y1, y2, ... , yN-1], # [x'0, x'1, ... , x'N-1], # [y'1, y'2, ..., y'N-1]] # solver = RK4(self.force) # Runge-Kutta method # solver = RK4(self.force_with_more_viscosity) # Runge-Kutta method # solver = Euler(self.force) # Euler method solver = Euler(self.force_with_more_viscosity) # Euler method t_count, frame = 0, 0 while self.t < self.t_max: if not self.pause: X = solver.solve(X, self.t, self.h) # update values self.point.position_x, self.point.position_y = X[0], X[1] self.point.vel_x, self.point.vel_y = X[2], X[3] # 各バネの自然長を増加させる & バネ定数を変化させる self.point.grow(self.grow_func, self.grow_func_k) # 各点間の距離が基準値を超えていたら,間に新たな点を追加する X = self.point.divide_if_extended(X) # self avoiding if self.self_avoiding: self.update_position_self_avoiding() # 一定の間隔で描画を行う if self.t > self.h * 12 * frame: # TODO: 要検討 log.info(self.t) log.info("N: " + str(self.point.N)) log.info("x: " + str(self.point.position_x)) log.info("y: " + str(self.point.position_y)) log.info("d: " + str( self.point.get_distances(self.point.position_x, self.point.position_y))) log.info("nl: " + str(self.point.natural_length)) log.info("K: " + str(self.point.K)) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [ np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0]) ] frame += 1 t_count += 1 self.t = self.h * t_count else: time.sleep(0.1) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [ np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0]) ] print "Done!"
from euler import Euler from math import pi if __name__ == "__main__": equation = input("enter first order differential equation: ") curve = input("curve: ") x0 = float(input("x0: ")) y0 = float(input("y0: ")) if curve == "": e = Euler(equation, x0, y0) else: e = Euler(equation, x0, y0, curve) while True: x_final = eval(input("find value at: ")) step_size = float(input("step_size: ")) e.compare_errors(x_final, step_size)
class GUI(QDialog): def __init__(self, parent=None): super(GUI, self).__init__(parent) self.euler = Euler(1.0, 1.0, 9.5, 100) self.exact = Exact(1.0, 1.0, 9.5, 100) self.improved_euler = Improved_euler(1.0, 1.0, 9.5, 100) self.rungekutta = RungeKutta(1.0, 1.0, 9.5, 100) self.createTopGroupBox() self.createSelectInitialBox() self.createMethodBox() self.createTabBox() mainLayout = QGridLayout() mainLayout.addWidget(self.topGroupBox, 0, 0) mainLayout.addWidget(self.selectInitialBox, 1, 0) mainLayout.addWidget(self.methodBox, 2, 0) mainLayout.addWidget(self.bottomTabWidget, 3, 0) self.setLayout(mainLayout) def createTopGroupBox(self): self.topGroupBox = QGroupBox() difEquationLabel = QLabel("y' = y^4 * cos(x) - y * tg(x)") init_x0 = QLabel('x0=') self.init_x0_val = QLabel('1.0') init_x0.setBuddy(self.init_x0_val) init_y0 = QLabel('y0=') self.init_y0_val = QLabel('1.0') init_y0.setBuddy(self.init_x0_val) init_X = QLabel('X=') self.init_X_val = QLabel('9.5') init_X.setBuddy(self.init_X_val) init_n = QLabel('n=') self.init_n_val = QLabel('100') init_n.setBuddy(self.init_n_val) self.plotButton = QPushButton('Plot') self.plotButton.clicked.connect(self.plot) headLayout = QHBoxLayout() headLayout.addWidget(difEquationLabel, 5) headLayout.addWidget(init_x0) headLayout.addWidget(self.init_x0_val) headLayout.addWidget(init_y0) headLayout.addWidget(self.init_y0_val) headLayout.addWidget(init_X) headLayout.addWidget(self.init_X_val) headLayout.addWidget(init_n) headLayout.addWidget(self.init_n_val) headLayout.addWidget(self.plotButton) self.topGroupBox.setLayout(headLayout) def createSelectInitialBox(self): self.selectInitialBox = QGroupBox() yLabel = QLabel("&y0:") xLabel = QLabel("&x0:") XLabel = QLabel("&X:") nLabel = QLabel("&N:") self.xTextEdit = QTextEdit() self.yTextEdit = QTextEdit() self.XTextEdit = QTextEdit() self.nTextEdit = QTextEdit() yLabel.setBuddy(self.yTextEdit) xLabel.setBuddy(self.xTextEdit) XLabel.setBuddy(self.XTextEdit) nLabel.setBuddy(self.nTextEdit) topLayout = QHBoxLayout() topLayout.addWidget(yLabel) topLayout.addWidget(self.yTextEdit) topLayout.addWidget(xLabel) topLayout.addWidget(self.xTextEdit) topLayout.addWidget(XLabel) topLayout.addWidget(self.XTextEdit) topLayout.addWidget(nLabel) topLayout.addWidget(self.nTextEdit) topLayout.addStretch(1) self.selectInitialBox.setLayout(topLayout) def createMethodBox(self): self.methodBox = QGroupBox() self.eulerButton = QPushButton('Euler(Red)') self.eulerButton.setCheckable(True) self.eulerButton.setChecked(True) self.impruvedEulerButton = QPushButton('Impuved Euler(Blue)') self.impruvedEulerButton.setChecked(True) self.impruvedEulerButton.setCheckable(True) self.rungeKutteButton = QPushButton('Runge-Kutte(Yellow)') self.rungeKutteButton.setCheckable(True) self.rungeKutteButton.setChecked(True) self.exactButton = QPushButton('Exact(Green)') self.exactButton.setChecked(True) self.exactButton.setCheckable(True) methodLayout = QHBoxLayout() methodLayout.addWidget(self.eulerButton) methodLayout.addWidget(self.impruvedEulerButton) methodLayout.addWidget(self.rungeKutteButton) methodLayout.addWidget(self.exactButton) self.methodBox.setLayout(methodLayout) def createTabBox(self): self.plotFigure = Figure() self.plotCanvas = FigureCanvas(self.plotFigure) plotToolbar = NavigationToolbar(self.plotCanvas, self) self.localErrorFigure = Figure() self.localErrorCanvas = FigureCanvas(self.localErrorFigure) localErrorToolbar = NavigationToolbar(self.localErrorCanvas, self) self.globalErrorFigure = Figure() self.globalErrorCanval = FigureCanvas(self.globalErrorFigure) globalErrorToolbar = NavigationToolbar(self.globalErrorCanval, self) plotLayout = QVBoxLayout() plotLayout.addWidget(plotToolbar) plotLayout.addWidget(self.plotCanvas) localErrorLayout = QVBoxLayout() localErrorLayout.addWidget(localErrorToolbar) localErrorLayout.addWidget(self.localErrorCanvas) globalErrorLayout = QVBoxLayout() selectNLayout = QHBoxLayout() self.startNTextEdit = QTextEdit() self.finishNTextEdit = QTextEdit() selectNLayout.addWidget(self.startNTextEdit) selectNLayout.addWidget(self.finishNTextEdit) globalErrorLayout.addLayout(selectNLayout) globalErrorLayout.addWidget(globalErrorToolbar) globalErrorLayout.addWidget(self.globalErrorCanval) # self.setLayout(layout) self.bottomTabWidget = QTabWidget() plotTab = QWidget() plotTab.setLayout(plotLayout) localErrorTab = QWidget() localErrorTab.setLayout(localErrorLayout) globalErrorTab = QWidget() globalErrorTab.setLayout(globalErrorLayout) self.bottomTabWidget.addTab(plotTab, 'Plot') self.bottomTabWidget.addTab(localErrorTab, 'Local Error') self.bottomTabWidget.addTab(globalErrorTab, 'Global Error') def plot(self): global_error_startn, global_error_finishn = 1, int(self.exact.h) if self.startNTextEdit.toPlainText() != '': try: global_error_startn = int(self.startNTextEdit.toPlainText()) except BaseException: print('invalid startn global error') if self.finishNTextEdit.toPlainText() != '': try: global_error_finishn = int(self.finishNTextEdit.toPlainText()) except BaseException: print('invalid finishn global error') methods = [ self.euler, self.improved_euler, self.rungekutta, self.exact ] if self.xTextEdit.toPlainText() != '': for method in methods: method.set_x0(self.xTextEdit.toPlainText()) self.init_x0_val.setText(self.xTextEdit.toPlainText()) if self.yTextEdit.toPlainText() != '': for method in methods: method.set_y0(self.yTextEdit.toPlainText()) self.init_y0_val.setText(self.yTextEdit.toPlainText()) if self.nTextEdit.toPlainText() != '': for method in methods: method.set_n(self.nTextEdit.toPlainText()) self.init_n_val.setText(self.nTextEdit.toPlainText()) if self.XTextEdit.toPlainText() != '': for method in methods: method.set_X(self.XTextEdit.toPlainText()) self.init_X_val.setText(self.XTextEdit.toPlainText()) ax = self.plotFigure.add_subplot(111) ax.clear() local_error_fig = self.localErrorFigure.add_subplot(111) local_error_fig.clear() global_error_fig = self.globalErrorFigure.add_subplot(111) global_error_fig.clear() if self.eulerButton.isChecked(): eulerx, eulery = self.euler.plot() ax.plot(eulerx, eulery, label='euler', color='r') local_errory = self.euler.local_error() local_error_fig.plot(eulerx, local_errory, color='r') global_errorx, global_errory = self.euler.global_error( global_error_startn, global_error_finishn) global_error_fig.plot(global_errorx, global_errory, color='r') if self.impruvedEulerButton.isChecked(): impruved_eulerx, impruved_eulery = self.improved_euler.plot() ax.plot(impruved_eulerx, impruved_eulery, label='impruved euler', color='b') local_errory = self.improved_euler.local_error() local_error_fig.plot(impruved_eulerx, local_errory, color='b') global_errorx, global_errory = self.improved_euler.global_error( global_error_startn, global_error_finishn) global_error_fig.plot(global_errorx, global_errory, color='b') if self.rungeKutteButton.isChecked(): runge_kuttax, runge_kuttay = self.rungekutta.plot() ax.plot(runge_kuttax, runge_kuttay, color='y') local_errory = self.rungekutta.local_error() local_error_fig.plot(runge_kuttax, local_errory, color='y') global_errorx, global_errory = self.rungekutta.global_error( global_error_startn, global_error_finishn) global_error_fig.plot(global_errorx, global_errory, color='y') if self.exactButton.isChecked(): ex, ey = self.exact.plot() ax.plot(ex, ey, color='g') ax.grid(True, which='both') local_error_fig.grid(True, which='both') global_error_fig.grid(True, which='both') ax.axhline(y=0, color='k') ax.axvline(x=0, color='k') local_error_fig.axhline(y=0, color='k') local_error_fig.axvline(x=0, color='k') global_error_fig.axhline(y=0, color='k') global_error_fig.axvline(x=0, color='k') # refresh plotCanvas self.plotCanvas.draw() self.localErrorCanvas.draw() self.globalErrorCanval.draw()
def update(self): """時間発展(タイムオーダーは成長よりも短くすること) 各点にかかる力は,それぞれに付いているバネから受ける力の合力。 Runge-Kutta法を用いて運動方程式を解く。 この内部でglow関数を呼ぶ --- Arguments --- point (class): 参照するPointクラスを指定する h (float): シミュレーションの時間発展の刻み t_max (float): シミュレーションを終了する時間 """ # 初期条件 X = np.array([self.point.position_x, self.point.position_y, self.point.vel_x, self.point.vel_y ]) # X = [[x0, x1, ... , xN-1], # [y1, y2, ... , yN-1], # [x'0, x'1, ... , x'N-1], # [y'1, y'2, ..., y'N-1]] # solver = RK4(self.force) # Runge-Kutta method # solver = RK4(self.force_with_more_viscosity) # Runge-Kutta method # solver = Euler(self.force) # Euler method solver = Euler(self.force_with_more_viscosity) # Euler method count_grow, frame = 1, 0 grow_interval = 1000 plot_interval = 8 while self.t < self.t_max: print self.t if not self.pause: print "solver" X = solver.solve(X, self.t, self.h) # update values self.point.position_x, self.point.position_y = X[0], X[1] self.point.vel_x, self.point.vel_y = X[2], X[3] # ある時間間隔で新しく線素を追加する print self.h * grow_interval * count_grow if self.t > self.h * grow_interval * count_grow: print "add point" X = self.point.add() count_grow += 1 # self avoiding if self.self_avoiding: self.update_position_self_avoiding() # 一定の間隔で描画を行う if self.t > self.h * plot_interval * frame: log.info(self.t) log.info("N: " + str(self.point.N)) log.info("x: " + str(self.point.position_x)) log.info("y: " + str(self.point.position_y)) log.info("d: " + str(self.point.distances( self.point.position_x, self.point.position_y))) log.info("nl: " + str(self.point.natural_length)) log.info("K: " + str(self.point.K)) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] frame += 1 self.t = self.t + self.h else: time.sleep(0.1) if self.point.is_open: yield [self.point.position_x, self.point.position_y] else: yield [np.append(self.point.position_x, self.point.position_x[0]), np.append(self.point.position_y, self.point.position_y[0])] print "Done!"
from euler import Euler geom = rotate(loadtxt('../data/n0012c.dat'), 30*pi/180) nE = 1000 dt = 0.001 Mach = 0.3 HiRes = 1. if not os.path.exists('fig'): os.mkdir('fig') for iAdapt in range(4): print 'Adapt cycle {0}'.format(iAdapt) if iAdapt == 0: v, t, b = initMesh(geom, nE) solver = Euler(v, t, b, Mach, HiRes) solver.integrate(1E-8, solver.freeStream()) else: xt0, W0 = solver.mesh.xt(), solver.soln v, t, b = adaptMesh(geom, v, t, b, nE, metric) solver = Euler(v, t, b, Mach, HiRes) W0 = griddata(xt0, W0, solver.mesh.xt(), method='nearest') solver.integrate(1E-8, W0) metric = zeros([v.shape[0], 2, 2]) # metric for next adaptation for T in arange(1,21) * dt: solver.integrate(T) metric += solver.metric() clf() solver.mesh.plotTriScalar(solver.soln[:,0])
def decodeValue(jsonData): """Returns a constructed math value based on the provided json data. Args: jsondata (dict): The JSON data to use to decode into a Math value. Returns: object: The constructed math value """ if type(jsonData) is not dict: return jsonData if '__mathObjectClass__' not in jsonData: raise Exception("Invalid JSON data for constructing value:" + str(jsonData)); if jsonData['__mathObjectClass__'] == 'Vec2': val = Vec2() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Vec3': val = Vec3() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Vec4': val = Vec4() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Euler': val = Euler() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Quat': val = Quat() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Xfo': val = Xfo() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Mat33': val = Mat33() val.jsonDecode(jsonData, decodeValue) elif jsonData['__mathObjectClass__'] == 'Mat44': val = Mat44() val.jsonDecode(jsonData, decodeValue) else: raise Exception("Unsupported Math type:" + jsonData['__mathObjectClass__']) return val
class TestEuler(unittest.TestCase): """ example text that mocks requests.get and returns a mock Response object """ def _mock_response(self, status=200, content="CONTENT"): """ since we typically test a bunch of different requests calls for a service, we are going to do a lot of mock responses, so its usually a good idea to have a helper function that builds these things """ mock_resp = mock.Mock() # set status code and content mock_resp.status_code = status mock_resp.content = content return mock_resp def setUp(self): self.e = Euler() self.problem1 = 'If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.' self.problem2 = '''Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.''' def test__generateProblemUrl(self): tests = [ { 'desc': 'Positive: Problem url integer', 'args': [1], 'expected': 'https://projecteuler.net/problem=1' }, { 'desc': 'Positive: Problem url integer', 'args': [512], 'expected': 'https://projecteuler.net/problem=512' }, { 'desc': 'Positive: Problem url string', 'args': ['1'], 'expected': 'https://projecteuler.net/problem=1' }, { 'desc': 'Negative: passing None number', 'args': [None], 'expected': None }, ] for test in tests: with self.subTest(msg=test['desc']): res = self.e._generateProblemUrl(test['args'][0]) self.assertEqual(res, test['expected'], test['desc']) @mock.patch('requests.get') def test__getUrlContent(self, mock_get): baseProbUrl = 'https://projecteuler.net/problem=1', tests = [ { 'desc': 'Positive: Problem url integer', 'args': baseProbUrl, 'expected': 'TestContent' }, { 'desc': 'Positive: Problem url integer', 'args': baseProbUrl, 'expected': 'TestContent' }, { 'desc': 'Positive: Problem url string', 'args': baseProbUrl, 'expected': 'TestContent' }, { 'desc': 'Negative: passing None Url', 'args': [None], 'expected': None }, ] mock_resp = self._mock_response(content="TestContent") mock_get.return_value = mock_resp for test in tests: with self.subTest(msg=test['desc']): res = self.e._getUrlContent(test['args'][0]) self.assertEqual(res, test['expected'], test['desc']) def test__getProblemFromHtml(self): tests = [ { 'desc': 'Positive: Hardcoded HTML content for problem 1', 'args': [HTML_CONTENT_FOR_PROBLEM1], 'expected': self.problem1 }, { 'desc': 'Positive: Passing actual HTML content for problem 1', 'args': [self.e._getUrlContent(self.e._generateProblemUrl(1))], 'expected': self.problem1 }, { 'desc': 'Positive: Passing actual HTML content for problem 2', 'args': [self.e._getUrlContent(self.e._generateProblemUrl(2))], 'expected': self.problem2 }, { 'desc': 'Negative: passing None', 'args': [None], 'expected': None }, { 'desc': 'Negative: passing empty string', 'args': [None], 'expected': None }, { 'desc': 'Negative: Invalid html content', 'args': ['Invlaid html content'], 'expected': None }, ] for test in tests: with self.subTest(msg=test['desc']): res = self.e._getProblemFromHtml(test['args'][0]) self.assertEqual(test['expected'], res) def test_getProblem(self): tests = [ { 'desc': 'Positive: Problem url integer', 'args': [1], 'expected': { 'url': 'https://projecteuler.net/problem=1', 'description': self.problem1 } }, { 'desc': 'Positive: Problem url integer', 'args': [2], 'expected': { 'url': 'https://projecteuler.net/problem=2', 'description': self.problem2 } }, { 'desc': 'Positive: Problem url string', 'args': ['1'], 'expected': { 'url': 'https://projecteuler.net/problem=1', 'description': self.problem1 } }, { 'desc': 'Negative: Passing None', 'args': [None], 'expected': { 'url': None, 'description': None }, }, { 'desc': 'Negative: passing negative problem number', 'args': [-1], 'expected': { 'url': 'https://projecteuler.net/problem=-1', 'description': None } }, { 'desc': 'Negative: passing non-existant problem number', 'args': [123456789], 'expected': { 'url': 'https://projecteuler.net/problem=123456789', 'description': None } }, ] for test in tests: with self.subTest(msg=test['desc']): res = self.e._getProblem(test['args'][0]) self.assertEqual(test['expected'], res)
if opc == "1": a = Area() while True: print("\n1. Area cuadrado") print("2. Area triangulo") print("3. Area circulo") op = input("Elige una opcion: ") if op == "1": a.areaCuadrado() elif op == "2": a.areaTriangulo() elif op == "3": a.areaCirculo() elif op == "0": break elif opc == "2": print("\n") z = Zodiaco() z.signo() elif opc == "3": e = Euler() print("\n") limite = int(input("Limite: ")) n = e.numeroe(limite) print("e: ", n) else: break
def setUp(self): self.e = Euler() self.problem1 = 'If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.' self.problem2 = '''Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.'''
def setUp(self): self.euler = Euler("y'=y*cos(x),\ny(0)=1\n\n")
def __init__(self, param, grid): self.list_param = [ 'modelname', 'tend', 'adaptable_dt', 'dt', 'cfl', 'dtmax', 'myrank', 'nprint', 'rescaledtime', 'noslip', 'geometry', 'enforce_momentum', 'forcing', 'plotting_module', 'freq_save', 'freq_plot', 'plot_interactive', 'nbproc', 'isisland' ] param.copy(self, self.list_param) grid.finalize_msk() #print('momentum=',self.enforce_momentum) self.list_grid = ['dx', 'nh', 'msk', 'xr0', 'yr0', 'x2', 'y2'] grid.copy(self, self.list_grid) if param.modelname == 'euler': if not (self.geometry in ['square', 'disc']): self.enforce_momentum = False from euler import Euler self.model = Euler(param, grid) else: # not yet implemented in other models self.enforce_momentum = False if param.modelname == 'advection': from advection import Advection self.model = Advection(param, grid) if param.modelname == 'boussinesq': from boussinesq import Boussinesq self.model = Boussinesq(param, grid) if param.modelname == 'quasigeostrophic': from quasigeostrophic import QG self.model = QG(param, grid) if self.isisland: grid.island.finalize(self.model.ope.mskp) self.model.ope.rhsp = grid.island.rhsp self.model.ope.psi = grid.island.psi # self.diag = Diag(param,grid) if self.plot_interactive: try: p = import_module(self.plotting_module) except: print('module %s for plotting cannot be found' % self.plotting_module) print('make sure file **%s.py** exists' % self.plotting_module) exit(0) self.plotting = p.Plotting(param, grid, self.model.var, self.model.diags) # here's a shortcut to the model state self.state = self.model.var.state self.t = 0. self.kt = 0 self.output = Output(param, grid, self.model.diags)