def testMarginalEstimationStrategy(self): xlim = np.array([[-1, 1], [-1, 1]]) trans = JointTransformation() dists = [] for idim in range(xlim.shape[0]): trans.add(LinearTransformation(xlim[idim, 0], xlim[idim, 1])) dists.append(Uniform(xlim[idim, 0], xlim[idim, 1])) dist = J(dists) def f(x): return np.prod([(1 + xi) * (1 - xi) for xi in x]) def F(x): return 1. - x**3 / 3. grid, alpha_vec = interpolate(f, 1, 2, gridType=GridType_Poly, deg=2, trans=trans) alpha = alpha_vec.array() q = (F(1) - F(-1))**2 q1 = doQuadrature(grid, alpha) q2 = AnalyticEstimationStrategy().mean(grid, alpha, dist, trans)["value"] self.assertTrue(abs(q - q1) < 1e-10) self.assertTrue(abs(q - q2) < 1e-10) ngrid, nalpha, _ = MarginalAnalyticEstimationStrategy().mean( grid, alpha, dist, trans, [[0]]) self.assertTrue(abs(nalpha[0] - 2. / 3.) < 1e-10) plotSG3d(grid, alpha) plt.figure() plotSG1d(ngrid, nalpha) plt.show()
def discretize1d_identity(self): # discretize the product of both grid, alpha = self.interpolate(1, 3, 4) jgrid, jalpha = discretizeProduct(grid, alpha, grid, alpha) # get reference values n = 200 x = np.linspace(0, 1, n) y1 = np.array([self.f([xi])**2 for xi in x]) y2 = np.array( [evalSGFunction(grid, alpha, np.array([xi]))**2 for xi in x]) y3 = np.array( [evalSGFunction(jgrid, jalpha, np.array([xi])) for xi in x]) assert np.sum(abs(y3 - y2)) < 1e-13 plt.plot(x, y1, label="solution") plt.plot(x, y2, label="product") plotSG1d(jgrid, jalpha, n=n, label="poly") plt.title("1 linear grid same level (maxlevel=%i, deg=%i), err = %g" % (jgrid.getStorage().getMaxLevel(), getDegree(jgrid), np.sum(abs(y3 - y2)))) plt.legend() plt.show()
def runAnalysis(self, analysis, uqManager, alabel, blabel, out, plot, results): if out: # ---------------------------------------------- # write stats # ---------------------------------------------- pathResults = os.path.join(self.pathResults, alabel, blabel) if not os.path.exists(pathResults): os.mkdir(pathResults) if self.numDims > 1: print("sobol indices") analysis.writeSensitivityValues(os.path.join(pathResults, alabel)) print("surpluses") analysis.writeSurplusesLevelWise(os.path.join(pathResults, alabel)) print("stats") analysis.writeStats(os.path.join(pathResults, alabel)) print("moments") analysis.writeMoments(os.path.join(pathResults, alabel)) print("sampling") path = os.path.join(pathResults, "samples") if not os.path.exists(path): os.mkdir(path) analysis.sampleGrids(os.path.join(path, alabel)) # ---------------------------------------------- # do some plotting # ---------------------------------------------- ts = uqManager.getKnowledge().getAvailableTimeSteps() sobolIndices = np.zeros((len(ts), 2 ** len(self.params.activeParams()) - 1)) for i, t in enumerate(ts): grid, alpha = uqManager.getKnowledge()\ .getSparseGridFunction(uqManager.getQoI(), t) print("-" * 80) print("plot: t=%g (i=%i), N=%i" % (t, i, grid.getSize())) # scatter plot of surpluses level wise surpluses = analysis.computeSurplusesLevelWise(t) maxLevel = grid.getStorage().getMaxLevel() if out and plot: fig = plotSurplusLevelWise(surpluses, maxLevel) fig.savefig(os.path.join(pathResults, "surpluses_t%g") % t) plt.close(fig) (fig, ax), A = plotSGNodal3d(grid, alpha) ax.set_xlabel("x") ax.set_ylabel("y") fig.savefig(os.path.join(pathResults, "nodal_t%g.png" % t)) plt.close(fig) # plot sparse grid approximation if self.numDims < 3: if self.numDims == 1: fig = plt.figure() plotSG1d(grid, alpha) plt.xlabel("x") elif self.numDims == 2: fig, ax, _ = plotSG3d(grid, alpha) ax.set_xlabel("x") ax.set_ylabel("y") fig.savefig(os.path.join(pathResults, "function_t%g.png" % t)) plt.close(fig) # write nodal values to file writeDataARFF({"filename": os.path.join(pathResults, "nodal_t%g.arff" % t), "names": self.params.activeParams().getNames() + ["value"], "data": DataMatrix(A)}) # show sobol indices me = None te = None if self.numDims > 1: anova = analysis.getAnovaDecomposition(t=t) me = anova.getSobolIndices() print("-------------- Sobol Indices (t = %i) ------------------" % t) for j, perm in enumerate(anova.getSortedPermutations(list(me.keys()))): print("%s: %s" % (perm, me[perm])) sobolIndices[i, j] = me[perm] print(sum(sobolIndices[i, :]), "==", 1) # ---------------------------------------------------------- # total effects te = anova.getTotalEffects() print("-------------- Total Effects (t = %i) -----------------" % t) for key, val in sorted(te.items()): print("%s: %s" % (key, val)) print("---------------------------------------------------------") print() if t not in results["results"]: results["results"][t] = {} results["knowledge_types"] = uqManager.getKnowledgeTypes() results["results"][t][maxLevel] = {} results["results"][t][maxLevel]["grid_size"] = grid.getSize() results["results"][t][maxLevel]["maxLevel"] = maxLevel results["results"][t][maxLevel]["surpluses"] = surpluses results["results"][t][maxLevel]["sobol_indices"] = me results["results"][t][maxLevel]["total_effects"] = te results["results"][t][maxLevel]["stats"] = uqManager.stats results["results"][t][maxLevel]["mean_estimated_per_iteration"] = {} for it, res in list(analysis.mean(ts=[t], reduce=False).items()): results["results"][t][maxLevel]["mean_estimated_per_iteration"][it] = res["value"] # maximum iteration -> final value it = max(results["results"][t][maxLevel]["mean_estimated_per_iteration"].keys()) results["results"][t][maxLevel]["mean_estimated"] = \ results["results"][t][maxLevel]["mean_estimated_per_iteration"][it] results["results"][t][maxLevel]["var_estimated_per_iteration"] = {} for it, res in list(analysis.var(ts=[t], reduce=False).items()): results["results"][t][maxLevel]["var_estimated_per_iteration"][it] = res["value"] # maximum iteration -> final value it = max(results["results"][t][maxLevel]["var_estimated_per_iteration"].keys()) results["results"][t][maxLevel]["var_estimated"] = \ results["results"][t][maxLevel]["var_estimated_per_iteration"][it] # -------------------------------------------- if out and plot and self.numDims > 1: names = anova.getSortedPermutations(list(me.keys())) fig = plotSobolIndices(sobolIndices, ts=ts, legend=True, names=names) fig.savefig(os.path.join(pathResults, "sobol.png")) plt.close(fig)
builder = builder.withStopPolicy().withAdaptiveIterationLimit(3) builder = builder.withCGSolver() builder.withAccuracy(1e-7) builder.withImax(100) # Create the final learner object learner = builder.andGetResult() gs = learner.grid.getStorage() print ("Dimensions: %i" % gs.getDimension()) print ("Grid points: %i" % gs.getSize()) print("================== Starting learning ==================") learner.setVerbosity(False) learner.learnData() print(learner.alpha) print("=======================================================") if numDims == 1: plt.scatter(samples[:, 0], values) plotSG1d(learner.grid, learner.alpha, color="red") else: plotSG2d(learner.grid, learner.alpha) plt.scatter(samples[:, 0], samples[:, 1]) plt.show()
plt.savefig("sin_analytic.pdf") # get a sparse grid approximation grid = Grid.createLinearGrid(numDims) grid.getGenerator().regular(level) gs = grid.getStorage() alpha = hierarchizeFun(fun) print("l=%i: (gs=%i)" % (level, grid.getSize())) print("-" * 80) # plot the result if plot and numDims < 3: fig = plt.figure() if numDims == 1: plotSG1d(grid, alpha) elif numDims == 2: plotSG2d(grid, alpha, show_negative=False, show_grid_points=True) plt.title(r"$\ell = %i, N = %i$" % (level, grid.getStorage().getSize())) fig.show() if numDims == 2: fig, ax, _ = plotSG3d(grid, alpha, grid_points_at=-2) ax.set_title(r"$\ell = %i, N = %i$" % (level, grid.getStorage().getSize())) ax.set_zlim(-2, 2) fig.show() plt.savefig("sin_sg_negative.pdf") plt.close(fig)
fig.show() # get a sparse grid approximation grid = Grid.createLinearGrid(numDims) grid.getGenerator().regular(level) gs = grid.getStorage() alpha = hierarchizeFun(fun) print("l=%i: (gs=%i)" % (level, grid.getSize())) print("-" * 80) # plot the result if numDims < 3: fig = plt.figure() if numDims == 1: plotSG1d(grid, alpha) elif numDims == 2: plotSG2d(grid, alpha, show_negative=False, show_grid_points=True) plt.title("neg: #gp = %i" % grid.getStorage().getSize()) fig.show() if code == "c++": newGrid = Grid.createLinearGrid(numDims) alpha_vec = DataVector(alpha) opLimit = createOperationMakePositive( grid, MakePositiveCandidateSearchAlgorithm_Intersections, MakePositiveInterpolationAlgorithm_SetToZero, True) opLimit.makePositive(newGrid, alpha_vec) grid = newGrid