Skip to content

Commit 7fcbebb

Browse files
author
Giacomo Cristinelli
committed
new files
1 parent a02d5e5 commit 7fcbebb

File tree

5 files changed

+343
-334
lines changed

5 files changed

+343
-334
lines changed

GCG.py

+26-55
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,11 @@
1313
import scipy.sparse as cp
1414
from dolfin import *
1515
from matplotlib import pyplot as pp
16-
from mshr import *
1716

18-
from GCG_operations import _sparsify, _Dinkelbach, _symmetric_rectangle_mesh, plot_result, TV
17+
from GCG_operations import _sparsify, TV
18+
from mesh import _create_mesh
19+
from insertion import _Dinkelbach
20+
from plots import plot_result, plot_convergence, plot_energy
1921
from SSN import _SSN
2022

2123

@@ -36,42 +38,20 @@ def _main_():
3638
start_time = time.time()
3739

3840
# A1.---STORING INFO IN THE LOG FILE
39-
flog.write("Variables:\n")
41+
with open('setup.conf', 'r') as conf_file:
42+
# Read the contents of the conf file
43+
conf_content = conf_file.read()
4044

41-
if Random_mesh and d == 2:
42-
flog.write(" Random mesh in a rectangle of size {}x{}, with indicator {}\n".format(lx2 - lx1, ly2 - ly1, N))
43-
elif Random_mesh and d == 3:
44-
flog.write(
45-
" Random mesh in a cube of size {}x{}x{}, with indicator {}\n".format(lx2 - lx1, ly2 - ly1, lz2 - lz1, N2))
46-
elif not Random_mesh and d == 2:
47-
flog.write(" Standard crossed mesh with {}x{} squares in a rectangle of size {}x{}\n".format(Nx, Ny, lx2 - lx1,
48-
ly2 - ly1))
49-
elif not Random_mesh and d == 3:
50-
flog.write(" Regular Box mesh with {}x{}x{} cubes in a cube of size {}x{}x{}\n".format(Nx, Ny, Nz, lx2 - lx1,
51-
ly2 - ly1, lz2 - lz1))
52-
else:
53-
raise Exception("Not supported dimension. Choose d=2,3")
54-
55-
flog.write(" The dimension is {}\n".format(d))
56-
flog.write(" The regularizer parameter is {}\n".format(alpha))
57-
flog.write(" TV with boundary: {}.\n".format(boundary))
58-
flog.write(" GCG has tolerance {}, and {} max iterations.\n".format(tolerance, max_iterations))
45+
# Open a text file for writing
46+
flog.write(conf_content + '\n')
5947

6048
# ---GEOMETRY LOOP ------------------------------------------------------------------------------------------------
6149

6250
flog.write("Geometry loop:\n")
6351
print("Starting geometry loop...\n")
6452

6553
# B1.---MESH GENERATION AND FUNCTION SPACES
66-
if Random_mesh and d == 2:
67-
mesh = _symmetric_rectangle_mesh(lx2, ly2, N)
68-
elif Random_mesh and d == 3:
69-
domain = Box(Point(lx1, ly1, lz1), Point(lx2, ly2, lz2))
70-
mesh = generate_mesh(domain, N2)
71-
elif not Random_mesh and d == 2:
72-
mesh = RectangleMesh(Point(lx1, ly1), Point(lx2, ly2), Nx, Ny, 'crossed')
73-
else:
74-
mesh = BoxMesh(Point(lx1, ly1, lz1), Point(lx2, ly2, lz2), Nx, Ny, Nz)
54+
mesh = _create_mesh(Random_mesh, d, lx1, lx2, ly1, ly2, lz1, lz2, Nx, Ny, Nz, N, N2, rd)
7555

7656
V = FunctionSpace(mesh, 'DG', 0) # PWC
7757
VL = FunctionSpace(mesh, 'CG', 1) # PWL
@@ -80,13 +60,9 @@ def _main_():
8060
e2f = mesh.topology()(d - 1, d)
8161
vol_face_fn = Function(V)
8262
bdy_length_fn = Function(V)
83-
int_lengths = np.empty(0)
8463
bdy_length = np.empty(0)
85-
int_cells = np.empty(shape=[0, 2])
8664
bdy_faces = np.empty(0)
87-
internal_facets = np.empty(0)
8865
facet_size = np.empty(0)
89-
bdy_facets = np.empty(0)
9066

9167
if d == 2:
9268
flog.write(" Made a mesh with {} vertices, and {} faces \n".format(mesh.num_vertices(), mesh.num_faces()))
@@ -121,6 +97,10 @@ def _main_():
12197
bdy_faces = np.append(bdy_faces, e2f(facet)[0])
12298
bdy_length = np.append(bdy_length, facet_size[facet])
12399

100+
# defining integrating measures
101+
domains = MeshFunction("size_t", mesh, mesh.topology().dim(), 0)
102+
dx = Measure("dx", domain=mesh, subdomain_data=domains)
103+
124104
# B2.---GRAPH GENERATION, creating graph with (d-1)-facets areas/length as weights
125105
G = maxflow.GraphFloat()
126106
G.add_nodes(mesh.num_cells())
@@ -139,6 +119,7 @@ def _main_():
139119
bdr = DirichletBC(VL, g, DomainBoundary())
140120
v = TestFunction(VL)
141121
u = TrialFunction(VL)
122+
142123
mass_form = v * u * dx
143124
M = assemble(mass_form)
144125
mat = as_backend_type(M).mat()
@@ -204,32 +185,30 @@ def _main_():
204185

205186
# D1.---WARM UP ITERATION
206187
coefficients, mean, adjoint, optval, misfit = _SSN(Kl, Km, coefficients, mean, measurements, alpha, M)
207-
flog.write("Warm up iteration:\n")
208-
flog.write(" The mean is {} \n".format(mean))
209-
flog.write(" The coefficients are {} \n".format(coefficients))
210-
flog.write(" The adjoint is {}\n".format(adjoint))
211-
flog.write(" Current value is %.6e \n" % optval)
212-
213188
j = 0
214189
Uk = Function(V)
215-
prev_Uk = Function(V)
216190
Uk.vector()[:] = mean.flatten() * U0_arr + Ul @ coefficients
191+
217192
opt = np.zeros(max_iterations + 1)
218193
energy = np.zeros(max_iterations + 1)
219194
rel_change = np.zeros(max_iterations + 1)
220195
data = []
221196
total_time = 0
222197

198+
energy[0] = 0.5 * assemble((Y0 - Yd) ** 2 * dx)
199+
export = [0, total_time, energy[0], optval/alpha, 0]
200+
data.append(export)
201+
223202
# D2.---MAIN LOOP
224203
while (j == 0) or (j <= max_iterations and opt[j - 1] > tolerance):
225204
start_iteration_time = time.time()
226205
flog.write("Iteration {} of Conditional gradient: \n".format(j))
227206
print("Starting iteration %s of GCG\n" % j)
207+
228208
# Solve state and adjoint equation
229209
rhk = Uk * v * dx
230210
Yk = Function(VL)
231211
Vk = Function(VL)
232-
Vkc = Function(VL)
233212
prev_time = time.time()
234213
prev_Uk = Uk
235214
solve(Lap == rhk, Yk, bdr, solver_parameters={'linear_solver': 'mumps'})
@@ -241,7 +220,7 @@ def _main_():
241220
flog.write(" Second PDE solve took %.2f seconds \n" % (time.time() - prev_time))
242221

243222
# making sure pk has zero average
244-
Pkp = project(Pk, V)
223+
Pkp = interpolate(Pk, V)
245224
intergral_pk = assemble(Pkp * dx)
246225
volume_domain = assemble(interpolate(Constant(1.0), V) * dx)
247226
Pkv = np.subtract(Pkp.vector(), intergral_pk / volume_domain)
@@ -284,17 +263,9 @@ def _main_():
284263
bdy_faces, Uk)
285264
rel_change[j] = assemble(abs(Uk - prev_Uk) * dx)/assemble(abs(Uk) * dx)
286265

287-
pp.plot(range(len(np.trim_zeros(opt))), np.log10(np.trim_zeros(opt)))
288-
pp.xlabel("iteration")
289-
pp.ylabel("convergence indicator")
290-
pp.savefig(rd + '/indicator.png', dpi=300)
291-
pp.close()
292-
pp.plot(range(len(np.trim_zeros(energy))), np.trim_zeros(energy))
293-
pp.xlabel("iteration")
294-
pp.ylabel("energy")
295-
# pp.ylim([0, 0.001])
296-
pp.savefig(rd + '/energy.png', dpi=300)
297-
pp.close()
266+
plot_convergence(rd, opt)
267+
plot_energy(rd, energy)
268+
298269
flog.write(" Current surrogate energy value is %.6e, with convergence indicator, %.6e \n" % (optval, opt[j]))
299270
flog.write(" Current actual energy value is %.6e \n" % (energy[j]))
300271
print("Step %s of GCG finished with energy value %.6e and convergence indicator %.6e \n" % (j, optval, opt[j]))
@@ -303,7 +274,7 @@ def _main_():
303274
plot_result(mesh, int_cells, flog, rd, Pkp, 3, j, d)
304275

305276
total_time += time.time() - start_iteration_time
306-
export = [j, total_time, energy[j], opt[j], rel_change[j]]
277+
export = [j+1, total_time, energy[j], opt[j], rel_change[j]]
307278
data.append(export)
308279
j += 1
309280

0 commit comments

Comments
 (0)