def run(plotIt=True): # Step1: Generate Tensor and Curvilinear Mesh sz = [40, 40] tM = discretize.TensorMesh(sz) rM = discretize.CurvilinearMesh( discretize.utils.exampleLrmGrid(sz, 'rotate')) # Step2: Direct Current (DC) operator def DCfun(mesh, pts): D = mesh.faceDiv sigma = 1e-2 * np.ones(mesh.nC) MsigI = mesh.getFaceInnerProduct(sigma, invProp=True, invMat=True) A = -D * MsigI * D.T A[-1, -1] /= mesh.vol[-1] # Remove null space rhs = np.zeros(mesh.nC) txind = discretize.utils.closestPoints(mesh, pts) rhs[txind] = np.r_[1, -1] return A, rhs pts = np.vstack((np.r_[0.25, 0.5], np.r_[0.75, 0.5])) # Step3: Solve DC problem (LU solver) AtM, rhstM = DCfun(tM, pts) AinvtM = SolverLU(AtM) phitM = AinvtM * rhstM ArM, rhsrM = DCfun(rM, pts) AinvrM = SolverLU(ArM) phirM = AinvrM * rhsrM if not plotIt: return # Step4: Making Figure fig, axes = plt.subplots(1, 2, figsize=(12 * 1.2, 4 * 1.2)) vmin, vmax = phitM.min(), phitM.max() dat = tM.plotImage(phitM, ax=axes[0], clim=(vmin, vmax), grid=True) cb0 = plt.colorbar(dat[0], ax=axes[0]) cb0.set_label("Voltage (V)") axes[0].set_title('TensorMesh') dat = rM.plotImage(phirM, ax=axes[1], clim=(vmin, vmax), grid=True) cb1 = plt.colorbar(dat[0], ax=axes[1]) cb1.set_label("Voltage (V)") axes[1].set_title('CurvilinearMesh')
DIV = mesh.faceDiv # Faces to cell centers divergence Mf_inv = mesh.getFaceInnerProduct(invMat=True) Mc = sdiag(mesh.vol) A = Mc * DIV * Mf_inv * DIV.T * Mc # Define RHS (charge distributions at cell centers) xycc = mesh.gridCC kneg = (xycc[:, 0] == -10) & (xycc[:, 1] == 0) # -ve charge distr. at (-10, 0) kpos = (xycc[:, 0] == 10) & (xycc[:, 1] == 0) # +ve charge distr. at (10, 0) rho = np.zeros(mesh.nC) rho[kneg] = -1 rho[kpos] = 1 # LU factorization and solve AinvM = SolverLU(A) phi = AinvM * rho # Compute electric fields E = Mf_inv * DIV.T * Mc * phi # Plotting fig = plt.figure(figsize=(14, 4)) ax1 = fig.add_subplot(131) mesh.plotImage(rho, vType='CC', ax=ax1) ax1.set_title('Charge Density') ax2 = fig.add_subplot(132) mesh.plotImage(phi, vType='CC', ax=ax2) ax2.set_title('Electric Potential')
mesh.setCellGradBC(["neumann", "neumann"]) # Set Neumann BC G = mesh.cellGrad D = mesh.faceDiv M = -D * Mf_alpha_inv * G * Mc + Afc * sdiag(u) * Mf_inv * G * Mc # Set time stepping, initial conditions and final matricies dt = 0.02 # Step width p = np.zeros(mesh.nC) # Initial conditions p(t=0)=0 I = sdiag(np.ones(mesh.nC)) # Identity matrix B = I + dt * M s = Mc_inv * q Binv = SolverLU(B) # Plot the vector field fig = plt.figure(figsize=(15, 15)) ax = 9 * [None] ax[0] = fig.add_subplot(332) mesh.plotImage( u, ax=ax[0], v_type="F", view="vec", stream_opts={"color": "w", "density": 1.0}, clim=[0.0, 10.0], )
def test_full_covariances(self): print("Test Full covariances: ") print("=======================") # Fit a Gaussian Mixture clf = WeightedGaussianMixture( mesh=self.mesh, n_components=self.n_components, covariance_type="full", max_iter=1000, n_init=10, tol=1e-8, means_init=self.means, warm_start=True, precisions_init=np.linalg.inv(self.sigma), weights_init=self.proportions, ) clf.fit(self.samples) # Define reg reg = make_PGI_regularization( mesh=self.mesh, gmmref=clf, approx_gradient=True, alpha_x=0.0, wiresmap=self.wires, cell_weights_list=self.cell_weights_list, ) mref = mkvc(clf.means_[clf.predict(self.samples)]) # check score value dm = self.model - mref score_approx0 = reg(self.model) score_approx1 = 0.5 * dm.dot(reg.deriv2(self.model, dm)) passed_score_approx = np.allclose(score_approx0, score_approx1) self.assertTrue(passed_score_approx) reg.objfcts[0].approx_eval = False score = reg(self.model) - reg(mref) passed_score = np.allclose(score_approx0, score, rtol=1e-4) self.assertTrue(passed_score) print("scores for PGI & Full Cov. are ok.") # check derivatives as an optimization on locally quadratic function deriv = reg.deriv(self.model) reg.objfcts[0].approx_gradient = False reg.objfcts[0].approx_hessian = False deriv_full = reg.deriv(self.model) passed_deriv1 = np.allclose(deriv, deriv_full, rtol=1e-4) self.assertTrue(passed_deriv1) print("1st derivatives for PGI & Full Cov. are ok.") Hinv = SolverLU(reg.deriv2(self.model)) p = Hinv * deriv direction2 = np.c_[self.wires * p] passed_derivative = np.allclose( mkvc(self.samples - direction2), mkvc(mref), rtol=1e-4 ) self.assertTrue(passed_derivative) print("2nd derivatives for PGI & Full Cov. are ok.") if self.PlotIt: print("Plotting", self.PlotIt) import matplotlib.pyplot as plt xmin, xmax = ymin, ymax = self.samples.min(), self.samples.max() x, y = np.mgrid[xmin:xmax:0.5, ymin:ymax:0.5] pos = np.empty(x.shape + (2,)) pos[:, :, 0] = x pos[:, :, 1] = y rv = clf.score_samples(pos.reshape(-1, 2)) rvm = clf.predict(pos.reshape(-1, 2)) figfull, axfull = plt.subplots(1, 1, figsize=(16, 8)) figfull.suptitle("Full Covariances Tests") axfull.contourf(x, y, rvm.reshape(x.shape), alpha=0.25, cmap="brg") axfull.contour(x, y, rv.reshape(x.shape), 20) axfull.scatter( self.samples[:, 0], self.samples[:, 1], color="blue", s=5.0, alpha=0.25 ) axfull.quiver( self.samples[:, 0], self.samples[:, 1], -(self.wires.s0 * deriv), -(self.wires.s1 * deriv), color="red", alpha=0.25, ) axfull.quiver( self.samples[:, 0], self.samples[:, 1], -direction2[:, 0], -direction2[:, 1], color="k", ) axfull.scatter( (self.samples - direction2)[:, 0], (self.samples - direction2)[:, 1], color="k", s=50.0, ) axfull.set_xlabel("Property 1") axfull.set_ylabel("Property 2") axfull.set_title("PGI with W") plt.show()