def save(self, dirname): '''Save the model and results. ''' fvtu = 'code/fem/poisson_solution000000.vtu' modelfname = os.path.join(dirname, 'model.pt') torch.save(self.nn.state_dict(), modelfname) rfile = os.path.join(dirname, 'results.npz') pts, u_exact = _vtu2data(fvtu) x = pts[:, 0] y = pts[:, 1] xt, yt = tensor(x.ravel()), tensor(y.ravel()) u = self.nn(xt, yt).detach().cpu().numpy() u.shape = x.shape du = u - u_exact L1 = np.mean(np.abs(du)) L2 = np.sqrt(np.mean(du**2)) Linf = np.max(np.abs(du)) np.savez(rfile, x=x, y=y, u=u, u_exact=u_exact, L1=L1, L2=L2, Linf=Linf)
def __init__(self, n_nodes, ns, nb=None, nbs=None, xL=0.0, xR=1.0, T=1.0, sample_frac=1.0): self.xL = xL self.xR = xR self.T = T self.sample_frac = sample_frac # Interior nodes self.nx, self.nt = self._get_points_split((xR - xL), T, n_nodes) self.i_nodes = self._get_points_mgrid(xL, xR, T, self.nx, self.nt, endpoint=False) # Fixed nodes if nb is None: nbx, nbt = self.nx, self.nt else: nbx, nbt = self._get_points_split((xR - xL), T, nb + 1) if nb == 0: self.f_nodes = ([], []) else: self.f_nodes = self._get_boundary_nodes(xL, xR, T, nbx, nbt) # Interior samples self.nsx, self.nst = self._get_points_split((xR - xL), T, ns) xi, ti = self._get_points_mgrid(xL, xR, T, self.nsx, self.nst, endpoint=False) self.p_samples = (tensor(xi, requires_grad=True), tensor(ti, requires_grad=True)) self.n_interior = len(self.p_samples[0]) self.rng_interior = np.arange(self.n_interior) self.sample_size = int(self.sample_frac * self.n_interior) # Boundary samples if nbs is None: nbsx, nbst = self.nsx, self.nst else: nbsx, nbst = self._get_points_split((xR - xL), T, nbs) xb, tb = self._get_boundary_nodes(xL, xR, T, nbsx, nbst) self.b_samples = (tensor(xb, requires_grad=True), tensor(tb, requires_grad=True))
def __init__(self, n, ns, sample_frac=1.0, dt=1e-3, T=1.0, t_skip=10): super().__init__(n, ns, sample_frac, dt=dt, T=T, t_skip=t_skip) self.xn = np.asarray([-1.0 + 2*i/(n + 1) for i in range(1, (n + 1))]) self.xs = tensor( [-1.0 + 2*i/(ns + 1) for i in range(1, (ns + 1))], requires_grad=True ) self.xbn = np.array([-1.0, 1.0]) self.xb = tensor(self.xbn) self.u0 = self.initial(self.xs)
def __init__(self, n_nodes, ns, nb=None, nbs=None, sample_frac=1.0): self.sample_frac = sample_frac # Interior nodes n = round(np.sqrt(n_nodes) + 0.49) self.n = n dxb2 = 1.0 / (n + 1) xl, xr = dxb2 - 1.0, 1.0 - dxb2 sl = slice(xl, xr, n * 1j) x, y = np.mgrid[sl, sl] cond = ~((x >= 0) & (np.abs(y) < dxb2)) self.i_nodes = (x[cond].ravel(), y[cond].ravel()) # Fixed nodes nb = n if nb is None else nb self.nb = nb dxb2 = 1.0 / (nb + 1) _x = np.linspace(dxb2 - 1.0, 1.0 - dxb2, nb) _o = np.ones_like(_x) nslit = int(nb // 2 + 1) x = np.hstack((_x, _o, _x, -1 * _o, np.linspace(0, 1, nslit))) y = np.hstack((_o * -1, _x, _o, _x, np.zeros(nslit))) self.f_nodes = (x, y) # Interior samples self.ns = ns = round(np.sqrt(ns) + 0.49) dxb2 = 1.0 / (ns) xl, xr = dxb2 - 1.0, 1.0 - dxb2 sl = slice(xl, xr, ns * 1j) x, y = np.mgrid[sl, sl] cond = ~((x >= 0) & (np.abs(y) < dxb2)) xs, ys = (tensor(t.ravel(), requires_grad=True) for t in (x[cond], y[cond])) self.p_samples = (xs, ys) self.n_interior = len(self.p_samples[0]) self.rng_interior = np.arange(self.n_interior) self.sample_size = int(self.sample_frac * self.n_interior) # Boundary samples nbs = ns if nbs is None else nbs self.nbs = nbs sl = slice(-1.0, 1.0, nbs * 1j) x, y = np.mgrid[sl, sl] cond = ((x < xl) | (x > xr)) | ((y < xl) | (y > xr)) x, y = x[cond].ravel(), y[cond].ravel() nslit = int(nbs // 2 + 1) xb = np.hstack((x, np.linspace(0, 1.0, nslit))) yb = np.hstack((y, np.zeros(nslit))) xb, yb = (tensor(t, requires_grad=True) for t in (xb, yb)) self.b_samples = (xb, yb)
def __init__(self, n, ns, sample_frac=1.0): self.n = n self.ns = ns self.sample_frac = sample_frac self.xn = np.asarray([i / (n + 1) for i in range(1, (n + 1))]) self.xs = tensor([i / (ns + 1) for i in range(1, (ns + 1))], requires_grad=True) self.xbn = np.array([0.0, 1.0]) self.xb = tensor(self.xbn) self.rng_interior = np.arange(self.ns) self.sample_size = int(self.sample_frac * self.ns)
def _get_errors(nn, fvtu): pts, u_exact = _vtu2data(fvtu) x = pts[:, 0] y = pts[:, 1] xt, yt = tensor(x.ravel()), tensor(y.ravel()) u = nn(xt, yt).detach().cpu().numpy() u.shape = x.shape du = u - u_exact L1 = np.mean(np.abs(du)) L2 = np.sqrt(np.mean(du**2)) Linf = np.max(np.abs(du)) return L1, L2, Linf
def save(self, dirname): '''Save the model and results. ''' nn = self.nn modelfname = os.path.join(dirname, 'model.pt') torch.save(nn.state_dict(), modelfname) rfile = os.path.join(dirname, 'results.npz') x, t = np.mgrid[-1:1:500j, 0:1:11j] xt, tt = tensor(x.ravel()), tensor(t.ravel()) u = nn(xt, tt).detach().cpu().numpy() u.shape = x.shape xp, tp, up = self.get_plot_data() np.savez(rfile, x=x, t=t, u=u, xp=xp, tp=tp, up=up)
def save(self, dirname): modelfname = os.path.join(dirname, 'model.pt') torch.save(self.nn.state_dict(), modelfname) rfile = os.path.join(dirname, 'results.npz') x, y, u = self.get_plot_data() lc = tensor(np.linspace(0, 1, 100)) midc = tensor(0.5*np.ones(100)) xc = torch.cat((lc, midc)) yc = torch.cat((midc, lc)) data = self.nn(xc, yc).detach().cpu().numpy() vc = data[:, 1][:100] uc = data[:, 0][100:] np.savez(rfile, x=x, y=y, u=u, xc=lc, uc=uc, vc=vc)
def boundary_loss(self, nn): xb = tensor(self.boundary(), requires_grad=True) u = nn(xb) _, ux, _ = self._compute_derivatives(u, xb) bc_u = u[0] - u[1] bc_ux = ux[0] - ux[1] return (bc_u**2 + bc_ux**2).sum()
def __init__(self, points, fixed_points, fixed_h=False): super().__init__() n_free = len(points) n_fixed = len(fixed_points) self.n = n = n_free + n_fixed if n_fixed: xmin = min(np.min(points), np.min(fixed_points)) xmax = max(np.max(points), np.max(fixed_points)) else: xmin, xmax = np.min(points), np.max(points) dx = (xmax - xmin) / n self.center = nn.Parameter(tensor(points)) self.fixed = tensor(fixed_points) if fixed_h: self.h = nn.Parameter(torch.tensor(dx)) else: self.h = nn.Parameter(dx * torch.ones(n))
def boundary_loss(self, nn): xb, yb = self.boundary() xbn, ybn = (t.detach().cpu().numpy() for t in (xb, yb)) u = nn(xb, yb) ub = tensor(self.exact(xbn, ybn)) bc = u - ub return (bc**2).sum()
def __init__(self, n_nodes, ns, nb=None, nbs=None, sample_frac=1.0): self.sample_frac = sample_frac # Interior nodes n = round(np.sqrt(n_nodes) + 0.49) self.n = n dxb2 = 1.0/(n + 1) xl, xr = dxb2, 1.0 - dxb2 sl = slice(xl, xr, n*1j) x, y = np.mgrid[sl, sl] self.i_nodes = (x.ravel(), y.ravel()) # Fixed nodes nb = n if nb is None else nb self.nb = nb if nb == 0: self.f_nodes = ([], []) else: dxb2 = 1.0/(nb) _x = np.linspace(dxb2, 1.0 - dxb2, nb) _o = np.ones_like(_x) x = np.hstack((_x, _o, _x, 0.0*_o)) y = np.hstack((_o*0.0, _x, _o, _x)) self.f_nodes = (x, y) # Interior samples self.ns = ns = round(np.sqrt(ns) + 0.49) dxb2 = 1.0/(ns) xl, xr = dxb2, 1.0 - dxb2 sl = slice(xl, xr, ns*1j) x, y = np.mgrid[sl, sl] xs, ys = (tensor(t.ravel(), requires_grad=True) for t in (x, y)) self.p_samples = (xs, ys) # Boundary samples nbs = ns if nbs is None else nbs self.nbs = nbs sl = slice(0, 1.0, nbs*1j) _x = np.linspace(dxb2, 1.0 - dxb2, nbs) o = np.ones_like(_x) def tg(x): return tensor(x, requires_grad=True) self.left = left = (tg(0.0*o), tg(_x)) self.right = right = (tg(o), tg(_x)) self.bottom = bottom = (tg(_x), tg(o)*0.0) self.top = top = (tg(_x), tg(o)) self.b_samples = ( torch.cat([x[0] for x in (top, bottom, left, right)]), torch.cat([x[1] for x in (top, bottom, left, right)]) ) self.n_interior = len(self.p_samples[0]) self.rng_interior = np.arange(self.n_interior) self.sample_size = int(self.sample_frac*self.n_interior)
def boundary_loss(self, nn): xb, tb = self.boundary() u = nn(xb, tb) ub = self._boundary_condition( xb.detach().cpu().numpy(), tb.detach().cpu().numpy() ) bc = u - tensor(ub) l = (bc**2).sum() return l
def forward(self, x): x = x.unsqueeze(1) y = self.layer1(x) y = self.activation(y) if self.use_pu: y1 = y.sum(axis=1).unsqueeze(1) else: y1 = tensor(1.0) y = self.layer2(y / y1) return y.squeeze()
def __init__(self, pde, activation, fixed_h=False, use_pu=False, max_nbrs=25): super().__init__() self.activation = activation self.use_pu = use_pu self.max_nbrs = max_nbrs points = pde.nodes() fixed_points = pde.fixed_nodes() n_free = len(points[0]) n_fixed = len(fixed_points[0]) self.n = n = n_free + n_fixed if n_fixed: dsize = np.ptp(np.hstack((points[0], fixed_points[0]))) else: dsize = np.ptp(points[0]) dx = dsize / np.sqrt(n) self.dx = dx pts = tensor(np.zeros((n_free, 2))) pts[:, 0] = tensor(points[0]) pts[:, 1] = tensor(points[1]) self.points = nn.Parameter(pts) fpts = tensor(np.zeros((n_fixed, 2))) fpts[:, 0] = tensor(fixed_points[0]) fpts[:, 1] = tensor(fixed_points[1]) self.f_points = fpts self.fixed_h = fixed_h if fixed_h: self.h = nn.Parameter(tensor(dx)) else: self.h = nn.Parameter(dx * tensor(np.ones(self.n))) n_vars = pde.n_vars() if n_vars > 1: self.u = nn.Parameter(tensor(np.zeros((self.n, n_vars)))) else: self.u = nn.Parameter(tensor(np.zeros(self.n))) self.sph = SPHConv(self.activation)
def __init__(self, points, fixed_points, fixed_h=False): super().__init__() n_free = len(points[0]) n_fixed = len(fixed_points[0]) self.n = n = n_free + n_fixed if n_fixed: dsize = np.ptp(np.hstack((points[0], fixed_points[0]))) else: dsize = np.ptp(points[0]) dx = dsize/np.sqrt(n) self.dx = dx self.x = nn.Parameter(tensor(points[0])) self.y = nn.Parameter(tensor(points[1])) fp = fixed_points self.xf = tensor(fp[0]) self.yf = tensor(fp[1]) self.fixed_h = fixed_h if fixed_h: self.h = nn.Parameter(tensor(dx)) else: self.h = nn.Parameter(dx*torch.ones(n))
def save(self, dirname): '''Save the model and results. ''' modelfname = os.path.join(dirname, 'model.pt') torch.save(self.nn.state_dict(), modelfname) rfile = os.path.join(dirname, 'results.npz') xp, yp, up = self.get_plot_data() uex_p = self.pde.exact(xp, yp) x, t = np.mgrid[0:1:100j, 0:0.2:21j] xt, tt = tensor(x.ravel()), tensor(t.ravel()) u = self.nn(xt, tt).detach().cpu().numpy() u_exact = self.pde.exact(x, t) u.shape = x.shape np.savez(rfile, x=x, t=t, u=u, u_exact=u_exact, xp=xp, yp=yp, up=up, uex_p=uex_p)
def __init__(self, f_nodes_int, f_nodes_bdy, f_samples_int, f_samples_bdy, sample_frac=1.0): self.f_nodes_int = f_nodes_int self.f_nodes_bdy = f_nodes_bdy self.f_samples_int = f_samples_int self.f_samples_bdy = f_samples_bdy self.sample_frac = sample_frac # Interior nodes: Free xi, yi = self._extract_coordinates(f_nodes_int) self.interior_nodes = (xi, yi) ## Boundary nodes: Fixed xb, yb = self._extract_coordinates(f_nodes_bdy) self.boundary_nodes = (xb, yb) ## Interior samples xi, yi = self._extract_coordinates(f_samples_int) self.interior_samples = (tensor(xi, requires_grad=True), tensor(yi, requires_grad=True)) self.n_interior = len(xi) self.rng_interior = np.arange(self.n_interior) self.sample_size = int(self.sample_frac * self.n_interior) ## Boundary samples xb, yb = self._extract_coordinates(f_samples_bdy) self.boundary_samples = (tensor(xb, requires_grad=True), tensor(yb, requires_grad=True))
def get_plot_data(self): x, y = self.pde.plot_points() xt, yt = tensor(x.ravel()), tensor(y.ravel()) pn = self.nn(xt, yt).detach().cpu().numpy() pn.shape = x.shape + (3,) return x, y, pn
def centers(self): return tensor([]), tensor([])
def tg(x): return tensor(x, requires_grad=True)
def get_plot_data(self): x = self.pde.plot_points() xt = tensor(x) pn = self.nn(xt).detach().cpu().numpy() return x, pn
def boundary_loss(self, nn): xb, tb = self.boundary() u = nn(xb, tb) ub = self.exact(xb.detach().cpu().numpy(), tb.detach().cpu().numpy()) bc = u - tensor(ub) return (bc**2).sum()
def old_boundary_loss(self, nn): xb = self.boundary() u = nn(xb) ub = -1.0 bc = u - tensor(ub) return (bc**2).sum()
def plot_points(self): xi, yi = self._extract_coordinates(self.f_samples_int) return (tensor(xi), tensor(yi))
def __init__(self): self._sp = nn.Softplus() self.k = tensor([1.0 + 4.0*np.log(2.0)]) self.fac = self._sp(tensor([1.0]))
def widths(self): return tensor([])
def _get_weights(self, n_modes): ws = np.zeros((1, self.n_modes)) for i in range(self.n_modes): ws[0, i] = i + 1.0 ws = tensor(ws) return ws
def boundary_loss(self, nn): u = nn(self.boundary()) ub = tensor(self.exact(self.xbn)) bc = u - ub return 1000 * (bc**2).sum()