generated from underworld-community/template-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExp_E_mixed-slip-version.py
384 lines (269 loc) · 10.4 KB
/
Exp_E_mixed-slip-version.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# ---
# jupyter:
# jupytext:
# formats: ipynb,md,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.13.5
# kernelspec:
# display_name: Python 3 (ipykernel)
# language: python
# name: python3
# ---
# This model of Exp E is from Feb 2022.
#
# It models the glacier described in Pattyn (...) as a deformed mesh. Some ingenuity is necessary for this to work, so maybe there will be another version necessary. Obe that just uses particles.
# # Basic python imports and model settings
# +
from underworld import function as fn
import underworld as uw
import underworld.visualisation as vis
import matplotlib.pyplot as pyplot
import numpy as np
from scipy.spatial import distance
import math
import os
import sys
import time
from scipy.signal import savgol_filter
g = 9.81
ice_density = 910.
A = 1e-16
n = 3.
# -
# ## Get topo info from file
# +
topo = np.genfromtxt("topo.csv")
topo_base = topo[:, 0:-2]
topo_surf = topo[:, 0:-1]
topo_surf = np.delete(topo_surf, obj=1, axis=1)
pyplot.plot(topo_base[:,0], topo_base[:,-1])
pyplot.plot(topo_surf[:,0], topo_surf[:,-1])
pyplot.show()
# +
resX = topo_base.shape[0] - 1
resY = topo_base.shape[0] - 1
air_height = 50.
maxX = np.max(topo_surf[:,0])
maxY = np.max(topo_surf[:,1]) + air_height
minX = np.min(topo_base[:,0])
minY = np.min(topo_base[:,1])
print(f"resX: {resX}, resY: {resY}" )
print(f"minX: {minX}, minY: {minY}" )
print(f"maxX: {maxX}, maxY: {maxY}" )
cell_height = maxY / resY
cell_width = maxX / resX
# -
# # The mesh
# +
elementType = "Q1/dQ0"
mesh = uw.mesh.FeMesh_Cartesian(elementType=(elementType),
elementRes=(resX, resY),
minCoord=(minX, minY),
maxCoord=(maxX, maxY),
periodic=[False, False])
submesh = mesh.subMesh
velocityField = uw.mesh.MeshVariable(mesh=mesh, nodeDofCount=mesh.dim)
pressureField = uw.mesh.MeshVariable(mesh=mesh, nodeDofCount=1)
pressureField.data[:] = 0.
velocityField.data[:] = [0., 0.]
# -
# ## Deform the mesh
figMesh = vis.Figure(figsize=(1200,600))
figMesh.append( vis.objects.Mesh(mesh, nodeNumbers=True))
# +
dx = (maxX - minX) / resX
dy = (maxX - maxY) / resY
def mesh_deform_base_Ind(section, fixPoint_index, fixPoint, mi):
section[fixPoint_index] = fixPoint
seqN = len(section)
for index in range(len(section)):
maxCoord = np.max(section)
minCoord = np.min(section)
section[index] = fixPoint + (index-fixPoint_index)*(maxCoord-fixPoint) / (seqN-fixPoint_index-1)
zz_pow = (section[index] - fixPoint)**mi
zz_pow_max = (maxCoord - fixPoint)**mi
section[index] =fixPoint + (section[index]-fixPoint) * zz_pow / zz_pow_max
return (section)
with mesh.deform_mesh():
for indexx in range(resX + 1):
start_x = dx * indexx
interface_y = topo_base[indexx, 1]
ind = np.where( abs(mesh.data[:, 0] - start_x) < 0.01*dx )
mesh.data[ind[0],1] = mesh_deform_base_Ind(mesh.data[ind[0], 1], 0, interface_y, 0.2)
# -
figMesh.show()
# # A material swarm
# +
# Initialise the 'materialVariable' data to represent different materials.
materialV = 0 # ice, isotropic
materialA = 1 # air
part_per_cell = 50
swarm = uw.swarm.Swarm(mesh=mesh, particleEscape=True)
swarmLayout = uw.swarm.layouts.PerCellSpaceFillerLayout(swarm=swarm, particlesPerCell=part_per_cell)
swarm.populate_using_layout(layout=swarmLayout)
materialVariable = swarm.add_variable(dataType="int", count=1)
coord = fn.input()
materialVariable.data[:] = materialA
iceBody = fn.shape.Polygon( np.append(topo_surf, topo_base[::-1], axis=0) )
for index in range( len(swarm.particleCoordinates.data) ):
co = swarm.particleCoordinates.data[index][:]
if iceBody.evaluate (tuple (co)):
materialVariable.data[index] = materialV
measurementSwarm = uw.swarm.Swarm(mesh=mesh, particleEscape=True)
# create pop control object
pop_control1 = uw.swarm.PopulationControl(swarm, aggressive=True, particlesPerCell=part_per_cell)
advector1 = uw.systems.SwarmAdvector(swarm=swarm, velocityField=velocityField, order=2)
pop_control2 = uw.swarm.PopulationControl(measurementSwarm)
advector2 = uw.systems.SwarmAdvector(swarm=measurementSwarm, velocityField=velocityField, order=2)
# -
figMaterials = vis.Figure(figsize=(1200,600))
figMaterials.append(vis.objects.Points(swarm, materialVariable, pointSize=1.0, rulers=True))
figMaterials.show()
# # Boundary conditions
# +
sideWalls = mesh.specialSets["MaxJ_VertexSet"] + mesh.specialSets["MinJ_VertexSet"]
vertWalls = mesh.specialSets["MaxI_VertexSet"] + mesh.specialSets["MinI_VertexSet"]
botWall = mesh.specialSets["MinJ_VertexSet"]
surfWalls = sideWalls = mesh.specialSets["MaxJ_VertexSet"]
# Dirichlet
condition = uw.conditions.DirichletCondition(variable = velocityField, indexSetsPerDof=(botWall, botWall))
velocityField.data[:] = [0., 0.]
# -
strainRateTensor = fn.tensor.symmetric(velocityField.fn_gradient)
strainRate_2ndInvariantFn = fn.tensor.second_invariant(strainRateTensor)
# # Viscosity, density, buoyancy
# +
minViscosityIceFn = fn.misc.constant(1e+6 / 3.1536e7)
maxViscosityIceFn = fn.misc.constant(1e+15 / 3.1536e7)
viscosityFnAir = fn.misc.constant(1e9 / 3.1536e7)
viscosityFnIceBase = 0.5 * A ** (-1./n) * (strainRate_2ndInvariantFn**((1.-n) / float(n)))
viscosityFnIce = fn.misc.max(fn.misc.min(viscosityFnIceBase, maxViscosityIceFn), minViscosityIceFn)
viscosityMap = {
materialV: viscosityFnIce,
materialA: viscosityFnAir,
}
viscosityFn = fn.branching.map( fn_key=materialVariable, mapping=viscosityMap )
devStressFn = 2.0 * viscosityFn * strainRateTensor
shearStressFn = strainRate_2ndInvariantFn * viscosityFn * 2.0
densityFnAir = fn.misc.constant( 0.001 )
densityFnIce = fn.misc.constant( ice_density )
densityMap = {
materialA: densityFnAir,
materialV: densityFnIce,
}
densityFn = fn.branching.map(fn_key=materialVariable, mapping=densityMap)
buoyancyFn = densityFn * (0., -1.) * 9.81
# -
devStressFn = 2.0 * viscosityFn * strainRateTensor
shearStressFn = strainRate_2ndInvariantFn * viscosityFn * 2.0
# # Solver
# +
stokes = uw.systems.Stokes(
velocityField=velocityField,
pressureField=pressureField,
voronoi_swarm=swarm,
conditions=condition,
fn_viscosity=viscosityFn,
fn_bodyforce=buoyancyFn,
)
solver = uw.systems.Solver(stokes)
solver.set_inner_method("mumps")
surfaceArea = uw.utils.Integral( fn=1.0, mesh=mesh, integrationType='surface', surfaceIndexSet=surfWalls)
surfacePressureIntegral = uw.utils.Integral( fn=pressureField, mesh=mesh, integrationType='surface', surfaceIndexSet=surfWalls)
def calibrate_pressure():
global pressureField
global surfaceArea
global surfacePressureIntegral
(area,) = surfaceArea.evaluate()
(p0,) = surfacePressureIntegral.evaluate()
pressureField.data[:] -= p0 / area
print (f'Calibration pressure {p0 / area}')
# test it out
try:
exec_time = time.time()
solver.solve(nonLinearIterate=True, callback_post_solve=calibrate_pressure)
exec_time = time.time() - exec_time
# print full stats to a file
solver.print_stats()
except:
print("Solver died early..")
exit(0)
print (f'Solving took: {exec_time} seconds')
# -
figVel = vis.Figure(figsize=(1200,600))
figVel.append(vis.objects.Surface(mesh, fn.math.dot(velocityField, velocityField), colourBar=True ))#fn_mask = materialVariable))
figVel.show()
# # Output
# +
#### Filename
outputFile = os.path.join(os.path.abspath("."), "jla"+"1e000"+ ".csv")
print(outputFile)
#### Smooth the stress
meshStressTensor = uw.mesh.MeshVariable(mesh, 3)
projectorStress = uw.utils.MeshVariable_Projection( meshStressTensor, devStressFn, type=0 )
projectorStress.solve()
#### Smooth the velocity
meshVelocity = uw.mesh.MeshVariable(mesh, 2)
projectorV = uw.utils.MeshVariable_Projection( meshVelocity, velocityField, type=0 )
projectorV.solve()
#### Smooth the pressure
meshP = uw.mesh.MeshVariable(mesh, 1)
projectorP = uw.utils.MeshVariable_Projection( meshP, pressureField, type=0 )
projectorP.solve()
#### Points
sub = cell_height
add = cell_height
surf_pos = topo_surf
base_pos = topo_base
#### Get the surface velocity
vxs = meshVelocity.evaluate(surf_pos).transpose()[0]
vys = meshVelocity.evaluate(surf_pos).transpose()[1]
vtots = np.sqrt( vxs*vxs + vys*vys )
#### Get the basal velocity
vxb = meshVelocity.evaluate(base_pos).transpose()[0]
vyb = meshVelocity.evaluate(base_pos).transpose()[1]
vtotb = np.sqrt( vxb*vxb + vyb*vyb )
#### Get the pressure
P = meshP.evaluate(base_pos).squeeze()
#P = pressureField.evaluate(base_pos).squeeze()
#### Get the shearstress
sxy = meshStressTensor.evaluate(base_pos).squeeze()[:,2]
#sxy = devStressFn.evaluate(base_pos).squeeze()[:,2]
#### plot pressure from grid / theoretical / difference
print("DeltaP")
#pyplot.plot((maxY - base_ypos[:]) * 9.81 * 910, color='red')
smoothed_2dg = savgol_filter(P, window_length = 3, polyorder = 2)
#pyplot.plot(P[ind], color='blue')
#pyplot.plot(P - (maxY - base_pos[ind, 1].squeeze()) * 9.81 * 910., color='green')
pyplot.plot(smoothed_2dg, color='black')
pyplot.show()
#### plot vx at surface
print("vxs")
smoothed_2dg = savgol_filter(vtots, window_length = 3, polyorder = 2)
#pyplot.plot(vxs[ind], color='red')
pyplot.plot(smoothed_2dg, color='black')
pyplot.show()
### plot shear stress
print("Shear stress")
smoothed_2dg = savgol_filter(sxy / 1000, window_length = 3, polyorder = 2)
#pyplot.plot (sxz[ind] / 1000., color='red')
pyplot.plot (smoothed_2dg, color='black')
pyplot.show ()
#### output to file
with open(outputFile, "w") as text_file:
for i in range(0, resX+1):
# Ausgabe [x] [y]
textline = str("{:.7f}".format(surf_pos[i, 0] / maxX)) + "\t"
#Ausgabe Geschwindigkeiten Surface[vx] [vy] [vz]
textline += str("{:.7f}".format(vtots[i])) + "\t" + str("{:.7f}".format(vys[i])) + "\t"
#Ausgabe Geschwindigkeiten Basis [vx] [vy]
#textline += str("{:.7f}".format(vxb[i])) + "\t"
# Scherspannung Basis Tensoren [Txz] [Tyz]
textline += str("{:.7f}".format(sxy[i] / 1000.)) + "\t"
# Ausgabe delta p
textline += str("{:.7f}".format( (P[i] - float((surf_pos[i, 1] - base_pos[i, 1]) * 9.81 * 910 )) / 1000)) + "\n"
text_file.write(textline)
# -