def knn_classify(data_file, K=5): # f_train, f_test, l_train, l_test = get_data(data_file) f_train, f_test, l_train, l_test = get_data_optimized(data_file) l_predict = [] for t in range(f_test.shape[0]): N = [] l = 0 for d in range(f_train.shape[0]): if len(N) <= K: N.append(d) else: for u in N: if dist(f_test[t], f_train[d]) < dist(f_test[t], f_train[u]): N.remove(u) N.append(d) break for n in N: if l_train[n] == 'A': l += 1 else: l -= 1 if l >= 0: l_predict.append('A') else: l_predict.append('B') acc = (float(sum(l_predict == l_test))/len(l_predict)) plot(f_train, l_train, f_test, l_test, l_predict, acc)
def create_histogram(dimensions, label): numberofvalues = len(dimensions) #calculates the width for each annotation across the labels width = [width for width, height in dimensions.values()] #95 percent width_zoom = sorted([width for width, height in dimensions.values() ])[:int(.95 * numberofvalues)] #calculates height of each annotations across the labels height = [height for width, height in dimensions.values()] #95 percent height_zoom = sorted([height for width, height in dimensions.values() ])[:int(.95 * numberofvalues)] #calculates aspect ratio of each annotation across the labels aspect_ratio = [width / height for width, height in dimensions.values()] aspect_ratio_zoom = sorted([ width / height for width, height in dimensions.values() ])[:int(.95 * numberofvalues)] # calculates areas of each annotation across the labels areas = [(width * height) / 100 for width, height in dimensions.values()] areas_zoom = sorted([ (width * height) / 100 for width, height in dimensions.values() ])[:int(.85 * numberofvalues)] #bins = np.arange(start=min(areas),stop=300,step=30) # plot(width,label,'Width') # plot(height,label,'Height') # plot(aspect_ratio,label,'Aspect Ratio') plot(areas_zoom, label, 'Areas Zoom')
def constantFrequencyExample(start=1.9, duration=0.5): filteredSignal = helpers.getSignal(start, duration, low_pass=100, high_pass=90, input_file="raw-epdf.wav") spectrum = helpers.getSpectrum(start, duration, low_pass=100, high_pass=90, input_file="raw-epdf.wav") segment = helpers.getSegment(start, duration, input_file="raw-epdf.wav") helpers.makeWavFromSpectrum(spectrum, segment, outputFile="recoveredWav.wav") # firstPeak = min([i[0] for i in spectrum.peaks()]) helpers.plot(spectrum)
def generate_borders(source, borders_only=False, labels=False, self_clip=False, trim_antarctica=False): """data from http://www.naturalearthdata.com/""" sf = shapefile.Reader("data/{}_admin_0_countries".format(source)) sovereigns = {} #key is 3-char code, value is list of (record,shape) for record, shape in zip(sf.records(), sf.shapes()): if trim_antarctica: if record[4] == 'ATA': #if it is Antarctica shape.points = trim_edges(shape.points) sovereigns[record[4]] = sovereigns.get(record[4], []) + [(record, shape)] for code in sorted(sovereigns.keys()): for record, shape in sovereigns[code]: if record[3] == record[8]: country_code = record[12] # metropole = (record, shape) # sovereigns[code].remove(metropole) #move the metropole to the front # sovereigns[code] = [metropole] + sovereigns[code] # break print('\t\t\t<g id="{}">'.format(country_code)) for record, shape in sovereigns[code]: x1, y1, x2, y2 = shape.bbox x = (x1 + x2) / 2 y = (y1 + y2) / 2 region_code = record[12] if country_code == region_code: #metropole # name = record[3] text_size = SIZE_CLASSES[int(record[2] - 2)] else: #dependency # name = '{} ({})'.format(record[8], record[3]) text_size = SIZE_CLASSES[int(record[2] - 1)] # if labels: # if text_size is not None: # print('\t\t\t\t<text class="label-{}" x="{:.3f}" y="{:.3f}">{}</text>'.format(text_size, x, y, name)) if borders_only: print( '\t\t\t\t<clipPath id="{0}-clipPath">'.format(region_code)) print( '\t\t\t\t\t<use href="#{0}-shape" />'.format(region_code)) print('\t\t\t\t</clipPath>') print( '\t\t\t\t<use href="#{0}-shape" style="fill:none; clip-path:url(#{0}-clipPath);" />' .format(region_code)) else: plot(shape.points, midx=shape.parts, close=False, fourmat='xd', tabs=4, ident="{0}-shape".format(region_code)) print('\t\t\t</g>')
def harmonics(base_frequency=400): # cos_sig = thinkdsp.CosSignal(freq=440, amp=1.0, offset=0) base_signal = thinkdsp.CosSignal(base_frequency, amp=1.0, offset=0) for i in xrange(2, 6): base_signal += thinkdsp.CosSignal(base_frequency * i, amp=1.0, offset=0) wave = base_signal.make_wave(duration=0.5, start=0, framerate=11025) spectrum = wave.make_spectrum() # helpers.makeWavFromSpectrum(spectrum, wave, 'exercise7.wav') helpers.plot(spectrum)
def underWaterSpectrum(signal, distance, absorbtionRate): spectrum = signal.make_spectrum() originalSpectrum = signal.make_spectrum() baseFrequency = getBaseFrequency(signal) index = 0; for freq in spectrum.fs: attenuation = attenuationFactor(distance, absorbtionRate, baseFrequency, freq) spectrum.amps[index] = spectrum.amps[index]/attenuation index += 1 helpers.plot(spectrum) return spectrum
def plot_side_indicatrix(phi0, r, res, side_res=1): points = [] midx = [0] for l in range(0, 181, 360 // res): pr, lr = obliquify(math.pi / 2 - r, math.radians(l), phi0, 0) points.append((pr, lr - math.pi)) for i in range(side_res): points.append((phi0 + r - (2 * r) / side_res * (i + 1), -math.pi)) midx.append(len(points)) for l in range(180, 361, 360 // res): pr, lr = obliquify(math.pi / 2 - r, math.radians(l), phi0, 0) points.append((pr, lr + math.pi)) for i in range(side_res): points.append((phi0 - r + (2 * r) / side_res * (i + 1), math.pi)) plot(points, midx=midx, close=False)
def create_plot(doc): """Create a static plot.""" doc.clear() # doc.theme = Theme(filename=join(getcwd(), 'theme.yaml')) sp = StockPrices() figure = plot(5, PLOT_WIDTH, PLOT_HEIGHT, get_data(sp, SELECTED, 5)) doc.add_root(figure)
def plot_shape(data, source, max_rank, trim_antarctica=False, flesh_out_antarctica=False): """data from http://www.naturalearthdata.com/""" sf = shapefile.Reader("data/{}_{}".format(source, data)) for i, field in enumerate(sf.fields): if 'rank' in field[0]: rank_idx = i - 1 for record, shape in zip(sf.records(), sf.shapes()): if record[rank_idx] <= max_rank: if trim_antarctica: if shape.points[0][ 1] < -60: #if it is Antarctica (this will have a few false positives, but that's fine) shape.points = trim_edges(shape.points) elif flesh_out_antarctica: if shape.points[0][1] < -60: shape.points = lengthen_edges(shape.points) plot(shape.points, midx=shape.parts, close=False, fourmat='xd')
def update_period(attr, old, new): """Update selected period.""" spinner.css_classes = ['loader-spinner'] overlay.css_classes = ['loader-overlay'] _data = get_data(sp, selected, period_selector.active) layout.children[2] = plot(period_selector.active, plot_width, plot_height, _data) spinner.css_classes = [] overlay.css_classes = []
def plot_pole_indicatrix(north, r, res, ctr_meridian=0, side_res=1, pole_res=1): if north: pp, pr = math.pi / 2, math.pi / 2 - r else: pp, pr = -math.pi / 2, -math.pi / 2 + r points = [] for i in range(side_res): points.append((pp + (pr - pp) / side_res * i, ctr_meridian - math.pi)) for x in range(-180, 181, 360 // res): points.append((pr, ctr_meridian + math.radians(x))) for i in range(side_res): points.append( (pr + (pp - pr) / side_res * (i + 1), ctr_meridian + math.pi)) for x in range(180, -181, -360 // pole_res): points.append((pp, ctr_meridian + math.radians(x))) plot(points)
def update_symbol_list(attr, old, new): """Update selected symobls.""" spinner.css_classes = ['loader-spinner'] overlay.css_classes = ['loader-overlay'] if symbol_selector.value is None: return if symbol_selector.value in selected: selected.remove(symbol_selector.value) else: selected.append(symbol_selector.value) if selected is None: _data = None else: _data = get_data(sp, selected, period_selector.active) layout.children[2] = plot(period_selector.active, plot_width, plot_height, _data) symbol_selector.value = None spinner.css_classes = [] overlay.css_classes = []
def test(): with pygmsh.occ.Geometry() as geom: container = geom.add_rectangle([0.0, 0.0, 0.0], 10.0, 10.0) letter_i = geom.add_rectangle([2.0, 2.0, 0.0], 1.0, 4.5) i_dot = geom.add_disk([2.5, 7.5, 0.0], 0.6) disk1 = geom.add_disk([6.25, 4.5, 0.0], 2.5) disk2 = geom.add_disk([6.25, 4.5, 0.0], 1.5) letter_o = geom.boolean_difference(disk1, disk2) geom.boolean_difference( container, geom.boolean_union([letter_i, i_dot, letter_o])) mesh = geom.generate_mesh() ref = 81.9131851877 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": # import meshio # meshio.write_points_cells('m.vtu', *test()) from helpers import plot mesh = test() plot("meshio_logo.png", mesh.points, mesh.get_cells_type("triangle"))
rect3 = geom.add_rectangle([10.0, 30.0, 0.0], 10.0, 1.0) rect4 = geom.add_rectangle([20.0, 9.0, 0.0], 10.0, 1.0) r1 = geom.add_rectangle([9.0, 0.0, 0.0], 21.0, 20.5, corner_radius=8.0) r2 = geom.add_rectangle([10.0, 00.0, 0.0], 20.0, 19.5, corner_radius=7.0) diff1 = geom.boolean_difference([r1], [r2]) r22 = geom.add_rectangle([9.0, 10.0, 0.0], 11.0, 11.0) inter1 = geom.boolean_intersection([diff1, r22]) r3 = geom.add_rectangle([10.0, 19.5, 0.0], 21.0, 21.0, corner_radius=8.0) r4 = geom.add_rectangle([10.0, 20.5, 0.0], 20.0, 20.0, corner_radius=7.0) diff2 = geom.boolean_difference([r3], [r4]) r33 = geom.add_rectangle([20.0, 19.0, 0.0], 11.0, 11.0) inter2 = geom.boolean_intersection([diff2, r33]) geom.boolean_difference([rect1, rect2], [disk1, disk2, rect3, rect4, inter1, inter2]) points, cells, _, _, _ = pygmsh.generate_mesh(geom) ref = 1082.4470502181903 assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': from helpers import plot plot('logo.png', *test()) # import meshio # meshio.write('logo.vtu', *test())
import copy from elliptic_curve import EllipticCurve from helpers import plot from point import Point C = EllipticCurve(a=-2, b=4) print(C) # case where P + Q + r = 0 ( tree points on curve) P = Point(C, 3, 5) P_copy = copy.copy(P) Q = Point(C, -2, 0) U = P+Q print(U) plot(C, P_copy, Q, U) # case where P + P + 0 = 0 (only one point on curve) P = Point(C, -2, 0) P_copy = copy.copy(P) Q = Point(C, -2, 0) U = P+Q print(U) plot(C, P_copy, Q, U) # case where P + Q + 0 = 0 (vertical line) P = Point(C, 0, 2) P_copy = copy.copy(P) Q = Point(C, 0, -2) U = P+Q print(U)
def main(): spectrum = getSquareWaveSignal(1100).make_wave().make_spectrum() helpers.plot(spectrum)
print(f"J={J}") # L2 regularisation #J += 1e4*reg #print(f"reg={1e4*reg}") # l2 regularisation reg = 0 for W in [W_1, W_2, b_1, W_3_1, W_3_2, b_2]: reg += 1e4*assemble(W**2*dx) J += reg print(f"reg={reg}") Jhat = ReducedFunctional(J, [Control(W_1), Control(b_1), Control(W_2), Control(b_2), Control(W_3_1), Control(W_3_2)]) C_up_eps_1 = Control(up_eps_1) C_up_eps_2 = Control(up_eps_2) set_log_level(LogLevel.ERROR) minimize(Jhat, tol=1e-200, options={"disp": True, "gtol": 1e-12, "maxiter": 20}) #print("|U - d| = ", assemble(inner(C_up.tape_value() - up_stab, C_up.tape_value() - up_stab)*dx)**0.5) u_nn, p_nn = C_up_eps_1.tape_value().split(deepcopy=True) plot(u_nn, "out/u_eps_1_nn.png") plot(p_nn, "out/p_eps_1_nn.png") u_nn, p_nn = C_up_eps_2.tape_value().split(deepcopy=True) plot(u_nn, "out/u_eps_2_nn.png") plot(p_nn, "out/p_eps_2_nn.png")
def train(u_stab, element): mesh = u_stab.function_space().mesh() n = FacetNormal(mesh) W = FunctionSpace(mesh, element) # Now solve the Poisson with an inconsistent element, # but with the NN as a source term # Define a neural network that will be added as a source term to the Poisson eqn # We pass into the network the mesh size :_ R = VectorFunctionSpace(mesh, "R", 0, dim=50) R2 = FunctionSpace(mesh, "R", 0) W_1 = [Function(R)] * 5 W_2 = Function(R) b_1 = Function(R) b_2 = Function(R2) eps = 1e1 for w in W_1: w.vector()[:] = eps * rand(R.dim()) W_2.vector()[:] = eps * rand(R.dim()) b_1.vector()[:] = eps * rand(R.dim()) b_2.vector()[:] = eps * rand(R2.dim()) def nn(u, v): inp = as_vector( [avg(u), jump(u), *grad(avg(u)), *grad(jump(u)), *n('+')]) def sigma_(vec, func=ufl.tanh): v = [func(vec[i]) for i in range(vec.ufl_shape[0])] return ufl.as_vector(v) relu = lambda vec: conditional(ufl.gt(vec, 0), vec, (ufl.exp(vec) - 1)) sigma = lambda vec: sigma_(vec, func=relu) nn = dot(W_2, sigma(ufl.transpose(as_vector(W_1)) * inp + b_1)) + b_2 return inner(nn, jump(v) + avg(v)) * dS, inner(nn, nn) * dS # Now solve the Stokes-NN forward problem u, reg = poisson(W, nn) plot(u, "out/u_nn0.png") J = assemble((u - u_stab)**2 * dx) print(f"J={J}") # L2 regularisation #J += 1e4*reg #print(f"reg={1e4*reg}") # l2 regularisation reg = 0 for W in [*W_1, W_2, b_1, b_2]: reg += 1e4 * assemble(W**2 * dx) J += reg print(f"reg={reg}") ctrls = [Control(W) for W in W_1] ctrls += [Control(b_1), Control(W_2), Control(b_2)] Jhat = ReducedFunctional(J, ctrls) C_u = Control(u) set_log_level(LogLevel.ERROR) minimize(Jhat, tol=1e-200, options={ "disp": True, "gtol": 1e-12, "maxiter": 20 }) print( "|U - d| = ", assemble( inner(C_u.tape_value() - u_stab, C_u.tape_value() - u_stab) * dx)**0.5) u_nn = C_u.tape_value() plot(u_nn, "out/u_nn.png") return nn
#solve(F == 0, up, bcs, solver_parameters={"nonlinear_solver": "snes", "snes_solver": {"line_search": "bt", "linear_solver": "lu", "report": False}}, # [basic,bt,cp,l2,nleqerr] # form_compiler_parameters={"optimize": True}) if nn: return up, assemble(reg) else: return up if __name__ == "__main__": mesh = UnitSquareMesh(16, 16, 'crossed') stable = [ VectorElement('Lagrange', triangle, 2), FiniteElement('Lagrange', triangle, 1) ] W = FunctionSpace(mesh, MixedElement(stable)) up = stokes(W) # Add noise eps_noise = 0 up.vector()[:] += eps_noise * rand(W.dim()) u_stab, p_stab = up.split(deepcopy=True) plot(u_stab, "out/u_stab.png") plot(p_stab, "out/p_stab.png") with HDF5File(MPI.comm_world, "out/up_stab.h5", "w") as xdmf: xdmf.write(up, "up")
def plot_indicatrix(phi0, lam0, r, res): points = [] for l in range(0, 360, 360 // res): points.append(obliquify(math.pi / 2 - r, math.radians(l), phi0, lam0)) plot(points)
def plot_orthodrome(phi0, lam0, tht0): points = [] for p in range(-90, 91): points.append(obliquify(math.radians(p), tht0, phi0, lam0)) plot(points, close=False)
def periodic_signal_spectrum(start=1.9, duration=4.8): spectrum = helpers.getSpectrum(start, duration, low_pass=100, high_pass=90, input_file="raw-epdf.wav") helpers.plot(spectrum)
def periodic_signal_example(start=1.9, duration=4.8): filteredSignal = helpers.getSignal(start, duration, low_pass=100, high_pass=90, input_file="raw-epdf.wav") helpers.plot(filteredSignal)
@pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry(characteristic_length_min=0.5, characteristic_length_max=0.5) container = geom.add_rectangle([0.0, 0.0, 0.0], 10.0, 10.0) letter_i = geom.add_rectangle([2.0, 2.0, 0.0], 1.0, 4.5) i_dot = geom.add_disk([2.5, 7.5, 0.0], 0.6) disk1 = geom.add_disk([6.25, 4.5, 0.0], 2.5) disk2 = geom.add_disk([6.25, 4.5, 0.0], 1.5) letter_o = geom.boolean_difference([disk1], [disk2]) geom.boolean_difference([container], [letter_i, i_dot, letter_o]) mesh = pygmsh.generate_mesh(geom) ref = 81.9131851877 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": # import meshio # meshio.write_points_cells('m.vtu', *test()) from helpers import plot plot("meshio_logo.png", test())
def create_plot(doc): """Creat a bokeh plot.""" # create a plot and style its properties # doc = curdoc() doc.theme = Theme(filename=join(dirname(__file__), 'theme.yaml')) doc.title = 'Sample bokeh plot' sp = StockPrices() plot_width = 600 plot_height = 600 # elements symbol_selector = AutocompleteInput(completions=list(sp.get_symbols()), width=150) period_selector = RadioButtonGroup(labels=[ "Today" if datetime.today().weekday() < 5 else "Friday", "5 days", "1 month", "6 months", "1 year", "5 years" ], active=5, width=400) selected = ['GOOGL', 'AMZN'] spinner = Div(text='') overlay = Div(text='') layout = column(Div(text='<header><h1>Stock Closing Prices</h1></header>', width=plot_width), row(column( widgetbox(Div(text='<h3>Period</h3>'), period_selector, width=400)), column( widgetbox(Div(text='<h3>Symbols</h3>'), symbol_selector, width=plot_width - 400)), height=95), plot(period_selector.active, plot_width, plot_height, get_data(sp, selected, period_selector.active)), spinner, overlay, width=plot_width + 20, height=plot_height + 120, sizing_mode='fixed') # layout.css_classes = ['wrapper'] doc.add_root(layout) # Set up callbacks # symbol selector def update_symbol_list(attr, old, new): """Update selected symobls.""" spinner.css_classes = ['loader-spinner'] overlay.css_classes = ['loader-overlay'] if symbol_selector.value is None: return if symbol_selector.value in selected: selected.remove(symbol_selector.value) else: selected.append(symbol_selector.value) if selected is None: _data = None else: _data = get_data(sp, selected, period_selector.active) layout.children[2] = plot(period_selector.active, plot_width, plot_height, _data) symbol_selector.value = None spinner.css_classes = [] overlay.css_classes = [] symbol_selector.on_change('value', update_symbol_list) # period selector def update_period(attr, old, new): """Update selected period.""" spinner.css_classes = ['loader-spinner'] overlay.css_classes = ['loader-overlay'] _data = get_data(sp, selected, period_selector.active) layout.children[2] = plot(period_selector.active, plot_width, plot_height, _data) spinner.css_classes = [] overlay.css_classes = [] period_selector.on_change('active', update_period)
if nn: Fnn, reg = nn(u, v) F += Fnn solve(F == 0, u, bcs) if nn: return u, assemble(reg) else: return u if __name__== "__main__": mesh = UnitIntervalMesh(16) stable = FiniteElement('Lagrange', interval, 1) W = FunctionSpace(mesh, stable) u = poisson(W) # Add noise eps_noise = 0 u.vector()[:] += eps_noise*rand(W.dim()) plot(u, "out/u_stab.png") with HDF5File(MPI.comm_world, "out/u_stab.h5", "w") as xdmf: xdmf.write(u, "u")
def main(): frequency = 10 for i in xrange(3): helpers.plot(removeHarmonics(sawToothSignal(freq=frequency), i)[1]) helpers.plot(getWave(sawToothSignal(freq=frequency)))
@pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry( characteristic_length_min=0.5, characteristic_length_max=0.5 ) container = geom.add_rectangle([0.0, 0.0, 0.0], 10.0, 10.0) letter_i = geom.add_rectangle([2.0, 2.0, 0.0], 1.0, 4.5) i_dot = geom.add_disk([2.5, 7.5, 0.0], 0.6) disk1 = geom.add_disk([6.25, 4.5, 0.0], 2.5) disk2 = geom.add_disk([6.25, 4.5, 0.0], 1.5) letter_o = geom.boolean_difference([disk1], [disk2]) geom.boolean_difference([container], [letter_i, i_dot, letter_o]) mesh = pygmsh.generate_mesh(geom) ref = 81.9131851877 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": # import meshio # meshio.write_points_cells('m.vtu', *test()) from helpers import plot plot("meshio_logo.png", test())
rect3 = geom.add_rectangle([10.0, 30.0, 0.0], 10.0, 1.0) rect4 = geom.add_rectangle([20.0, 9.0, 0.0], 10.0, 1.0) r1 = geom.add_rectangle([9.0, 0.0, 0.0], 21.0, 20.5, corner_radius=8.0) r2 = geom.add_rectangle([10.0, 00.0, 0.0], 20.0, 19.5, corner_radius=7.0) diff1 = geom.boolean_difference([r1], [r2]) r22 = geom.add_rectangle([9.0, 10.0, 0.0], 11.0, 11.0) inter1 = geom.boolean_intersection([diff1, r22]) r3 = geom.add_rectangle([10.0, 19.5, 0.0], 21.0, 21.0, corner_radius=8.0) r4 = geom.add_rectangle([10.0, 20.5, 0.0], 20.0, 20.0, corner_radius=7.0) diff2 = geom.boolean_difference([r3], [r4]) r33 = geom.add_rectangle([20.0, 19.0, 0.0], 11.0, 11.0) inter2 = geom.boolean_intersection([diff2, r33]) geom.boolean_difference([rect1, rect2], [disk1, disk2, rect3, rect4, inter1, inter2]) points, cells, _, _, _ = pygmsh.generate_mesh(geom) ref = 1082.4470502181903 assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == "__main__": from helpers import plot plot("logo.png", *test()) # import meshio # meshio.write_points_cells('logo.vtu', *test())
def train_ad(u_stab, V, alpha): mesh = V.mesh() # Define a neural network that will be added as a source term to the Stokes eqn R = VectorFunctionSpace(mesh, "R", 0, dim=50) W_1, W_2, b_1, b_2, W_3_1, W_3_2 = Function(R), Function(R), Function( R), Function(R), Function(R), Function(R) W_3 = as_vector([W_3_1, W_3_2]) R2 = VectorFunctionSpace(mesh, "R", 0, dim=2) eps = 1e1 W_1.vector()[:] = eps * rand(R.dim()) W_2.vector()[:] = eps * rand(R.dim()) W_3[0].vector()[:] = eps * rand(R.dim()) W_3[1].vector()[:] = eps * rand(R.dim()) b_1.vector()[:] = eps * rand(R.dim()) b_2.vector()[:] = eps * rand(b_2.function_space().dim()) def nn(u, v): #return inner(grad(p), grad(q)) * dx def sigma_(vec, func=ufl.tanh): v = [func(vec[i]) for i in range(vec.ufl_shape[0])] return ufl.as_vector(v) relu = lambda vec: conditional(ufl.gt(vec, 0), vec, (ufl.exp(vec) - 1)) sigma = lambda vec: sigma_(vec, func=relu) #lambda x:x) #from IPython import embed #embed() n1 = dot(W_2, sigma(W_1 * u) + b_1) n2 = dot(W_3_1, sigma(W_3_2 * u.dx(0)) + b_2) return inner(n1, v) * dx + inner(n2, v.dx(0)) * dx, inner( n1, n1) * dx + inner(n2, n2) * dx, n1 # Now solve the Stokes-NN forward problem uh, reg = advection_diffusion(V, alpha, nn) plot(uh, "out/ad0.png") J = assemble((uh - u_stab)**2 * dx(domain=u_stab.function_space().mesh())) print(f"J={J}", u_stab.function_space().ufl_element()) reg = 0 for W in [W_1, W_2, W_3_1, W_3_2, b_1, b_2]: reg += 1E-2 * assemble(W**2 * dx) J += reg print(f"reg={reg}") Jhat = ReducedFunctional(J, [ Control(W_1), Control(b_1), Control(b_2), Control(W_2), Control(W_3_1), Control(W_3_2) ]) C_u = Control(uh) set_log_level(LogLevel.ERROR) minimize(Jhat, tol=1e-200, options={ "disp": True, "gtol": 1e-12, "maxiter": 50 }) print( "|U - d| = ", assemble( inner(C_u.tape_value() - u_stab, C_u.tape_value() - u_stab) * dx(domain=u_stab.function_space().mesh()))**0.5) u_nn = C_u.tape_value() df.plot(u_nn, label='learned', marker='o') df.plot(interpolate(u_stab, V), label='data alpha {}'.format(alpha)) df.plot(advection_diffusion(V, alpha=alpha, nn=None), label='no nn') plt.legend() plt.savefig("out/ad_nn.png") return nn
@pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason='requires Gmsh >= 3') def test(): geom = pygmsh.opencascade.Geometry( characteristic_length_min=0.5, characteristic_length_max=0.5, ) container = geom.add_rectangle([0.0, 0.0, 0.0], 10.0, 10.0) letter_i = geom.add_rectangle([2.0, 2.0, 0.0], 1.0, 4.5) i_dot = geom.add_disk([2.5, 7.5, 0.0], 0.6) disk1 = geom.add_disk([6.25, 4.5, 0.0], 2.5) disk2 = geom.add_disk([6.25, 4.5, 0.0], 1.5) letter_o = geom.boolean_difference([disk1], [disk2]) geom.boolean_difference([container], [letter_i, i_dot, letter_o]) points, cells, _, _, _ = pygmsh.generate_mesh(geom) ref = 81.9131851877 assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': # import meshio # meshio.write('m.vtu', *test()) from helpers import plot plot('meshio_logo.png', *test())
def train_stokes(up_stab, ustab_elm): mesh = up_stab.function_space().mesh() W = FunctionSpace(mesh, ustab_elm) # Now solve the Stokes with an unstable element pair, # but with the NN as a source term # Define a neural network that will be added as a source term to the Stokes eqn R = VectorFunctionSpace(mesh, "R", 0, dim=50) W_1, W_2, b_1, W_3_1, W_3_2 = Function(R), Function(R), Function( R), Function(R), Function(R) W_3 = as_vector([W_3_1, W_3_2]) R2 = VectorFunctionSpace(mesh, "R", 0, dim=2) b_2 = Function(R2) eps = 1e1 W_1.vector()[:] = eps * rand(R.dim()) W_2.vector()[:] = eps * rand(R.dim()) W_3[0].vector()[:] = eps * rand(R.dim()) W_3[1].vector()[:] = eps * rand(R.dim()) b_1.vector()[:] = eps * rand(R.dim()) b_2.vector()[:] = eps * rand(R2.dim()) def nn(u, p, v, q): #return inner(grad(p), grad(q)) * dx def sigma_(vec, func=ufl.tanh): v = [func(vec[i]) for i in range(vec.ufl_shape[0])] return ufl.as_vector(v) relu = lambda vec: conditional(ufl.gt(vec, 0), vec, (ufl.exp(vec) - 1)) sigma = lambda vec: sigma_(vec, func=relu) #lambda x:x) nn_p = dot( W_3, sigma(ufl.transpose(as_vector([W_1, W_2])) * grad(p) + b_1)) + b_2 #nn_q = dot(W_3, sigma(ufl.transpose(as_vector([W_1, W_2])) * grad(q) + b_1)) + b_2 return inner(nn_p, grad(q)) * dx, inner(nn_p, nn_p) * dx, nn_p # Now solve the Stokes-NN forward problem up, reg = stokes(W, nn) u_nn, p_nn = up.split(deepcopy=True) plot(u_nn, "out/u_nn0.png") plot(p_nn, "out/p_nn0.png") J = assemble((up - up_stab)**2 * dx) print(f"J={J}") # L2 regularisation #J += 1e4*reg #print(f"reg={1e4*reg}") # l2 regularisation reg = 0 for W in [W_1, W_2, b_1, W_3_1, W_3_2, b_2]: reg += 1e4 * assemble(W**2 * dx) J += reg print(f"reg={reg}") Jhat = ReducedFunctional(J, [ Control(W_1), Control(b_1), Control(W_2), Control(b_2), Control(W_3_1), Control(W_3_2) ]) C_up = Control(up) set_log_level(LogLevel.ERROR) minimize(Jhat, tol=1e-200, options={ "disp": True, "gtol": 1e-12, "maxiter": 20 }) print( "|U - d| = ", assemble( inner(C_up.tape_value() - up_stab, C_up.tape_value() - up_stab) * dx)**0.5) u_nn, p_nn = C_up.tape_value().split(deepcopy=True) plot(u_nn, "out/u_nn.png") plot(p_nn, "out/p_nn.png") return nn