-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhoto.lua
657 lines (500 loc) · 16.9 KB
/
hoto.lua
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
-- associated with Branch-Generator
-- 7/1
-- load pre-implemented lua functions
ug_load_script("ug_util.lua")
ug_load_script("util/load_balancing_util.lua")
AssertPluginsLoaded({"neuro_collection"})
InitUG(3, AlgebraType("CPU", 1))
EnableLUA2C(true) -- speed up evaluation of lua functions by c program
-- EnableLUA2VM(true)
print(GetLogAssistant():get_debug_IDs()) --output options
SetDebugLevel(debugID.LIB_DISC_NEWTON,2 )
-------------------------------------
-- parse command line parameters ---
-------------------------------------
-- choice of grid name
gridName = util.GetParam("-grid", "modelDendrite3d_ssr.ugx")
-- refinements (global and at ERM)
numGlobRefs = util.GetParamNumber("-numGlobRefs", 1)
numERMRefs = util.GetParamNumber("-numERMRefs", 1)
-- which ER mechanisms are to be activated?
setting = util.GetParam("-setting", "all")
setting = string.lower(setting)
validSettings = {}
validSettings["all"] = 0;
validSettings["none"] = 0;
validSettings["ip3r"] = 0;
validSettings["ryr"] = 0;
if (validSettings[setting] == nil) then
error("Unknown setting " .. setting)
end
-- densities
ryrDensity = util.GetParamNumber("-ryrDensity", 0.86)
pmcaDensity = util.GetParamNumber("-pmcaDensity", 500)
ncxDensity = util.GetParamNumber("-ncxDensity", 15)
-- buffer
totalBuffer = util.GetParamNumber("-totBuf", 4*40.0e-6)
-- choice of algebra
-- useBlockAlgebra = util.HasParamOption("-block")
-- choice of solver setup
solverID = util.GetParam("-solver", "GMG")
solverID = string.upper(solverID)
validSolverIDs = {}
validSolverIDs["GMG"] = 0
validSolverIDs["GS"] = 0
validSolverIDs["ILU"] = 0
if (validSolverIDs[solverID] == nil) then
error("Unknown solver identifier " .. solverID)
end
-- error tolerance for Limex iteration
tol = util.GetParamNumber("-tol", 0.01)
-- specify "-verbose" to output linear solver convergence
verbose = util.HasParamOption("-verbose")
-- parameters for instationary simulation
dt = util.GetParamNumber("-dt", 1e-2)
endTime = util.GetParamNumber("-endTime", 2.0e-2)
-- choose outfile directory
outDir = util.GetParam("-outName", "wave3d")
outDir = outDir .. "/"
-- specify -vtk to generate vtk output
generateVTKoutput = util.HasParamOption("-vtk")
pstep = util.GetParamNumber("-pstep", dt, "plotting interval")
-------------------------
-- problem constants --
-------------------------
-- setting-dependent variables
withIP3R = true
withRyR = true
withSERCAandLeak = true
if setting == "none" then
withIP3R = false
withRyR = false
withSERCAandLeak = false
end
if setting == "ip3r" then
withRyR = false
end
if setting == "ryr" then
withIP3R = false
end
-- total cytosolic calbindin concentration
-- (four times the real value in order to simulate four binding sites in one)
totalClb = totalBuffer
-- diffusion coefficients
D_cac = 220.0
D_cae = 220.0
D_ip3 = 280.0
D_clb = 20.0
-- calbindin binding rates
k_bind_clb = 27.0e06
k_unbind_clb = 19
-- initial concentrations
ca_cyt_init = 5.0e-08
ca_er_init = 2.5e-4
ip3_init = 4.0e-8
clb_init = totalClb / (k_bind_clb/k_unbind_clb*ca_cyt_init + 1)
-- IP3 constants
reactionRateIP3 = 0.11
equilibriumIP3 = 4.0e-08
reactionTermIP3 = -reactionRateIP3 * equilibriumIP3
-- ER densities
IP3Rdensity = 17.3
local v_s = 6.5e-27 -- V_S param of SERCA pump
local k_s = 1.8e-7 -- K_S param of SERCA pump
local j_ip3r = 3.7606194166520605e-23 -- single channel IP3R flux (mol/s) - to be determined via gdb
local j_ryr = 1.1201015633466695e-21 -- single channel RyR flux (mol/s) - to be determined via gdb
-- ryr1: 1.1204582669024472e-21
---[[
-- equilibration using SERCA
leakERconstant = 3.8e-17
local j_leak = ca_er_init-ca_cyt_init -- leak proportionality factor
SERCAfluxDensity = leakERconstant * j_leak
if withIP3R then
SERCAfluxDensity = SERCAfluxDensity + IP3Rdensity * j_ip3r
end
if withRyR then
SERCAfluxDensity = SERCAfluxDensity + ryrDensity * j_ryr
end
SERCAdensity = SERCAfluxDensity / (v_s/(k_s/ca_cyt_init+1.0)/ca_er_init)
if (SERCAdensity < 0) then error("SERCA flux density is outward for these density settings!") end
--]]
--[[
-- equilibration using leakage
SERCAdensity = 1973.0
SERCAflux = v_s / (k_s / ca_cyt_init + 1.0) / ca_er_init
netEquilFlux = SERCAdensity*SERCAflux
if withIP3R then
netEquilFlux = netEquilFlux - IP3Rdensity * j_ip3r
end
if withRyR then
netEquilFlux = netEquilFlux - ryrDensity * j_ryr
end
leakERconstant = netEquilFlux / (ca_er_init - ca_cyt_init)
if (leakERconstant < 0) then
error("ER leakage flux density is outward for these density settings!")
end
--]]
-- PM densities
vdccDensity = 0.0 -- 1.0
leakPMconstant = pmcaDensity * 6.9672131147540994e-24 -- single pump PMCA flux (mol/s)
+ ncxDensity * 6.7567567567567566e-23 -- single pump NCX flux (mol/s)
--+ vdccDensity * (-1.5752042094823713e-25) -- single channel VGCC flux (mol/s)
-- *1.5 // * 0.5 for L-type // T-type
if (leakPMconstant < 0) then error("PM leak flux is outward for these density settings!") end
-- activation pattern
caEntryDuration = 0.001
function synCurrentDensityCa(x, y, z, t, si)
-- single spike (~1200 ions)
local influx
if t <= caEntryDuration
then influx = 2.5e-3 * (1.0 - t/caEntryDuration)
else influx = 0.0
end
return influx
end
ip3EntryDelay = 0.000
ip3EntryDuration = 0.2
function synCurrentDensityIP3(x, y, z, t, si)
local influx
if t > ip3EntryDelay and t <= ip3EntryDelay+ip3EntryDuration
then influx = 7.5e-5 * (1.0 - t/ip3EntryDuration)
else influx = 0.0
end
return influx
end
-------------------------------
-- setup approximation space --
-------------------------------
-- load domain
reqSubsets = {"cyt", "er", "pm", "erm", "meas#1", "meas#2"}
dom = util.CreateDomain(gridName, numRefs, reqSubsets)
cytVol = "cyt"
erVol = "er"
plMem = "pm"
plMem_vec = {"pm"}
erMem = "erm"
erMemVec = {"erm"}
bdry = "meas#1, meas#2"
outerDomain = cytVol .. ", " .. plMem .. ", " .. erMem .. ", ".. bdry
innerDomain = erVol .. ", " .. erMem
-- create approximation space
approxSpace = ApproximationSpace(dom)
approxSpace:add_fct("ca_cyt", "Lagrange", 1, outerDomain)
approxSpace:add_fct("ca_er", "Lagrange", 1, innerDomain)
approxSpace:add_fct("clb", "Lagrange", 1, outerDomain)
approxSpace:add_fct("ip3", "Lagrange", 1, outerDomain)
approxSpace:add_fct("o2", "Lagrange", 1, "erm")
approxSpace:add_fct("c1", "Lagrange", 1, "erm")
approxSpace:add_fct("c2", "Lagrange", 1, "erm")
approxSpace:init_levels()
approxSpace:init_surfaces()
approxSpace:init_top_surface()
approxSpace:print_layout_statistic()
approxSpace:print_statistic()
if useBlockAlgebra then
OrderCuthillMcKee(approxSpace, true)
end
-- in parallel environments: domain distribution
-- balancer.partitioner = "parmetis"
balancer.partitioner = "dynBisection"
balancer.staticProcHierarchy = true
balancer.firstDistLvl = -1
balancer.redistSteps = 0
-- balancer.parallelElementThreshold = 4
balancer.ParseParameters()
balancer.PrintParameters()
loadBalancer = balancer.CreateLoadBalancer(dom)
if loadBalancer ~= nil then
loadBalancer:enable_vertical_interface_creation(solverID == "GMG")
if balancer.partitioner == "parmetis" then
mu = ManifoldUnificator(dom)
mu:add_protectable_subsets("erm")
cdgm = ClusteredDualGraphManager()
cdgm:add_unificator(SiblingUnificator())
cdgm:add_unificator(mu)
balancer.defaultPartitioner:set_dual_graph_manager(cdgm)
end
balancer.Rebalance(dom, loadBalancer)
loadBalancer:estimate_distribution_quality()
loadBalancer:print_quality_records()
if balancer.partitioner == "parmetis" then
print("Edge cut on base level: "..balancer.defaultPartitioner:edge_cut_on_lvl(0))
end
end
-- 见err_est_simple_test
-- balancer.RefineAndRebalanceDomain(dom, numRefs, loadBalancer)
--[[
refiner = HangingNodeDomainRefiner(dom)
for i = 1, numGlobRefs do
mark_global(refiner, dom)
-- was mark_global(refiner, approxSpace)
refiner:refine()
end
--]]
--[[
if numGlobRefs > 0 then
local refiner = GlobalDomainRefiner(dom)
for i = 1, numGlobRefs do
refiner:refine()
end
end
--]]
print(dom:domain_info():to_string())
SaveGridHierarchyTransformed(dom:grid(), dom:subset_handler(), outDir .. "grid/refined_grid_hierarchy_p" .. ProcRank() .. ".ugx", 1.0)
SaveParallelGridLayout(dom:grid(), outDir .. "grid/parallel_grid_layout_p"..ProcRank()..".ugx", 1.0)
--------------------------
-- setup discretization --
--------------------------
-- diffusion --
diffCaCyt = ConvectionDiffusion("ca_cyt", cytVol, "fv1")
diffCaCyt:set_diffusion(D_cac)
-- scaling 2
diffCaER = ConvectionDiffusion("ca_er", "er", "fv1")
diffCaER:set_diffusion(D_cae)
diffClb = ConvectionDiffusion("clb", cytVol, "fv1")
diffClb:set_diffusion(D_clb)
diffIP3 = ConvectionDiffusion("ip3", cytVol, "fv1")
diffIP3:set_diffusion(D_ip3)
diffIP3:set_reaction_rate(reactionRateIP3)
diffIP3:set_reaction(reactionTermIP3)
-- buffering --
discBuffer = BufferFV1(cytVol) -- where buffering occurs
discBuffer:add_reaction(
"clb", -- the buffering substance
"ca_cyt", -- the buffered substance
totalClb, -- total amount of buffer
k_bind_clb, -- binding rate constant
k_unbind_clb -- unbinding rate constant
)
-- er membrane transport systems
ip3r = IP3R({"ca_cyt", "ca_er", "ip3"})
ip3r:set_scale_inputs({1e3,1e3,1e3})
ip3r:set_scale_fluxes({1e15}) -- from mol/(um^2 s) to (mol um)/(dm^3 s)
ryr = RyRImplicit({"ca_cyt", "ca_er", "o2", "c1", "c2"}, {"erm"})
ryr:set_scale_inputs({1e3, 1e3, 1.0, 1.0, 1.0})
ryr:set_scale_fluxes({1e15}) -- from mol/(um^2 s) to (mol um)/(dm^3 s)
serca = SERCA({"ca_cyt", "ca_er"})
serca:set_scale_inputs({1e3,1e3})
serca:set_scale_fluxes({1e15}) -- from mol/(um^2 s) to (mol um)/(dm^3 s)
leakER = Leak({"ca_er", "ca_cyt"})
leakER:set_scale_inputs({1e3,1e3})
leakER:set_scale_fluxes({1e3}) -- from mol/(m^2 s) to (mol um)/(dm^3 s)
discIP3R = MembraneTransportFV1(erMem, ip3r)
discIP3R:set_density_function(IP3Rdensity)
discRyR = MembraneTransportFV1(erMem, ryr)
discRyR:set_density_function(ryrDensity)
discSERCA = MembraneTransportFV1(erMem, serca)
discSERCA:set_density_function(SERCAdensity)
--discERLeak = MembraneTransportFv1(erMem, leakER)
discERLeak = MembraneTransportFV1(erMem, leakER)
discERLeak:set_density_function(1e12*leakERconstant/(1e3)) -- from mol/(um^2 s M) to m/s
-- plasma membrane transport systems
pmca = PMCA({"ca_cyt", ""})
pmca:set_constant(1, 1.0)
pmca:set_scale_inputs({1e3,1.0})
pmca:set_scale_fluxes({1e15}) -- from mol/(um^2 s) to (mol um)/(dm^3 s)
ncx = NCX({"ca_cyt", ""})
ncx:set_constant(1, 1.0)
ncx:set_scale_inputs({1e3,1.0})
ncx:set_scale_fluxes({1e15}) -- from mol/(um^2 s) to (mol um)/(dm^3 s)
leakPM = Leak({"", "ca_cyt"})
leakPM:set_constant(0, 1.0)
leakPM:set_scale_inputs({1.0,1e3})
leakPM:set_scale_fluxes({1e3}) -- from mol/(m^2 s) to (mol um)/(dm^3 s)
discPMCA = MembraneTransportFV1("pm", pmca)
discPMCA:set_density_function(pmcaDensity)
discNCX = MembraneTransportFV1("pm", ncx)
discNCX:set_density_function(ncxDensity)
discPMLeak = MembraneTransportFV1("pm", leakPM)
discPMLeak:set_density_function(1e12*leakPMconstant / (1.0-1e3*ca_cyt_init))
-- synaptic activity
synapseInfluxCa = UserFluxBoundaryFV1("ca_cyt", "meas#1")
synapseInfluxCa:set_flux_function("synCurrentDensityCa")
synapseInfluxIP3 = UserFluxBoundaryFV1("ip3", "meas#1")
synapseInfluxIP3:set_flux_function("synCurrentDensityIP3")
-- domain discretization --
domDisc = DomainDiscretization(approxSpace)
domDisc:add(diffCaCyt)
domDisc:add(diffCaER)
domDisc:add(diffClb)
domDisc:add(diffIP3)
domDisc:add(discBuffer)
if withIP3R then
domDisc:add(discIP3R)
end
if withRyR then
domDisc:add(discRyR)
domDisc:add(ryr) -- also add ryr as elem disc (for state variables)
end
if withSERCAandLeak then
domDisc:add(discSERCA)
domDisc:add(discERLeak)
end
domDisc:add(discPMCA)
domDisc:add(discNCX)
domDisc:add(discPMLeak)
domDisc:add(synapseInfluxCa)
if withIP3R then
domDisc:add(synapseInfluxIP3)
end
-- setup time discretization --
timeDisc = ThetaTimeStep(domDisc)
timeDisc:set_theta(1.0) -- 1.0 is implicit Euler
-- create operator from discretization
op = AssembledOperator()
op:set_discretization(timeDisc)
op:init()
------------------
-- solver setup --
------------------
-- debug writer
dbgWriter = GridFunctionDebugWriter(approxSpace)
dbgWriter:set_base_dir(outDir)
dbgWriter:set_vtk_output(false)
-- biCGstab --
convCheck = ConvCheck()
convCheck:set_minimum_defect(1e-50)
convCheck:set_reduction(1e-8)
convCheck:set_verbose(verbose)
if (solverID == "ILU") then
bcgs_steps = 1000
ilu = ILU()
ilu:set_sort(true)
bcgs_precond = ilu
elseif (solverID == "GS") then
bcgs_steps = 1000
bcgs_precond = GaussSeidel()
else -- (solverID == "GMG")
gmg = GeometricMultiGrid(approxSpace)
gmg:set_discretization(timeDisc)
gmg:set_base_level(0)
gmg:set_gathered_base_solver_if_ambiguous(true)
-- treat SuperLU problems with Dirichlet constraints by using constrained version
gmg:set_base_solver(LU())
smoother = GaussSeidel()
gmg:set_smoother(smoother)
gmg:set_smooth_on_surface_rim(true)
gmg:set_cycle_type(1)
gmg:set_num_presmooth(3)
gmg:set_num_postsmooth(3)
--gmg:set_rap(true)
--gmg:set_debug(GridFunctionDebugWriter(approxSpace))
bcgs_steps = 1000
bcgs_precond = gmg
end
convCheck:set_maximum_steps(bcgs_steps)
bicgstabSolver = BiCGStab()
bicgstabSolver:set_preconditioner(bcgs_precond)
bicgstabSolver:set_convergence_check(convCheck)
--bicgstabSolver:set_debug(dbgWriter)
--- non-linear solver ---
-- convergence check
newtonConvCheck = CompositeConvCheck(approxSpace, 10, 1e-17, 1e-08)
--newtonConvCheck:set_component_check("ca_cyt, ca_er, clb, ip3", 1e-18, 1e-10)
newtonConvCheck:set_verbose(true)
newtonConvCheck:set_time_measurement(true)
--newtonConvCheck:set_adaptive(true)
-- Newton solver
newtonSolver = NewtonSolver()
newtonSolver:set_linear_solver(bicgstabSolver)
newtonSolver:set_convergence_check(newtonConvCheck)
newtonSolver:set_debug(dbgWriter)
newtonSolver:init(op)
-------------
-- solving --
-------------
-- get grid function
u = GridFunction(approxSpace)
-- set initial value
InterpolateInner(ca_cyt_init, u, "ca_cyt", 0.0)
InterpolateInner(ca_er_init, u, "ca_er", 0.0)
InterpolateInner(clb_init, u, "clb", 0.0)
InterpolateInner(ip3_init, u, "ip3", 0.0)
ryr:calculate_steady_state(u)
-- timestep in seconds
dtmin = 1e-9
dtmax = 1e-2
time = 0.0
step = 0
-- initial vtk output
if (generateVTKoutput) then
out = VTKOutput()
out:print(outDir .. "vtk/solution", u, step, time)
end
dtStart = util.GetParamNumber("-dtStart", dt)
function log2(x)
return math.log(x)/math.log(2)
end
startLv = math.ceil(log2(dt/dtStart))
dtStartNew = dt / math.pow(2, startLv)
if (math.abs(dtStartNew-dtStart)/dtStart > 1e-5) then
print("dtStart argument ("..dtStart..") was not admissible;" ..
"taking "..dtStartNew.." instead.")
end
dt = dtStartNew
-- create new grid function for old value
uOld = u:clone()
-- store grid function in vector of old solutions
solTimeSeries = SolutionTimeSeries()
solTimeSeries:push(uOld, time)
-- start iterating in time
min_dt = dt / math.pow(2,15)
cb_interval = 10
lv = startLv
levelUpDelay = 0
cb_counter = {}
for i = 0, startLv do cb_counter[i] = 0 end
while endTime-time > 0.001*dt do
print("++++++ POINT IN TIME " .. math.floor((time+dt)/dt+0.5)*dt .. "s BEGIN ++++++")
-- setup time Disc for old solutions and timestep
timeDisc:prepare_step(solTimeSeries, dt)
-- apply newton solver
if newtonSolver:apply(u) == false
then
-- in case of failure:
print ("Newton solver failed at point in time " .. time .. " with time step " .. dt)
dt = dt/2
lv = lv + 1
VecScaleAssign(u, 1.0, solTimeSeries:latest())
-- halve time step and try again unless time step below minimum
if dt < min_dt
then
print ("Time step below minimum. Aborting. Failed at point in time " .. time .. ".")
time = endTime
else
print ("Trying with half the time step...")
cb_counter[lv] = 0
end
else
-- update new time
time = solTimeSeries:time(0) + dt
-- update check-back counter and if applicable, reset dt
cb_counter[lv] = cb_counter[lv] + 1
while cb_counter[lv] % (2*cb_interval) == 0 and lv > 0 and (time >= levelUpDelay or lv > startLv) do
print ("Doubling time due to continuing convergence; now: " .. 2*dt)
dt = 2*dt;
lv = lv - 1
cb_counter[lv] = cb_counter[lv] + cb_counter[lv+1] / 2
cb_counter[lv+1] = 0
end
-- plot solution every pstep seconds
if (generateVTKoutput) then
if math.abs(time/pstep - math.floor(time/pstep+0.5)) < 1e-5 then
out:print(outDir .. "vtk/solution", u, math.floor(time/pstep+0.5), time)
end
end
-- get oldest solution
oldestSol = solTimeSeries:oldest()
-- copy values into oldest solution (we reuse the memory here)
VecScaleAssign(oldestSol, 1.0, u)
-- push oldest solutions with new values to front, oldest sol pointer is popped from end
solTimeSeries:push_discard_oldest(oldestSol, time)
print("++++++ POINT IN TIME " .. math.floor(time/dt+0.5)*dt .. "s END ++++++++");
end
end
if (generateVTKoutput) then
out:write_time_pvd(outDir .. "vtk/solution", u)
end
if doProfiling then
WriteProfileData(outDir .."pd.pdxml")
end